# getAllFilesForPullRequest(client, owner, repo, pullNumber)
Returns info about all files changed in a PR (max 3000 results)
Parameters
Name | Types | Description |
---|---|---|
client | object |
hydrated octokit ready to use for GitHub Actions |
owner | string |
repo owner |
repo | string |
repo name |
pullNumber | number |
pull request number |
# getChangedFilesBetweenTags(client, owner, repo, baseTag, headTag)
Get a list of files changed betwen two tags for a github repo
Parameters
Name | Types | Description |
---|---|---|
client | object |
hydrated octokit ready to use for GitHub Actions |
owner | string |
repo owner |
repo | string |
repo name |
baseTag | string |
base tag |
headTag | string |
head tag |
# getLargeJsonAtRef(client, owner, repo, path, ref)
Get large (>1MB) JSON file from git repo on at ref as a json object
Parameters
Name | Types | Description |
---|---|---|
client | object |
Hydrated octokit ready to use for GitHub Actions |
owner | string |
Repo owner |
repo | string |
Repo name |
path | string |
Path of the file in repo relative to root directory |
ref | string |
Git refrence (commit, branch, tag) |
# _makeBadge()
# makeBadge(format, format.label, format.message, format.labelColor, format.color, format.style)
Create a badge
Parameters
Name | Types | Description |
---|---|---|
format | object |
Object specifying badge data |
format.label | string |
(Optional) Badge label (e.g: 'build') |
format.message | string |
(Required) Badge message (e.g: 'passing') |
format.labelColor | string |
(Optional) Label color |
format.color | string |
(Optional) Message color |
format.style | string |
(Optional) Visual style e.g: 'flat' |
# constructor(attrs, attrs.name, attrs.content, attrs.attrs)
Xml Element Constructor
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.name | string |
Name of the XML tag |
attrs.content | Array.<string |
module:badge-maker/lib/xml~XmlElement> |
attrs.attrs | object |
Object representing the tag's attributes as name/value pairs |
# ElementList()
Convenience class. Sometimes it is useful to return an object that behaves like an XmlElement but renders multiple XML tags (not wrapped in a
# _parseJson(buffer)
Parse data from JSON endpoint
Parameters
Name | Types | Description |
---|---|---|
buffer | string |
JSON repsonse from upstream API |
# _requestGraphql(attrs, attrs.schema, attrs.url, attrs.query, attrs.variables, attrs.options, attrs.httpErrorMessages, attrs.systemErrors, attrs.transformJson, attrs.transformErrors)
Request data from an upstream GraphQL API, parse it and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response against |
attrs.url | string |
URL to request |
attrs.query | object |
Parsed GraphQL object representing the query clause of GraphQL POST body e.g. gql{ query { ... } } |
attrs.variables | object |
Variables clause of GraphQL POST body |
attrs.options | object |
Options to pass to got. See documentation |
attrs.httpErrorMessages | object |
Key-value map of HTTP status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
attrs.systemErrors | object |
Key-value map of got network exception codes and an object of params to pass when we construct an Inaccessible exception object e.g: { ECONNRESET: { prettyMessage: 'connection reset' } } . See {@link https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md#errorcodes got error codes} for allowed keys and {@link module:core/base-service/errors~RuntimeErrorProps} for allowed values |
attrs.transformJson | Function |
Function which takes the raw json and transforms it before further procesing. In case of multiple query in a single graphql call and few of them throw error, partial data might be used ignoring the error. |
attrs.transformErrors | Function |
Function which takes an errors object from a GraphQL response and returns an instance of ShieldsRuntimeError. The default is to return the first entry of the errors array as an InvalidResponse. |
# printer.js()
# _parseJson(buffer)
Parse data from JSON endpoint
Parameters
Name | Types | Description |
---|---|---|
buffer | string |
JSON repsonse from upstream API |
# _requestJson(attrs, attrs.schema, attrs.url, attrs.options, attrs.httpErrors, attrs.systemErrors)
Request data from an upstream API serving JSON, parse it and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response against |
attrs.url | string |
URL to request |
attrs.options | object |
Options to pass to got. See documentation |
attrs.httpErrors | object |
Key-value map of status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
attrs.systemErrors | object |
Key-value map of got network exception codes and an object of params to pass when we construct an Inaccessible exception object e.g: { ECONNRESET: { prettyMessage: 'connection reset' } } . See {@link https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md#errorcodes got error codes} for allowed keys and {@link module:core/base-service/errors~RuntimeErrorProps} for allowed values |
# base.js()
# _requestSvg(attrs, attrs.schema, attrs.valueMatcher, attrs.url, attrs.options, attrs.httpErrors, attrs.systemErrors)
Request data from an endpoint serving SVG, parse a value from it and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response against |
attrs.valueMatcher | RegExp |
RegExp to match the value we want to parse from the SVG |
attrs.url | string |
URL to request |
attrs.options | object |
Options to pass to got. See documentation |
attrs.httpErrors | object |
Key-value map of status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
attrs.systemErrors | object |
Key-value map of got network exception codes and an object of params to pass when we construct an Inaccessible exception object e.g: { ECONNRESET: { prettyMessage: 'connection reset' } } . See {@link https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md#errorcodes got error codes} for allowed keys and {@link module:core/base-service/errors~RuntimeErrorProps} for allowed values |
# BaseSvgScrapingService()
Services which scrape data from another SVG badge should extend BaseSvgScrapingService
# emoji.muan.co()
# valueFromSvgBadge(svg, valueMatcher)
Extract a value from SVG
Parameters
Name | Types | Description |
---|---|---|
svg | string |
SVG to parse |
valueMatcher | RegExp |
RegExp to match the value we want to parse from the SVG |
# _requestToml(attrs, attrs.schema, attrs.url, attrs.options, attrs.httpErrors, attrs.systemErrors)
Request data from an upstream API serving TOML, parse it and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response against |
attrs.url | string |
URL to request |
attrs.options | object |
Options to pass to got. See documentation |
attrs.httpErrors | object |
Key-value map of status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
attrs.systemErrors | object |
Key-value map of got network exception codes and an object of params to pass when we construct an Inaccessible exception object e.g: { ECONNRESET: { prettyMessage: 'connection reset' } } . See {@link https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md#errorcodes got error codes} for allowed keys and {@link module:core/base-service/errors~RuntimeErrorProps} for allowed values |
# _requestXml(attrs, attrs.schema, attrs.url, attrs.options, attrs.httpErrors, attrs.systemErrors, attrs.parserOptions)
Request data from an upstream API serving XML, parse it and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response against |
attrs.url | string |
URL to request |
attrs.options | object |
Options to pass to got. See documentation |
attrs.httpErrors | object |
Key-value map of status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
attrs.systemErrors | object |
Key-value map of got network exception codes and an object of params to pass when we construct an Inaccessible exception object e.g: { ECONNRESET: { prettyMessage: 'connection reset' } } . See {@link https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md#errorcodes got error codes} for allowed keys and {@link module:core/base-service/errors~RuntimeErrorProps} for allowed values |
attrs.parserOptions | object |
Options to pass to fast-xml-parser. See documentation |
# emoji.muan.co()
# _requestYaml(attrs, attrs.schema, attrs.url, attrs.options, attrs.httpErrors, attrs.systemErrors, attrs.encoding)
Request data from an upstream API serving YAML, parse it and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response against |
attrs.url | string |
URL to request |
attrs.options | object |
Options to pass to got. See documentation |
attrs.httpErrors | object |
Key-value map of status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
attrs.systemErrors | object |
Key-value map of got network exception codes and an object of params to pass when we construct an Inaccessible exception object e.g: { ECONNRESET: { prettyMessage: 'connection reset' } } . See {@link https://github.com/sindresorhus/got/blob/main/documentation/7-retry.md#errorcodes got error codes} for allowed keys and {@link module:core/base-service/errors~RuntimeErrorProps} for allowed values |
attrs.encoding | object |
Character encoding |
# BaseService()
Abstract base class which all service classes inherit from. Concrete implementations of BaseService must implement the methods category(), route() and handle(namedParams, queryParams)
# category()
Name of the category to sort this badge into (eg. "build"). Used to sort the badges on the main shields.io website.
# emoji.muan.co()
# eService()
# getEnum(param)
Extract an array of allowed values from this service's route pattern for a given route parameter
Parameters
Name | Types | Description |
---|---|---|
param | string |
The name of a param in this service's route pattern |
# handle(namedParams, queryParams)
Asynchronous function to handle requests for this service. Take the route parameters (as defined in the route
property), perform a request using this._requestFetcher
, and return the badge data.
Parameters
Name | Types | Description |
---|---|---|
namedParams | object |
Params parsed from route pattern defined in this.route.pattern or this.route.capture |
queryParams | object |
Params parsed from the query string |
# constructor(props, message)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
message | string |
Exception message for debug purposes |
# constructor(props)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
# constructor(props)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
# constructor(props)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
# constructor(props)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
# constructor(props)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
# constructor(props)
Parameters
Name | Types | Description |
---|---|---|
props | module:core/base-service/errors~RuntimeErrorProps |
Refer to individual attrs |
# defaultPrettyMessage()
Default message for this exception if none is specified. Implementations of ShieldsRuntimeError should implement this method.
# InvalidParameter()
Throw this error when a user supplied input or parameter is invalid or unexpected
# mergeQueries(queries)
Utility function to merge two graphql queries together This is basically copied from graphql-query-merge but can't use that due to incorrect packaging.
Parameters
Name | Types | Description |
---|---|---|
queries | ...object |
queries to merge |
# pathParam(param)
Helper function for assembling an OpenAPI path parameter object
Parameters
Name | Types | Description |
---|---|---|
param | module:core/base-service/openapi~PathParamInput |
Input param |
# pathParams(params)
Helper function for assembling an array of OpenAPI path parameter objects The code const params = pathParams( { name: 'name1', example: 'example1' }, { name: 'name2', example: 'example2' }, )
is equivilent to const params = [ pathParam({ name: 'name1', example: 'example1' }), pathParam({ name: 'name2', example: 'example2' }), ]
Parameters
Name | Types | Description |
---|---|---|
params | ...module:core/base-service/openapi~PathParamInput |
Input params |
# queryParam(param)
Helper function for assembling an OpenAPI query parameter object
Parameters
Name | Types | Description |
---|---|---|
param | module:core/base-service/openapi~QueryParamInput |
Input param |
# queryParams(params)
Helper function for assembling an array of OpenAPI query parameter objects The code const params = queryParams( { name: 'name1', example: 'example1' }, { name: 'name2', example: 'example2' }, )
is equivilent to const params = [ queryParam({ name: 'name1', example: 'example1' }), queryParams({ name: 'name2', example: 'example2' }), ]
Parameters
Name | Types | Description |
---|---|---|
params | ...module:core/base-service/openapi~QueryParamInput |
Input params |
# errors.js()
# getCachedResource(attrs, attrs.url, attrs.ttl, attrs.json, attrs.scraper, attrs.options, attrs.requestFetcher)
Make a HTTP request using an in-memory cache
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
- Refer to individual attrs |
attrs.url | string |
- URL to request |
attrs.ttl | number |
- Number of milliseconds to keep cached value for |
attrs.json | boolean |
- True if we expect to parse the response as JSON |
attrs.scraper | Function |
- Function to extract value from the response |
attrs.options | object |
- Options to pass to got |
attrs.requestFetcher | Function |
- Custom fetch function |
# createNumRequestCounter(attrs, attrs.category, attrs.serviceFamily, attrs.name)
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.category | string |
e.g: 'build' |
attrs.serviceFamily | string |
e.g: 'npm' |
attrs.name | string |
e.g: 'NpmVersion' |
# constructor(config)
Badge Server Constructor
Parameters
Name | Types | Description |
---|---|---|
config | object |
Configuration object read from config yaml files by https://www.npmjs.com/package/config and validated against publicConfigSchema and privateConfigSchema |
# registerRedirects()
Set up a couple of redirects: One for the raster badges. Another to redirect the base URL / (we use this to redirect {@link https://img.shields.io/} to {@link https://shields.io/} )
# registerServices()
Iterate all the service classes defined in /services, load each service and register a Scoutcamp route for each service.
# Server()
The Server is based on the web framework Scoutcamp. It creates an http server, sets up helpers for token persistence and monitoring. Then it loads all the services, injecting dependencies as it asks each one to register its route with Scoutcamp.
# start()
Start the HTTP server: Bootstrap Scoutcamp, Register handlers, Start listening for requests on this.baseUrl()
# createServiceTester()
Automatically create a ServiceTester. When run from e.g. gem-rank.tester.js
, this will create a tester that attaches to the service found in gem-rank.service.js
. This can't be used for .service.js
files which export more than one service.
# factory(superclass)
Factory which wraps an "icedfrisby-nock" with some additional functionality: - check if a request was intercepted - set expectations on the badge JSON response
Parameters
Name | Types | Description |
---|---|---|
superclass | Function |
class to extend |
# beforeEach()
Function to invoke before each test. This is a stub which can be overridden on instances.
# loader.js()
# only(services)
Limit the test run to the specified services.
Parameters
Name | Types | Description |
---|---|---|
services | string[] |
An array of service id prefixes to run |
# constructor(attrs, attrs.id, attrs.title, attrs.pathPrefix)
Service Tester Constructor
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.id | string |
Specifies which tests to run from the CLI or pull requests |
attrs.title | string |
Prints in the Mocha output |
attrs.pathPrefix | string |
Prefix which is automatically prepended to each tested URI. The default is /${attrs.id} . |
# create(msg)
Create a new test. The hard work is delegated to IcedFrisby. {@link https://github.com/MarkHerhold/IcedFrisby/#show-me-some-code} Note: The caller should not invoke toss() on the Frisby chain, as it's invoked automatically by the tester.
Parameters
Name | Types | Description |
---|---|---|
msg | string |
The name of the test |
# eUrl(attrs, attrs.baseUrl, attrs.skipIntercepted, attrs.retry, attrs.retry.count, attrs.retry.backoff)
Register the tests with Mocha.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.baseUrl | string |
base URL for test server |
attrs.skipIntercepted | boolean |
skip tests which intercept requests |
attrs.retry | object |
retry configuration |
attrs.retry.count | number |
number of times to retry test |
attrs.retry.backoff | number |
number of milliseconds to add to the wait between each retry |
# only()
Run only this tester. This can be invoked using the --only argument to the CLI, or directly on the tester.
# s(ServiceClass)
Construct a ServiceTester instance for a single service class
Parameters
Name | Types | Description |
---|---|---|
ServiceClass | Function |
A class that extends base-service/base.BaseService |
# ServiceTester()
Encapsulate a suite of tests. Create new tests using create() and register them with Mocha using toss().
# lodash.difference()
# servicesForTitle(title)
Given a pull request title like '[Travis Sonar] Support user token authentication' extract the list of service names in square brackets as an array of strings.
Parameters
Name | Types | Description |
---|---|---|
title | string |
Pull Request title |
# add(id, data, usesRemaining, nextReset)
Add a token with user-provided ID and data.
Parameters
Name | Types | Description |
---|---|---|
id | string |
token string |
data | * |
reserved for future use |
usesRemaining | number |
Number of uses remaining until the token is exhausted |
nextReset | number |
Time when the token can be used again even if it's exhausted (unix timestamp) |
# compareTokens(first, second)
compareTokens
Parameters
Name | Types | Description |
---|---|---|
first | module:core/token-pooling/token-pool~Token |
first token to compare |
second | module:core/token-pooling/token-pool~Token |
second token to compare |
# constructor(id, data, usesRemaining, nextReset)
Token Constructor
Parameters
Name | Types | Description |
---|---|---|
id | string |
token string |
data | * |
reserved for future use |
usesRemaining | number |
Number of uses remaining until the token is exhausted |
nextReset | number |
Time when the token can be used again even if it's exhausted (unix timestamp) |
# constructor(batchSize)
TokenPool Constructor
Parameters
Name | Types | Description |
---|---|---|
batchSize | number |
The maximum number of times we use each token before moving on to the next one. |
# forEach(callback)
Iterate over all valid tokens.
Parameters
Name | Types | Description |
---|---|---|
callback | Function |
function to execute on each valid token |
# freeze()
Freeze the uses remaining and next reset values. Helpful for keeping stable ordering for a valid priority queue.
# next()
Obtain the next available token, returning null
if no tokens are available. Tokens are initially pulled from a FIFO queue. The first token is used for a batch of requests, then returned to the queue to give those requests the opportunity to complete. The next token is used for the next batch of requests. This strategy allows a token to be used for concurrent requests, not just sequential request, and simplifies token recovery after errored and timed out requests. By the time the original token re-emerges, its requests should have long since completed. Even if a couple them are still running, they can reasonably be ignored. The uses remaining won't be 100% correct, but that's fine, because Shields uses only 75% The process continues until an exhausted token is pulled from the FIFO queue. At that time it's placed in the priority queue based on its scheduled reset time. To ensure the priority queue works as intended, the scheduled reset time is frozen then. After obtaining a token using next()
, invoke update()
on it to set a new use-remaining count and next-reset time. Invoke invalidate()
to indicate it should not be reused.
# sanitizeToken(id)
Compute a one-way hash of the input string.
Parameters
Name | Types | Description |
---|---|---|
id | string |
token |
# Token()
Encapsulate a rate-limited token, with a user-provided ID and user-provided data. Each token has a notion of the number of uses remaining until exhausted, and the next reset time, when it can be used again even if it's exhausted.
# TokenPool()
Encapsulate a collection of rate-limited tokens and choose the next available token when one is needed. Designed for the Github API, though may be also useful with other rate- limited APIs.
# update(usesRemaining, nextReset)
Update the uses remaining and next reset time for a token.
Parameters
Name | Types | Description |
---|---|---|
usesRemaining | number |
Number of uses remaining until the token is exhausted |
nextReset | number |
Time when the token can be used again even if it's exhausted (unix timestamp) |
# isBuildStatus()
Joi schema for validating Build Status. Checks if the build status is present in the list of allowed build status.
# renderBuildStatusBadge(attrs, attrs.label, attrs.status)
Handles rendering concerns of badges that display build status. Determines the message and color of the badge according to the build status.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attributes |
attrs.label | string |
If provided then badge label is set to this value |
attrs.status | string |
Build status |
# age(date)
Determines the color used for a badge according to the age. Age is calculated as days elapsed till current date. The color varies from bright green to red as the age increases.
Parameters
Name | Types | Description |
---|---|---|
date | string |
Date string |
# colorScale(steps, colors, reversed)
Creates a callback function that determines badge color from the colors array. If the colors array is provided then for n steps, there should be n + 1 color. If the colors array is not provided then it is chosen from the default colors array according to the size of the steps array.
Parameters
Name | Types | Description |
---|---|---|
steps | number[] |
Steps array |
colors | string[] |
Colors array. If provided, should be of length steps.length + 1 |
reversed | boolean |
If true then the colors array will be considered in reverse order |
# coveragePercentage(percentage)
Determines the color used for a badge by comparing percentage and floor values. The color varies from red to bright green as the percentage increases.
Parameters
Name | Types | Description |
---|---|---|
percentage | number |
Percentage value |
# downloadCount(downloads)
Determines the color used for a badge by comparing the download count and floor values. The color varies from red to bright green as the download count increases.
Parameters
Name | Types | Description |
---|---|---|
downloads | number |
Download count |
# floorCount(value, yellow, yellowgreen, green)
Determines the color used for a badge by comparing the value and floor count values. The color can vary from red to bright green depending on the range the value lies in. Decreasing the value will shift the color towards red. Increasing the value will shift the color towards bright green.
Parameters
Name | Types | Description |
---|---|---|
value | number |
Current value |
yellow | number |
Yellow color threshold, should be greater than 0 |
yellowgreen | number |
Yellowgreen color threshold, should be greater than yellow |
green | number |
Green color threshold, should be greater than yellowgreen |
# letterScore(score)
Determines the color used for a badge by matching score with grade values. The color varies from bright green to red as the score decreases. The score can be one of the following grade value: ['A', 'B', 'C', 'D', 'E']. The color defaults to red if the score does not matches with any of the grade values.
Parameters
Name | Types | Description |
---|---|---|
score | string |
Score value |
# pep440VersionColor(version)
Determines the color used for a badge based on PEP440 versioning.
Parameters
Name | Types | Description |
---|---|---|
version | string |
number |
# version(version)
Determines the color used for a badge based on version.
Parameters
Name | Types | Description |
---|---|---|
version | string |
number |
# contributorColor(contributorCount)
Determines the color used for a badge based on the contributor count. The color varies from red to bright green as the contributor count increases.
Parameters
Name | Types | Description |
---|---|---|
contributorCount | number |
Contributor count |
# renderContributorBadge(attrs, attrs.label, attrs.contributorCount)
Handles rendering concerns of badges that display contributor count. Determines the message and color of the badge according to the contributor count.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attributes |
attrs.label | string |
If provided then badge label is set to this value |
attrs.contributorCount | number |
Contributor count |
# formatters.js()
# renderDownloadsBadge(attrs, attrs.downloads, attrs.interval, attrs.version, attrs.labelOverride, attrs.colorOverride, attrs.messageSuffixOverride, attrs.versionedLabelPrefix)
Handles rendering concerns of badges that display download counts, with override/customization support
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.downloads | number |
Number of downloads |
attrs.interval | string |
Period or interval the downloads occurred (e.g. day, week, month). If provided then this Will be reflected in the badge message unless overridden by other message-related parameters |
attrs.version | string |
Version or tag that was downloaded which will be reflected in the badge label (unless the label is overridden) |
attrs.labelOverride | string |
If provided then the badge label is set to this value overriding any other label-related parameters |
attrs.colorOverride | string |
If provided then the badge color is set to this value instead of the color being based on the count of downloads |
attrs.messageSuffixOverride | string |
If provided then the badge message will will have this value added to the download count, separated with a space |
attrs.versionedLabelPrefix | string |
If provided then the badge label will use this value as the prefix for versioned badges, e.g. [email protected] . Defaults to 'downloads' |
# compoundValueSchema()
Joi schema for validating compound value. Checks if the compound value is of type individualValueSchema, array of individualValueSchema or empty array.
# individualValueSchema()
Joi schema for validating individual value. Checks if the individual value is of type string or number.
# renderDynamicBadge(attrs, attrs.defaultLabel, attrs.tag, attrs.value, attrs.prefix, attrs.suffix)
Handles rendering concerns of dynamic badges. Determines the label of the badge according to the tag and defaultLabel. Determines the message of the badge according to the prefix, suffix and value. Sets the color of the badge to blue.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attributes |
attrs.defaultLabel | string |
default badge label |
attrs.tag | string |
If provided then this value will be appended to the badge label, e.g. [email protected] |
attrs.value | any |
Value or array of value to be used for the badge message |
attrs.prefix | string |
If provided then the badge message will use this value as a prefix |
attrs.suffix | string |
If provided then the badge message will use this value as a suffix |
# transformAndValidate(attrs, attrs.data, attrs.key)
Look up the value in the data object by key and validate the value against compoundValueSchema.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attributes |
attrs.data | object |
Object containing the data for validation |
attrs.key | string |
Key to retrieve the data from object for validation |
# fetch(attrs, attrs.schema, attrs.url, attrs.httpErrors)
Request data from an upstream API, transform it to JSON and validate against a schema
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.schema | Joi |
Joi schema to validate the response transformed to JSON |
attrs.url | string |
URL to request |
attrs.httpErrors | object |
Key-value map of status codes and custom error messages e.g: { 404: 'package not found' } . This can be used to extend or override the default |
# s(superclass)
Dynamic service class factory which wraps {@link module:core/base-service/base~BaseService} with support of {@link https://jsonpath.com/|JSONPath}.
Parameters
Name | Types | Description |
---|---|---|
superclass | Function |
class to extend |
# fetchEndpointData(serviceInstance, attrs, attrs.url, attrs.httpErrors, attrs.validationPrettyErrorMessage, attrs.includeKeys)
Fetches data from the endpoint and validates the data.
Parameters
Name | Types | Description |
---|---|---|
serviceInstance | object |
Instance of Endpoint class |
attrs | object |
Refer to individual attributes |
attrs.url | string |
Endpoint URL |
attrs.httpErrors | object |
Object containing error messages for different error codes |
attrs.validationPrettyErrorMessage | string |
If provided then the error message is set to this value |
attrs.includeKeys | boolean |
If true then includes error details in error message |
# validateEndpointData(data, attrs, attrs.prettyErrorMessage, attrs.includeKeys)
Strictly validate the data according to the endpoint schema. This rejects unknown/invalid keys. Optionally it prints those keys in the message to provide detailed feedback.
Parameters
Name | Types | Description |
---|---|---|
data | object |
Object containing the data for validation |
attrs | object |
Refer to individual attributes |
attrs.prettyErrorMessage | string |
If provided then error message is set to this value |
attrs.includeKeys | boolean |
If true then includes error details in error message, defaults to false |
# FreeCodeCampPoints()
This badge displays the total number of points a student has accumulated from completing challenges on freeCodeCamp.
# schema()
Validates that the schema response is what we're expecting. The username pattern should match the requirements in the freeCodeCamp repository.
# clock()
# validateAffiliations(value, helpers)
Validates affiliations should contain combination of allowed values in any order.
Parameters
Name | Types | Description |
---|---|---|
value | string |
affiliation current value |
helpers | * |
object to construct custom error |
# licenseToColor(licenses)
Maps the license to its corresponding color and priority and sorts the list of mapped licenses by priority.
Parameters
Name | Types | Description |
---|---|---|
licenses | string |
string[] |
# renderLicenseBadge(attrs, attrs.license, attrs.licenses, attrs.color)
Handles rendering concerns of license badges. Determines the message of the badge by joining the licenses in a comma-separated format. Sets the badge color to the provided value, if not provided then the color is used from licenseToColorMap.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attributes |
attrs.license | string |
License to render, required if badge contains only one license |
attrs.licenses | string[] |
List of licenses to render, required if badge contains multiple licenses |
attrs.color | string |
If provided then the badge will use this color value |
# formatters.js()
Utilities relating to Lua 'rocks' version numbers. This compares version numbers using the algorithm followed by luarocks command-line utility. Some specific things about LuaRocks package versioning: 1. A version string consists of two parts: the package version (version of the package code) and the revision of rockspec
file https://github.com/luarocks/luarocks/wiki/Rockspec-format > version (string, mandatory field) - the version of the package, plus a suffix indicating the revision of the rockspec. Example: "2.0.1-1" 2. The package version (the first part of the LuaRocks version, the part before dash) can be anything, SemVer is not mandatory and is not used very often. Non-digit versions are not rare: scm
, dev
, alpha
, etc. 3. scm
(or cvs
) is used to indicate dev version built from VCS (e.g. "scm-1"
). dev
version string is also used sometimes, and I don't know what the difference. 4. LuaRocks API does not tell you which version is the “latest”, and the package maintainer cannot mark a specific version as the latest. You should figure out it yourself. https://github.com/luarocks/luarocks/blob/405ee29ba8444d97646f62e72effeaff2bfe3f79/src/luarocks/search.lua#L182 https://github.com/luarocks/luarocks/blob/405ee29ba8444d97646f62e72effeaff2bfe3f79/src/luarocks/core/vers.lua#L83
# getColor(attrs, attrs.status)
Return color for active, maintenance and archived statuses, which were the three example keywords used in Netflix's open-source meetup. See https://slideshare.net/aspyker/netflix-open-source-meetup-season-4-episode-1 Other keywords are possible, but will appear in grey.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.status | string |
Specifies the current maintenance status |
# getDependencyVersion(attrs, attrs.kind, attrs.wantedDependency, attrs.dependencies, attrs.devDependencies, attrs.peerDependencies, attrs.optionalDependencies)
Determines the dependency version based on the dependency type.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
- Refer to individual attributes |
attrs.kind | string |
- Wanted dependency type, defaults to prod |
attrs.wantedDependency | string |
- Name of the wanted dependency |
attrs.dependencies | object |
- Map of dependencies |
attrs.devDependencies | object |
- Map of dev dependencies |
attrs.peerDependencies | object |
- Map of peer dependencies |
attrs.optionalDependencies | object |
- Map of optional dependencies |
# isPackageJsonWithDependencies()
Joi schema for validating package json object. Checks if the object has all the dependency types and the dependency types are valid.
# e(versions, includePrereleases)
Find the object representation of the latest release.
Parameters
Name | Types | Description |
---|---|---|
versions | object[] |
An array of object representing a version. |
includePrereleases | boolean |
Includes pre-release semver for the search. |
# expandPackageVersions(json, packageName)
Extract the array of minified versions of the given packageName, expand them back to their original format then return.
Parameters
Name | Types | Description |
---|---|---|
json | object |
The response of Packagist v2 API. |
packageName | string |
The package name. |
# fetchByJsonAPI(attrs, attrs.user, attrs.repo, attrs.schema, attrs.server)
It is highly recommended to use base fetch method! JSON API includes additional information about downloads, dependents count, github info, etc. However, responses from JSON API are cached for twelve hours by packagist servers, so data fetch from this method might be outdated. For more information please refer to https://packagist.org/apidoc#get-package-data.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.user | string |
package user |
attrs.repo | string |
package repository |
attrs.schema | Joi |
Joi schema to validate the response transformed to JSON |
attrs.server | string |
URL for the packagist registry server (Optional) |
# packagist.org(attrs, attrs.user, attrs.repo, attrs.schema, attrs.server)
Default fetch method. This method utilizes composer metadata API which "... is the preferred way to access the data as it is always up to date, and dumped to static files so it is very efficient on our end." (comment from official documentation). For more information please refer to https://packagist.org/apidoc#get-package-data.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.user | string |
package user |
attrs.repo | string |
package repository |
attrs.schema | Joi |
Joi schema to validate the response transformed to JSON |
attrs.server | string |
URL for the packagist registry server (Optional) |
# packagist.org(attrs, attrs.user, attrs.repo, attrs.schema, attrs.server)
Fetch dev releases method. This method utilizes composer metadata API which "... is the preferred way to access the data as it is always up to date, and dumped to static files so it is very efficient on our end." (comment from official documentation). For more information please refer to https://packagist.org/apidoc#get-package-data.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
Refer to individual attrs |
attrs.user | string |
package user |
attrs.repo | string |
package repository |
attrs.schema | Joi |
Joi schema to validate the response transformed to JSON |
attrs.server | string |
URL for the packagist registry server (Optional) |
# asciiVersionCompare(v1, v2)
Return a negative value if v1 < v2, zero if v1 = v2, a positive value otherwise.
Parameters
Name | Types | Description |
---|---|---|
v1 | string |
- First version for comparison |
v2 | string |
- Second version for comparison |
# compare(v1, v2)
Compares two versions and return an integer based on the result. See https://getcomposer.org/doc/04-schema.md#version and https://github.com/badges/shields/issues/319#issuecomment-74411045
Parameters
Name | Types | Description |
---|---|---|
v1 | string |
- First version |
v2 | string |
- Second version |
# getPhpReleases(githubApiProvider)
Fetches the PHP release versions from cache if exists, else fetch from the source url and save in cache.
Parameters
Name | Types | Description |
---|---|---|
githubApiProvider | object |
- Github API provider |
# got.js()
Utilities relating to PHP version numbers. This compares version numbers using the algorithm followed by Composer (see https://getcomposer.org/doc/04-schema.md#version).
# isStable(version)
Determines if a version is stable or not.
Parameters
Name | Types | Description |
---|---|---|
version | string |
- Version number |
# latest(versions)
Determines the latest version from a list of versions.
Parameters
Name | Types | Description |
---|---|---|
versions | string[] |
- List of versions |
# minorVersion(version)
Checks if a version is valid and returns the minor version.
Parameters
Name | Types | Description |
---|---|---|
version | string |
- Version number |
# numberedVersionData(version)
Take a version without the starting v. eg, '1.0.x-beta' Return { numbers: [1,0,something big], modifier: 2, modifierCount: 1 }
Parameters
Name | Types | Description |
---|---|---|
version | string |
- Version number string |
# toNum(s)
Try to convert to a list of numbers.
Parameters
Name | Types | Description |
---|---|---|
s | string |
- Version number string |
# versionReduction(versions, phpReleases)
Reduces the list of php versions that intersect with release versions to a version range (for eg. '5.4 - 7.1', '>= 5.5').
Parameters
Name | Types | Description |
---|---|---|
versions | string[] |
- List of php versions |
phpReleases | string[] |
- List of php release versions |
# getDependencyVersion(attrs, attrs.kind, attrs.wantedDependency, attrs.lockfileData)
Determines the dependency version based on the dependency type.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
- Refer to individual attributes |
attrs.kind | string |
- Wanted dependency type ('dev' or 'default'), defaults to 'default' |
attrs.wantedDependency | string |
- Name of the wanted dependency |
attrs.lockfileData | object |
- Object containing lock file data |
# isLockfile()
Joi schema for validating lock file object. Checks if the lock file object has required properties and the properties are valid.
# e(attrs, attrs.base)
Creates a RouteBuilder object.
Parameters
Name | Types | Description |
---|---|---|
attrs | object |
- Refer to individual attributes |
attrs.base | string |
- Base URL, defaults to '' |
# push(format, capture)
Saves the format and capture values in the RouteBuilder instance.
Parameters
Name | Types | Description |
---|---|---|
format | string |
- Pattern based on path-to-regex, for example: (?:(.+)\.)?${serviceBaseUrl} |
capture | string |
- Value to capture |
# toObject()
Returns a new object based on RouteBuilder instance containing its base, format and capture properties.
# index.js()
# isMetricWithPattern(nestedRegexp)
Parameters
Name | Types | Description |
---|---|---|
nestedRegexp | RegExp |
Pattern that must appear after the metric. |
# addv(version)
Add a starting v to the version unless it doesn't starts with a digit or is a date (yyyy-mm-dd) For example, addv("1.2.3") returns "v1.2.3", but addv("hello") or addv("2021-10-31"), returns "hello" and "2021-10-31" respectively.
Parameters
Name | Types | Description |
---|---|---|
version | string |
- Version string |
# currencyFromCode(code)
Converts the ISO 4217 code to the corresponding currency symbol. If the the symbol for the code is not found, then the code itself is returned.
Parameters
Name | Types | Description |
---|---|---|
code | string |
- ISO 4217 code |
# formatDate(d)
Returns a formatted date string without the year based on the value of input date param d.
Parameters
Name | Types | Description |
---|---|---|
d | Date |
string |
# formatRelativeDate(timestamp)
Returns a relative date from the input timestamp. For example, day after tomorrow's timestamp will return 'in 2 days'.
Parameters
Name | Types | Description |
---|---|---|
timestamp | number |
string |
# maybePluralize(singular, countable, plural)
Returns a string that is either the singular or the plural form of a word, depending on the length of the countable parameter.
Parameters
Name | Types | Description |
---|---|---|
singular | string |
- Singular form of the word |
countable | string[] |
- Array of values you want to count |
plural | string |
- Plural form of the word |
# metric(n)
Given a number (positive or negative), returns a string with appropriate unit in the metric system, SI. Note: numbers beyond the peta- cannot be represented as integers in JS. For example, if you call metric(1000), it will return "1k", which means one kilo or one thousand.
Parameters
Name | Types | Description |
---|---|---|
n | number |
- Input number |
# omitv(version)
Remove the starting v in a string if it exists. For example, omitv("v1.2.3") returns "1.2.3", but omitv("hello") returns "hello".
Parameters
Name | Types | Description |
---|---|---|
version | string |
- Version string |
# ordinalNumber(n)
Calculates the ordinal number of the given number. For example, if the input is 1, the output is “1ˢᵗ”.
Parameters
Name | Types | Description |
---|---|---|
n | number |
- Input number |
# starRating(rating, max)
Creates a string of stars and empty stars based on the rating. The number of stars is determined by the integer part of the rating. An additional star or a three-quarter star or a half star or a quarter star is added based on the decimal part of the rating. The remaining stars are empty stars until the maximum number of stars is reached.
Parameters
Name | Types | Description |
---|---|---|
rating | number |
- Current rating |
max | number |
- Maximum rating |
# anyInteger()
Joi validator that checks if a value is a number, an integer and the value must be present.
# fileSize()
Joi validator for a file size we are going to pass to bytes.parse see https://github.com/visionmedia/bytes.js#bytesparsestringnumber-value-numbernull
# nonNegativeInteger()
Joi validator that checks if a value is a number, an integer, greater than or equal to zero and the value must be present.
# optionalDottedVersionNClausesWithOptionalSuffix()
Joi validator that checks if a value is a string that matches a regular expression. The regular expression matches strings that start with one or more digits, followed by zero or more groups of a dot and one or more digits, followed by an optional suffix that starts with a dash or a plus sign and can contain any characters. This validator can be used to validate properties that can be version strings with an optional suffix or absent. For example, some valid values for this validator are: 1, 1.0, 1.0.0, 1.0.0-beta Some invalid values for this validator are: abc, 1.a, 1.0-, .1
# optionalNonNegativeInteger()
Joi validator that checks if a value is a number, an integer, and greater than or equal to zero.
# optionalUrl()
Joi validator that checks if a value is a URL TODO: This accepts URLs with query strings and fragments, which for some purposes should be rejected.
# semver()
Joi validator that checks if a value is a valid semantic versioning string and the value must be present.
# semverRange()
Joi validator that checks if a value is a valid semantic versioning range and the value must be present.
# compareDottedVersion(v1, v2)
Compares two strings representing version numbers lexicographically and returns an integer value.
Parameters
Name | Types | Description |
---|---|---|
v1 | string |
- The first version to compare |
v2 | string |
- The second version to compare |
# latest(versions, options, options.pre)
Finds the largest version number lexicographically or semantically from an array of strings representing version numbers and returns it as a string. latest() is looser than latestMaybeSemVer() as it will attempt to make sense of anything, falling back to alphabetic sorting. We should ideally prefer latest() over latestMaybeSemVer() when adding version badges.
Parameters
Name | Types | Description |
---|---|---|
versions | string[] |
- The array of version numbers to compare |
options | object |
- An optional object that contains additional options |
options.pre | boolean |
- Whether to include pre-release versions or not, defaults to false |
# latestDottedVersion(versions)
Finds the largest version number lexicographically from an array of strings representing version numbers and returns it as a string.
Parameters
Name | Types | Description |
---|---|---|
versions | string[] |
- The array of version numbers to compare |
# latestMaybeSemVer(versions, pre)
Finds the largest version number lexicographically or semantically from an array of strings representing version numbers and returns it as a string. latestMaybeSemVer() is used for versions that match some kind of dotted version pattern.
Parameters
Name | Types | Description |
---|---|---|
versions | string[] |
- The array of version numbers to compare |
pre | boolean |
- Whether to include pre-release versions or not |
# listCompare(a, b)
Compares two arrays of numbers lexicographically and returns an integer value.
Parameters
Name | Types | Description |
---|---|---|
a | number[] |
- The first array to compare |
b | number[] |
- The second array to compare |
# rangeStart(v)
Returns the start of the range that matches a given version string.
Parameters
Name | Types | Description |
---|---|---|
v | string |
- A version string that follows the Semantic Versioning specification. The function will accept and coerce invalid versions into valid ones. |
# renderVersionBadge(options, options.version, options.tag, options.defaultLabel, options.versionFormatter)
Creates a badge object that displays information about a version number. It should usually be used to output a version badge.
Parameters
Name | Types | Description |
---|---|---|
options | object |
- An object that contains the options for the badge |
options.version | string |
- The version number to display on the badge |
options.tag | string |
- The tag to display on the badge, such as "alpha" or "beta" |
options.defaultLabel | string |
- The default label to display on the badge, such as "npm" or "github" |
options.versionFormatter | Function |
- The function to use to format the color of the badge based on the version number |
# slice(v, releaseType)
Slices the specified number of dotted parts from the given semver version.
Parameters
Name | Types | Description |
---|---|---|
v | string |
- The semver version to slice |
releaseType | string |
- The release type to slice up to. Can be one of "major", "minor", or "patch" |
# render(translatedPercent)
Takes a percentage and maps it to a message and color. The colors are determined based on how Weblate does it internally. {@link https://github.com/WeblateOrg/weblate/blob/main/weblate/trans/widgets.py Weblate on GitHub}
Parameters
Name | Types | Description |
---|---|---|
translatedPercent | * |
The percentage of translations translated. |
# WeblateProjectTranslatedPercentage()
This badge displays the percentage of strings translated on a project on a Weblate instance.
# exampleQueryParams()
Example query param object. Contains up_message, down_message, up_color and down_color properties.
# queryParamSchema()
Joi schema for validating query params. Checks if the query params obect has valid up_message, down_message, up_color and down_color properties.
# renderWebsiteStatus(options, options.isUp, options.upMessage, options.downMessage, options.upColor, options.downColor)
Creates a badge object that displays information about website status.
Parameters
Name | Types | Description |
---|---|---|
options | object |
- The options for rendering the status |
options.isUp | boolean |
- Whether the website or service is up or down |
options.upMessage | string |
- The message to display when the website or service is up |
options.downMessage | string |
- The message to display when the website or service is down |
options.upColor | string |
- The color to use when the website or service is up |
options.downColor | string |
- The color to use when the website or service is down |
# WikiapiaryInstalls()
This badge displays the total installations of a MediaWiki extensions, skins, etc via Wikiapiary. {@link https://www.mediawiki.org/wiki/Manual:Extensions MediaWiki Extensions Manual}