Nice! Read the few sections below to understand how this project is structured and how to implement new features.
This section explains how to create new templates and plugins. It also contains references about used packages, global project structure and list which contributions on are accepted.
Thanks for your interest in metrics and wanting to help it growing!
Review below which contributions are accepted:
Section | Addition | Editions | Notes |
---|---|---|---|
🧩 Plugins | ✔️ | ✔️ |
|
🖼️ Templates | ❌ | 〽️ |
|
🧪 Tests | ✔️ | ✔️ |
|
🧱 Core | ❌ | 〽️ |
|
🗃️ Repository | ❌ | ❌ |
|
Legend
- ✔️: Contributions welcomed!
- 〽️: Contributions welcomed, but must be discussed first
- ❌: Only maintainers can manage these files
Before working on something, ensure that it isn't already in progress and that it will not duplicate any open pull requests (including drafts). If you're unsure, always open an issue first to get insights and gather feedback.
Even if your changes don't get merged in lowlighter/metrics, please don't be too sad. Metrics is designed to be highly customizable, so you can always decide to generate metrics on your forked repository 🙂!
🗂️ Project structure
This section explain how metrics is structured.
source/app/metrics/
contains core metrics filessource/app/action/
contains GitHub action filesindex.mjs
contains GitHub action entry pointaction.yml
contains GitHub action descriptor
source/app/web/
contains web instance filesindex.mjs
contains web instance entry pointinstance.mjs
contains web instance source codesettings.example.json
contains web instance settings examplestatics/
contains web instance static filesapp.js
contains web instance client source codeapp.placeholder.js
contains web instance placeholder mocked data
source/app/mocks/
contains mocked data filesapi/
contains mocked api dataaxios/
contains external REST APIs mocked datagithub/
contains mocked GitHub api data
index.mjs
contains mockers
source/plugins/
contains source code of pluginsREADME.md
contains plugin documentationmetadata.yml
contains plugin metadataindex.mjs
contains plugin source codequeries/
contains plugin GraphQL queries
source/templates/
contains templates filesREADME.md
contains template documentationmetadata.yml
contains template metadataimage.svg
contains template image used to render metricsstyle.css
contains style used to render metricsfonts.css
contains additional fonts used to render metricstemplate.mjs
contains template source code
tests/
contains testsmetrics.test.js
contains metrics testers
Dockerfile
contains docker instructions used to build metrics imagepackage.json
contains dependencies and command line aliases
📦 Packages
Below is a list of used packages.
- express/express.js and expressjs/compression
- To serve, compute and render a GitHub user's metrics
- nfriedly/express-rate-limit
- To apply rate limiting on server and avoid spams and hitting GitHub API's own rate limit
- octokit/graphql.js and octokit/rest.js
- To perform request to GitHub GraphQL API and GitHub REST API
- mde/ejs
- To render SVG images
- ptarjan/node-cache
- To cache generated content
- oliver-moran/jimp, foliojs/png.js and eugeneware/gifencoder
- To process images transformations
- svg/svgo
- To optimize generated SVG
- axios/axios
- To make HTTP/S requests
- actions/toolkit
- To build the GitHub Action
- vuejs/vue and egoist/vue-prism-component + prismjs/prism
- To display server application
- puppeteer/puppeteer
- To scrape the web
- marudor/libxmljs2 and chrisbottin/xml-formatter
- To format, test and verify SVG validity
- facebook/jest and nodeca/js-yaml
- For unit testing
- marak/faker.js
- For mocking data
- steveukx/git-js
- For simple git operations
- twitter/twemoji-parser
- To parse emojis and replace them by twemojis
- jshemas/openGraphScraper
- To retrieve open graphs metadata
- panosoft/node-chartist and gionkunz/chartist-js
- To display embed SVG charts
- rbren/rss-parser
- To parse RSS streams
🖼️ Templates
Templates require you to be comfortable with HTML, CSS and JavaScript (EJS flavored).
Metrics does not really accept new default templates in order to avoid bloating main repository (and it also makes maintaining easier upon new plugins releases).
Redesigns of existing templates are also typically avoided to keep visual consistency across all versions, but fear not! Users will still be able to use your custom templates thanks to community templates!
If you make something awesome, don't hesitate to share it!
💬 Creating a new template from scratch
Find a cool name for your template and run:
npm run quickstart -- template <template_name>
It will create a new folder in source/templates
with the following files:
- A
README.md
to describe your template and document it - An
image.svg
with base structure for rendering - A
metadata.yml
which list templates attributes and supported formats - A
partials/
folder where you'll be able to implement parts of your template- A
partials/_.json
with a JSON array listing these parts in the order you want them displayed (unless overridden by user withconfig_order
option)
- A
If needed, you can also create the following optional files:
- A
fonts.css
containing base64 encoded custom fonts - A
styles.css
with custom CSS that'll style your template - A
template.mjs
with additional data processing and formatting at template-level- When your template is used through
setup_community_templates
on official releases, this is disabled by default unless user trusts it by appending+trust
at the end of source - You can specify the default
template.mjs
fallback by fillingextends
key in yourmetadata.yml
(defaults to"classic"
template)
- When your template is used through
If inexistent, these will fallback to classic
template files.
Templates are auto-loaded based on their folder existence, so there's no need to register them somewhere.
💬 Creating image.svg
and partials
The base structure for rendering looks like below:
<svg xmlns="http://www.w3.org/2000/svg" width="480" height="99999" class="<%= !animated ? 'no-animations' : '' %>">
<defs><style><%= fonts %></style></defs>
<style><%= style %></style>
<foreignObject x="0" y="0" width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink">
<% for (const partial of [...partials]) { %>
<%- await include(`partials/${partial}.ejs`) %>
<% } %>
<div id="metrics-end"></div>
</div>
</foreignObject>
</svg>
fonts
andstyle
variables will both be populated with the same content as yourfonts.css
andstyles.css
files- (or those of
classic
template files if inexistent)
- (or those of
partials
variable will be populated withpartials/_.json
content- Main loop will iterate over this array to include all defined partials
#metrics-end
is a special HTML tag which must remain at the bottom of SVG template- This is used to compute dynamically height through a puppeteer headless instance
- SVG height must also be set to a high number so it doesn't get cropped accidentally while puppeteer compute element.getBoundingClientRect()
As you can see, we exploit the fact that SVG images are able to render HTML and CSS content so designing partials is the same as creating static web pages.
EJS framework is also used to programmatically create content through the help of templating tags (<% %>
).
💬 Filling metadata.yml
metadata.yml
is an optional file which describes what account types are allowed, which formats are supported, etc.
Here's an example:
name: "🖼️ Template name"
extends: classic # Fallback to "classic" template "template.mjs" if not trusted
index: ~ # Leave as it (this is used to order plugins on metrics README.md)
supports:
- user # Support users account
- organization # Support organizations account
- repository # Support repositories metrics
formats:
- svg # Support SVG output
- png # Support PNG output
- jpeg # Support JPEG output
- json # Support JSON output
- markdown # Support markdown output
- markdown-pdf # Support PDF output
Core plugin will automatically check whether template supports given account or repository and output format and will throw an error in case they aren't compatible.
💬 Adding custom fonts
⚠️ This significantly increases rendered metrics filesize and thus not recommended
When using this feature, you should aim to restrict used charset to avoid including useless data.
Here's a quick step-by-step tutorial to create base64 encoded fonts:
-
- Find a font on fonts.google.com
- Select regular, bold, italic and bold+italic fonts
- Open
embed
tab and extracthref
-
- Open extracted
href
in a browser and append&text=
parameter with list of used characters
- e.g.
&text=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
- Open extracted
-
- Download each font file from urls present in generated stylesheet
-
- Convert them into base64 with
woff
format on transfonter.org
- Convert them into base64 with
-
- Download archive and extract it
-
- Copy content of generated stylesheet to
fonts.css
- Copy content of generated stylesheet to
-
- Update your template
style.css
to use the new font
- Update your template
🧩 Plugins
Plugins lets add new features with additional content to rendered metrics and are coded with JavaScript modules.
New plugins are welcomed, but maintainers have no obligation to maintain them. It means you (as author) may be notified about open issues regarding related plugin.
💬 Creating a new plugin from scratch
Find a cool name for your plugin and run:
npm run quickstart -- plugin <plugin_name>
It will create a new folder in source/plugins
with the following files:
- A
README.md
to describe your plugin and document it - An
index.mjs
with minimal plugin code - A
metadata.yml
which list plugin attributes and inputs - A
tests.yml
for unit tests
Here are some guidelines to follow about plugins:
- They should never be dependent on output produced by other plugins (though allowed to re-use core and base data)
- It allows parallelization of plugins execution
- It avoids creating inter-dependencies which makes it confusing for both developers and users
- Use of new external dependencies should be avoided
- Adding new libraries to use only ~5% of its possibilities is just a waste
- For APIs, most of the time a few HTTP calls instead of installing a full SDK wrapper is more than sufficient
imports
probably already contains a library or a function that can help you achieving what you want- It also add more unstability since metrics may break upon external API breaking changes
- Adding new libraries to use only ~5% of its possibilities is just a waste
- Use of raw commands (spawning sub-process) should be avoided unless needed
- Errors should be handled gracefully with error messages
- Plugins arguments should NEVER be directly edited from inside a plugin
- These are used by all plugins, including core and base so it would create unattended side effects
- They should include customization options (limit entries, detailed output, etc.) for end user
- Be sure to follow other options "lexical fields" to keep consistency and a certain abstraction level. For example use
my_plugin_user
and notmy_plugin_username
ormy_plugin_login
- Options should only affect content, not styling
- Be sure to follow other options "lexical fields" to keep consistency and a certain abstraction level. For example use
You'll also need to an unused emoji to use as your plugin icon.
Plugins are auto-loaded based on their folder existence, so there's no need to register them somewhere.
💬 Implementing index.mjs
and gathering new data from external APIs
Default exported function in index.mjs
will receive the following inputs:
login
, set to GitHub loginq
, with query parameters (formatted with dots (.
) instead of underscores (_
) and withoutplugin_
prefix)imports
, with libraries and utilitariesimports.url
for NodeJSurl
libraryimports.os
for NodeJSos
libraryimports.fs
for NodeJSfs
libraryimports.paths
for NodeJSpaths
libraryimports.util
for NodeJSutil
libraryimports.axios
for axios/axiosimports.puppeteer
for puppeteer/puppeteerimports.run
is an helper to run raw commandimports.shuffle
is an helper to shuffle arrayimports.imgb64
is an helper to download and resize an image into base64imports.__module
is an helper to find__dirname
from a moduleimport.meta.url
- And more...
data
andcomputed
, with all data gathered from core and basegraphql
andrest
, with authenticated octokit clients (for GitHub APIs)queries
, with autoloaded GraphQL queries and replacersaccount
, set to account type ("user" or "organization")
Second input contains configuration settings from settings.json (which is mostly used by web instances) and also all user inputs of type token
.
As said previously, plugins arguments should NEVER be directly edited from it, since these are used by all plugins, including core and base so it would create unattended side effects.
As for data gathering related to:
- GitHub, use
graphql
(for GraphQL API) orrest
REST API - Third-Party services, use
imports.axios
to make APIs calls - In last resort, use
imports.puppeteer
For GraphQL queries, use queries
which will auto-load all queries from queries
directory and will lets you create custom queries on the fly.
For example:
//Calling this
await graphql(queries.myplugin.myquery({login:"github-user", account:"user"}))
//With this in source/plugins/myplugin/queries/myquery.graphql
query MyQuery {
$account(login: "$login") {
name
}
}
//Will have the same result as calling this
await graphql(`
query MyQuery {
user(login: "github-user") {
name
}
}
`)
💬 Filling metadata.yml
metadata.yml
is a mandatory file which describes what inputs are allowed, which entities are supported, etc.
Here's an example:
name: "🧩 Plugin name (with emoji icon)"
cost: Estimates how many GitHub requests is used during plugin execution ("N/A" for Third-Party services)
categorie: github # Plugin categorie ("github", "social" or "other")
index: ~ # Leave as it (this is used to order plugins on metrics README.md)
supports:
- user # Support users account
- organization # Support organizations account
- repository # Support repositories metrics
inputs:
# A comment detailing input purposes
# An input must have at least a "description" and a "default" (used to generated GitHub Action `action.yml`)
plugin_input:
description: Short description (few words)
type: boolean
default: no
Because of GitHub Actions limitations, only strings and numbers are actually supported by action.yml
inputs.
Metrics apply additional post-processing to handle inputs.
Supported input types are boolean
, string
, number
, array
and json
.
- Allowed values for
string
andarray
types may be restricted usingvalues
attribute- Special default values
.user.login
,.user.twitter
and.user.website
will respectively be replaced by user's login, Twitter username and website (not available whentoken
is set toNOT_NEEDED
by user)
- Special default values
- Lower and upper limits for
number
may be set usingmin
andmax
attribute - Array
format
attribute define how string should be splitted (comma-separated
orspace-separated
)
You can additionally specify an example
which will also be used in web instance input placeholder.
Inputs will be available through imports.metadata.plugins.*.inputs
with correct typing and default values (plugin_
prefix will be dropped, and all underscored (_
) will be changed to dots (.
) instead):
//Load inputs
let {limit, "limit.field":limit_field} = imports.metadata.plugins.myplugin.inputs({data, account, q})
Additionally, if account
type isn't supported, this method will automatically prevent your plugin from running by throwing an error.
💬 Creating a new partial
In templates you want to support, create a new .ejs
file in partials
folder and paste the following for a quick start:
<% if (plugins./* your plugin name */) { %>
<section>
<div class="row">
<% if (plugins./* your plugin name */.error) { %>
<section>
<div class="field error">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16"><path fill-rule="evenodd" d="M2.343 13.657A8 8 0 1113.657 2.343 8 8 0 012.343 13.657zM6.03 4.97a.75.75 0 00-1.06 1.06L6.94 8 4.97 9.97a.75.75 0 101.06 1.06L8 9.06l1.97 1.97a.75.75 0 101.06-1.06L9.06 8l1.97-1.97a.75.75 0 10-1.06-1.06L8 6.94 6.03 4.97z"></path></svg>
<%= plugins./* your plugin name */.error.message %>
</div>
</section>
<% } else { %>
<section>
<%# Do stuff in there -%>
</section>
<% } %>
</div>
</section>
<% } %>
- First conditional statement ensures that partial is displayed only when plugin is enabled
- Nested conditional statement check plugin output
- If it failed, an error message instead will be displayed instead
- If it succeeded, second section in render.
Additional CSS rules may be added to style.css
of edited template, but ensure it does not break other plugins rendering.
💬 Redacting plugin's README.md
README.md
is a mandatory file which contains basic documentation about your plugin.
It should contain:
- A brief description of plugin's purpose
- A table including demos (this is automatically extracted upon metrics
README.md
auto-generation)- Multiple demo are allowed, but if they're too big, please embed them in
<detail></details>
tags - Note that the
<img width="900" height="1" alt="">
must not be deleted, it is used to fill table height
- Multiple demo are allowed, but if they're too big, please embed them in
- Additional documentation on how to setup, token creation, etc.
- A workflow example, with all available options
### 🧩 Your plugin name
<table>
<td align="center">
<img src="">
<img width="900" height="1" alt="">
</td>
</table>
#### ℹ️ Examples workflows
[➡️ Available options for this plugin](metadata.yml)
'''yaml
- uses: lowlighter/metrics@latest
with:
# ... other options
plugin_custom: yes
'''
💬 Fast prototyping and testing
The easiest way to test and prototype your plugin is to setup a web instance. See documentation for more informations about that.
Open a browser and try to generate metrics with new your plugin enabled to see if it works as expected:
http://localhost:3000/your-github-login?base=0&your-plugin-name=1
Once ready, define test cases in your plugin directory tests.yml
.
These tests will be run with:
- Metrics action
- Metrics web instance
- Metrics web instance placeholder (rendered by browser)
Most APIs (including GitHub) usually have a rate-limit to ensure quality of service.
This is why APIs output must be mocked and added in source/app/mocks/api/
in order for tests to be able to be performed anytime.
Files from these directories are auto-loaded, so you just need to create new functions (see other mocked data for examples).
Finally, edit source/app/web/statics/app.placeholder.js to add mocked result (but this time from metrics server) so users will be able to render placeholder preview in web instance.
💬 Submitting a pull request
Ensure that:
metadata.yml
is correctly filledtests.yml
has defined test casesmocks/api
has mocked data for external APIsapp.placeholder.js
has been updated with mocked plugin outputREADME.md
of plugin explain how plugin works<table>
tag MUST remain present (along with<img width="900" height="1" alt="">
) as these are extracted for globalREADME.md
npm run linter
outputs no errorsnpm test
is successful
Use config.output
option to render a PNG version of your plugin:
http://localhost:3000/your-github-login?base=0&your-plugin-name=1&config.output=png
And finally open a new pull request and ensure that all builds succeed.
Additionally, you can test your changes with GitHub action by using your fork in your workflow:
- uses: github-login/metrics@feat-my-plugin
with:
# options...
Global README.md
, plugins/README.md
, templates/README.md
, action.yml
and settings.example.json
are automatically rebuild by GitHub action, do not edit them manually.
This section explore some topics which explain globally how metrics was designed and how it works.
💬 Creating SVGs images on-the-fly
Metrics actually exploit the possibility of integrating HTML and CSS into SVGs, so basically creating these images is as simple as designing static web pages. It can even handle animations and transparency.
SVGs are templated through EJS framework to make the whole rendering process easier thanks to variables, conditional and loop statements. Only drawback is that it tends to make syntax coloration a bit confused because templates are often misinterpreted as HTML tags markers (<%= "EJS templating syntax" %>
).
Images (and custom fonts) are encoded into base64 to prevent cross-origin requests, while also removing any external dependencies, although it tends to increase files sizes.
Since SVG renders differently depending on OS and browsers (system fonts, CSS support, ...), it's pretty hard to compute dynamically height. Previously, it was computed with ugly formulas, but as it wasn't scaling really well (especially since the introduction of variable content length plugins). It was often resulting in large empty blank spaces or really badly cropped image.
To solve this, metrics now spawns a puppeteer instance and directly render SVG in a browser environment (with all animations disabled). An hidden "marker" element is placed at the end of the image, and is used to resize image through its Y-offset.
Additional bonus of using pupeeter is that it can take screenshots, making it easy to convert SVGs to PNG output.
Finally, SVGs image can be optimized through svgo, which helps to remove unused attributes and blank space, while also reducing a bit the file size.
💬 Gathering external data from GitHub APIs and Third-Party services
Metrics mostly use GitHub APIs since it is its primary target. Most of the time, data are retrieved through GraphQL to save APIs requests, but it sometimes fallback on REST for other features. Octokit SDKs are used to make it easier.
As for other external services (Twitter, Spotify, PageSpeed, ...), metrics use their respective APIs, usually making https requests through axios and by following their documentation. It would be overkill to install entire SDKs for these since plugins rarely uses more than 2/3 calls.
In last resort, pupeeter is seldom used to scrap websites, though its use tends to make things slow and unstable (as it'll break upon HTML structural changes).
💬 Web instance and GitHub action similarities
Historically, metrics used to be only a web service without any customization possible. The single input was a GitHub username, and was composed of what is now base
content (along with languages
and followup
plugin, which is why they can be computed without any additional queries). That's why base
content is handled a bit differently from plugins.
As it gathered more and more plugins over time, generating a single user's metrics was becoming costly both in terms of resources but also in APIs requests. It was thus decided to switch to GitHub Action. At first, it was just a way to explore possibilities of this GitHub feature, but now it's basically the full-experience of metrics (unless you use your own self-hosted instance).
Both web instance and Action actually use the same entrypoint so they basically have the same features. Action just format inputs into a query-like object (similarly to when url params are parsed by web instance), from which metrics compute the rendered image. It also makes testing easier, as test cases can be reused since only inputs differs.
💬 Testing and mocking
Testing is done through jest framework.
While the best would be to work with real data during testing, to avoid consuming too much APIs requests for testing (and to be more planet friendly), they're mocked using JavaScript Proxies and Faker.js. Basically function calls are "trapped" and send randomly generated data from Faker.js if we're in a development environment.
Written by lowlighter