diff --git a/assets/anchor.js b/assets/anchor.js new file mode 100644 index 00000000..1f573dcb --- /dev/null +++ b/assets/anchor.js @@ -0,0 +1,350 @@ +/*! + * AnchorJS - v4.0.0 - 2017-06-02 + * https://github.com/bryanbraun/anchorjs + * Copyright (c) 2017 Bryan Braun; Licensed MIT + */ +/* eslint-env amd, node */ + +// https://github.com/umdjs/umd/blob/master/templates/returnExports.js +(function (root, factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define([], factory); + } else if (typeof module === 'object' && module.exports) { + // Node. Does not work with strict CommonJS, but + // only CommonJS-like environments that support module.exports, + // like Node. + module.exports = factory(); + } else { + // Browser globals (root is window) + root.AnchorJS = factory(); + root.anchors = new root.AnchorJS(); + } +})(this, function () { + 'use strict'; + function AnchorJS(options) { + this.options = options || {}; + this.elements = []; + + /** + * Assigns options to the internal options object, and provides defaults. + * @param {Object} opts - Options object + */ + function _applyRemainingDefaultOptions(opts) { + opts.icon = opts.hasOwnProperty('icon') ? opts.icon : '\ue9cb'; // Accepts characters (and also URLs?), like '#', '¶', '❡', or '§'. + opts.visible = opts.hasOwnProperty('visible') ? opts.visible : 'hover'; // Also accepts 'always' & 'touch' + opts.placement = opts.hasOwnProperty('placement') + ? opts.placement + : 'right'; // Also accepts 'left' + opts.class = opts.hasOwnProperty('class') ? opts.class : ''; // Accepts any class name. + // Using Math.floor here will ensure the value is Number-cast and an integer. + opts.truncate = opts.hasOwnProperty('truncate') + ? Math.floor(opts.truncate) + : 64; // Accepts any value that can be typecast to a number. + } + + _applyRemainingDefaultOptions(this.options); + + /** + * Checks to see if this device supports touch. Uses criteria pulled from Modernizr: + * https://github.com/Modernizr/Modernizr/blob/da22eb27631fc4957f67607fe6042e85c0a84656/feature-detects/touchevents.js#L40 + * @returns {Boolean} - true if the current device supports touch. + */ + this.isTouchDevice = function () { + return !!( + 'ontouchstart' in window || + (window.DocumentTouch && document instanceof DocumentTouch) + ); + }; + + /** + * Add anchor links to page elements. + * @param {String|Array|Nodelist} selector - A CSS selector for targeting the elements you wish to add anchor links + * to. Also accepts an array or nodeList containing the relavant elements. + * @returns {this} - The AnchorJS object + */ + this.add = function (selector) { + var elements, + elsWithIds, + idList, + elementID, + i, + index, + count, + tidyText, + newTidyText, + readableID, + anchor, + visibleOptionToUse, + indexesToDrop = []; + + // We reapply options here because somebody may have overwritten the default options object when setting options. + // For example, this overwrites all options but visible: + // + // anchors.options = { visible: 'always'; } + _applyRemainingDefaultOptions(this.options); + + visibleOptionToUse = this.options.visible; + if (visibleOptionToUse === 'touch') { + visibleOptionToUse = this.isTouchDevice() ? 'always' : 'hover'; + } + + // Provide a sensible default selector, if none is given. + if (!selector) { + selector = 'h2, h3, h4, h5, h6'; + } + + elements = _getElements(selector); + + if (elements.length === 0) { + return this; + } + + _addBaselineStyles(); + + // We produce a list of existing IDs so we don't generate a duplicate. + elsWithIds = document.querySelectorAll('[id]'); + idList = [].map.call(elsWithIds, function assign(el) { + return el.id; + }); + + for (i = 0; i < elements.length; i++) { + if (this.hasAnchorJSLink(elements[i])) { + indexesToDrop.push(i); + continue; + } + + if (elements[i].hasAttribute('id')) { + elementID = elements[i].getAttribute('id'); + } else if (elements[i].hasAttribute('data-anchor-id')) { + elementID = elements[i].getAttribute('data-anchor-id'); + } else { + tidyText = this.urlify(elements[i].textContent); + + // Compare our generated ID to existing IDs (and increment it if needed) + // before we add it to the page. + newTidyText = tidyText; + count = 0; + do { + if (index !== undefined) { + newTidyText = tidyText + '-' + count; + } + + index = idList.indexOf(newTidyText); + count += 1; + } while (index !== -1); + index = undefined; + idList.push(newTidyText); + + elements[i].setAttribute('id', newTidyText); + elementID = newTidyText; + } + + readableID = elementID.replace(/-/g, ' '); + + // The following code builds the following DOM structure in a more effiecient (albeit opaque) way. + // ''; + anchor = document.createElement('a'); + anchor.className = 'anchorjs-link ' + this.options.class; + anchor.href = '#' + elementID; + anchor.setAttribute('aria-label', 'Anchor link for: ' + readableID); + anchor.setAttribute('data-anchorjs-icon', this.options.icon); + + if (visibleOptionToUse === 'always') { + anchor.style.opacity = '1'; + } + + if (this.options.icon === '\ue9cb') { + anchor.style.font = '1em/1 anchorjs-icons'; + + // We set lineHeight = 1 here because the `anchorjs-icons` font family could otherwise affect the + // height of the heading. This isn't the case for icons with `placement: left`, so we restore + // line-height: inherit in that case, ensuring they remain positioned correctly. For more info, + // see https://github.com/bryanbraun/anchorjs/issues/39. + if (this.options.placement === 'left') { + anchor.style.lineHeight = 'inherit'; + } + } + + if (this.options.placement === 'left') { + anchor.style.position = 'absolute'; + anchor.style.marginLeft = '-1em'; + anchor.style.paddingRight = '0.5em'; + elements[i].insertBefore(anchor, elements[i].firstChild); + } else { + // if the option provided is `right` (or anything else). + anchor.style.paddingLeft = '0.375em'; + elements[i].appendChild(anchor); + } + } + + for (i = 0; i < indexesToDrop.length; i++) { + elements.splice(indexesToDrop[i] - i, 1); + } + this.elements = this.elements.concat(elements); + + return this; + }; + + /** + * Removes all anchorjs-links from elements targed by the selector. + * @param {String|Array|Nodelist} selector - A CSS selector string targeting elements with anchor links, + * OR a nodeList / array containing the DOM elements. + * @returns {this} - The AnchorJS object + */ + this.remove = function (selector) { + var index, + domAnchor, + elements = _getElements(selector); + + for (var i = 0; i < elements.length; i++) { + domAnchor = elements[i].querySelector('.anchorjs-link'); + if (domAnchor) { + // Drop the element from our main list, if it's in there. + index = this.elements.indexOf(elements[i]); + if (index !== -1) { + this.elements.splice(index, 1); + } + // Remove the anchor from the DOM. + elements[i].removeChild(domAnchor); + } + } + return this; + }; + + /** + * Removes all anchorjs links. Mostly used for tests. + */ + this.removeAll = function () { + this.remove(this.elements); + }; + + /** + * Urlify - Refine text so it makes a good ID. + * + * To do this, we remove apostrophes, replace nonsafe characters with hyphens, + * remove extra hyphens, truncate, trim hyphens, and make lowercase. + * + * @param {String} text - Any text. Usually pulled from the webpage element we are linking to. + * @returns {String} - hyphen-delimited text for use in IDs and URLs. + */ + this.urlify = function (text) { + // Regex for finding the nonsafe URL characters (many need escaping): & +$,:;=?@"#{}|^~[`%!'<>]./()*\ + var nonsafeChars = /[& +$,:;=?@"#{}|^~[`%!'<>\]\.\/\(\)\*\\]/g, + urlText; + + // The reason we include this _applyRemainingDefaultOptions is so urlify can be called independently, + // even after setting options. This can be useful for tests or other applications. + if (!this.options.truncate) { + _applyRemainingDefaultOptions(this.options); + } + + // Note: we trim hyphens after truncating because truncating can cause dangling hyphens. + // Example string: // " ⚡⚡ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + urlText = text + .trim() // "⚡⚡ Don't forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + .replace(/\'/gi, '') // "⚡⚡ Dont forget: URL fragments should be i18n-friendly, hyphenated, short, and clean." + .replace(nonsafeChars, '-') // "⚡⚡-Dont-forget--URL-fragments-should-be-i18n-friendly--hyphenated--short--and-clean-" + .replace(/-{2,}/g, '-') // "⚡⚡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-short-and-clean-" + .substring(0, this.options.truncate) // "⚡⚡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated-" + .replace(/^-+|-+$/gm, '') // "⚡⚡-Dont-forget-URL-fragments-should-be-i18n-friendly-hyphenated" + .toLowerCase(); // "⚡⚡-dont-forget-url-fragments-should-be-i18n-friendly-hyphenated" + + return urlText; + }; + + /** + * Determines if this element already has an AnchorJS link on it. + * Uses this technique: http://stackoverflow.com/a/5898748/1154642 + * @param {HTMLElemnt} el - a DOM node + * @returns {Boolean} true/false + */ + this.hasAnchorJSLink = function (el) { + var hasLeftAnchor = + el.firstChild && + (' ' + el.firstChild.className + ' ').indexOf(' anchorjs-link ') > -1, + hasRightAnchor = + el.lastChild && + (' ' + el.lastChild.className + ' ').indexOf(' anchorjs-link ') > -1; + + return hasLeftAnchor || hasRightAnchor || false; + }; + + /** + * Turns a selector, nodeList, or array of elements into an array of elements (so we can use array methods). + * It also throws errors on any other inputs. Used to handle inputs to .add and .remove. + * @param {String|Array|Nodelist} input - A CSS selector string targeting elements with anchor links, + * OR a nodeList / array containing the DOM elements. + * @returns {Array} - An array containing the elements we want. + */ + function _getElements(input) { + var elements; + if (typeof input === 'string' || input instanceof String) { + // See https://davidwalsh.name/nodelist-array for the technique transforming nodeList -> Array. + elements = [].slice.call(document.querySelectorAll(input)); + // I checked the 'input instanceof NodeList' test in IE9 and modern browsers and it worked for me. + } else if (Array.isArray(input) || input instanceof NodeList) { + elements = [].slice.call(input); + } else { + throw new Error('The selector provided to AnchorJS was invalid.'); + } + return elements; + } + + /** + * _addBaselineStyles + * Adds baseline styles to the page, used by all AnchorJS links irregardless of configuration. + */ + function _addBaselineStyles() { + // We don't want to add global baseline styles if they've been added before. + if (document.head.querySelector('style.anchorjs') !== null) { + return; + } + + var style = document.createElement('style'), + linkRule = + ' .anchorjs-link {' + + ' opacity: 0;' + + ' text-decoration: none;' + + ' -webkit-font-smoothing: antialiased;' + + ' -moz-osx-font-smoothing: grayscale;' + + ' }', + hoverRule = + ' *:hover > .anchorjs-link,' + + ' .anchorjs-link:focus {' + + ' opacity: 1;' + + ' }', + anchorjsLinkFontFace = + ' @font-face {' + + ' font-family: "anchorjs-icons";' + // Icon from icomoon; 10px wide & 10px tall; 2 empty below & 4 above + ' src: url(data:n/a;base64,AAEAAAALAIAAAwAwT1MvMg8yG2cAAAE4AAAAYGNtYXDp3gC3AAABpAAAAExnYXNwAAAAEAAAA9wAAAAIZ2x5ZlQCcfwAAAH4AAABCGhlYWQHFvHyAAAAvAAAADZoaGVhBnACFwAAAPQAAAAkaG10eASAADEAAAGYAAAADGxvY2EACACEAAAB8AAAAAhtYXhwAAYAVwAAARgAAAAgbmFtZQGOH9cAAAMAAAAAunBvc3QAAwAAAAADvAAAACAAAQAAAAEAAHzE2p9fDzz1AAkEAAAAAADRecUWAAAAANQA6R8AAAAAAoACwAAAAAgAAgAAAAAAAAABAAADwP/AAAACgAAA/9MCrQABAAAAAAAAAAAAAAAAAAAAAwABAAAAAwBVAAIAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAMCQAGQAAUAAAKZAswAAACPApkCzAAAAesAMwEJAAAAAAAAAAAAAAAAAAAAARAAAAAAAAAAAAAAAAAAAAAAQAAg//0DwP/AAEADwABAAAAAAQAAAAAAAAAAAAAAIAAAAAAAAAIAAAACgAAxAAAAAwAAAAMAAAAcAAEAAwAAABwAAwABAAAAHAAEADAAAAAIAAgAAgAAACDpy//9//8AAAAg6cv//f///+EWNwADAAEAAAAAAAAAAAAAAAAACACEAAEAAAAAAAAAAAAAAAAxAAACAAQARAKAAsAAKwBUAAABIiYnJjQ3NzY2MzIWFxYUBwcGIicmNDc3NjQnJiYjIgYHBwYUFxYUBwYGIwciJicmNDc3NjIXFhQHBwYUFxYWMzI2Nzc2NCcmNDc2MhcWFAcHBgYjARQGDAUtLXoWOR8fORYtLTgKGwoKCjgaGg0gEhIgDXoaGgkJBQwHdR85Fi0tOAobCgoKOBoaDSASEiANehoaCQkKGwotLXoWOR8BMwUFLYEuehYXFxYugC44CQkKGwo4GkoaDQ0NDXoaShoKGwoFBe8XFi6ALjgJCQobCjgaShoNDQ0NehpKGgobCgoKLYEuehYXAAAADACWAAEAAAAAAAEACAAAAAEAAAAAAAIAAwAIAAEAAAAAAAMACAAAAAEAAAAAAAQACAAAAAEAAAAAAAUAAQALAAEAAAAAAAYACAAAAAMAAQQJAAEAEAAMAAMAAQQJAAIABgAcAAMAAQQJAAMAEAAMAAMAAQQJAAQAEAAMAAMAAQQJAAUAAgAiAAMAAQQJAAYAEAAMYW5jaG9yanM0MDBAAGEAbgBjAGgAbwByAGoAcwA0ADAAMABAAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAH//wAP) format("truetype");' + + ' }', + pseudoElContent = + ' [data-anchorjs-icon]::after {' + + ' content: attr(data-anchorjs-icon);' + + ' }', + firstStyleEl; + + style.className = 'anchorjs'; + style.appendChild(document.createTextNode('')); // Necessary for Webkit. + + // We place it in the head with the other style tags, if possible, so as to + // not look out of place. We insert before the others so these styles can be + // overridden if necessary. + firstStyleEl = document.head.querySelector('[rel="stylesheet"], style'); + if (firstStyleEl === undefined) { + document.head.appendChild(style); + } else { + document.head.insertBefore(style, firstStyleEl); + } + + style.sheet.insertRule(linkRule, style.sheet.cssRules.length); + style.sheet.insertRule(hoverRule, style.sheet.cssRules.length); + style.sheet.insertRule(pseudoElContent, style.sheet.cssRules.length); + style.sheet.insertRule(anchorjsLinkFontFace, style.sheet.cssRules.length); + } + } + + return AnchorJS; +}); diff --git a/assets/bass-addons.css b/assets/bass-addons.css new file mode 100644 index 00000000..c27e96d8 --- /dev/null +++ b/assets/bass-addons.css @@ -0,0 +1,12 @@ +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: .5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: .875rem; + border-radius: 3px; + box-sizing: border-box; +} diff --git a/assets/bass.css b/assets/bass.css new file mode 100644 index 00000000..2d860c56 --- /dev/null +++ b/assets/bass.css @@ -0,0 +1,544 @@ +/*! Basscss | http://basscss.com | MIT License */ + +.h1{ font-size: 2rem } +.h2{ font-size: 1.5rem } +.h3{ font-size: 1.25rem } +.h4{ font-size: 1rem } +.h5{ font-size: .875rem } +.h6{ font-size: .75rem } + +.font-family-inherit{ font-family:inherit } +.font-size-inherit{ font-size:inherit } +.text-decoration-none{ text-decoration:none } + +.bold{ font-weight: bold; font-weight: bold } +.regular{ font-weight:normal } +.italic{ font-style:italic } +.caps{ text-transform:uppercase; letter-spacing: .2em; } + +.left-align{ text-align:left } +.center{ text-align:center } +.right-align{ text-align:right } +.justify{ text-align:justify } + +.nowrap{ white-space:nowrap } +.break-word{ word-wrap:break-word } + +.line-height-1{ line-height: 1 } +.line-height-2{ line-height: 1.125 } +.line-height-3{ line-height: 1.25 } +.line-height-4{ line-height: 1.5 } + +.list-style-none{ list-style:none } +.underline{ text-decoration:underline } + +.truncate{ + max-width:100%; + overflow:hidden; + text-overflow:ellipsis; + white-space:nowrap; +} + +.list-reset{ + list-style:none; + padding-left:0; +} + +.inline{ display:inline } +.block{ display:block } +.inline-block{ display:inline-block } +.table{ display:table } +.table-cell{ display:table-cell } + +.overflow-hidden{ overflow:hidden } +.overflow-scroll{ overflow:scroll } +.overflow-auto{ overflow:auto } + +.clearfix:before, +.clearfix:after{ + content:" "; + display:table +} +.clearfix:after{ clear:both } + +.left{ float:left } +.right{ float:right } + +.fit{ max-width:100% } + +.max-width-1{ max-width: 24rem } +.max-width-2{ max-width: 32rem } +.max-width-3{ max-width: 48rem } +.max-width-4{ max-width: 64rem } + +.border-box{ box-sizing:border-box } + +.align-baseline{ vertical-align:baseline } +.align-top{ vertical-align:top } +.align-middle{ vertical-align:middle } +.align-bottom{ vertical-align:bottom } + +.m0{ margin:0 } +.mt0{ margin-top:0 } +.mr0{ margin-right:0 } +.mb0{ margin-bottom:0 } +.ml0{ margin-left:0 } +.mx0{ margin-left:0; margin-right:0 } +.my0{ margin-top:0; margin-bottom:0 } + +.m1{ margin: .5rem } +.mt1{ margin-top: .5rem } +.mr1{ margin-right: .5rem } +.mb1{ margin-bottom: .5rem } +.ml1{ margin-left: .5rem } +.mx1{ margin-left: .5rem; margin-right: .5rem } +.my1{ margin-top: .5rem; margin-bottom: .5rem } + +.m2{ margin: 1rem } +.mt2{ margin-top: 1rem } +.mr2{ margin-right: 1rem } +.mb2{ margin-bottom: 1rem } +.ml2{ margin-left: 1rem } +.mx2{ margin-left: 1rem; margin-right: 1rem } +.my2{ margin-top: 1rem; margin-bottom: 1rem } + +.m3{ margin: 2rem } +.mt3{ margin-top: 2rem } +.mr3{ margin-right: 2rem } +.mb3{ margin-bottom: 2rem } +.ml3{ margin-left: 2rem } +.mx3{ margin-left: 2rem; margin-right: 2rem } +.my3{ margin-top: 2rem; margin-bottom: 2rem } + +.m4{ margin: 4rem } +.mt4{ margin-top: 4rem } +.mr4{ margin-right: 4rem } +.mb4{ margin-bottom: 4rem } +.ml4{ margin-left: 4rem } +.mx4{ margin-left: 4rem; margin-right: 4rem } +.my4{ margin-top: 4rem; margin-bottom: 4rem } + +.mxn1{ margin-left: -.5rem; margin-right: -.5rem; } +.mxn2{ margin-left: -1rem; margin-right: -1rem; } +.mxn3{ margin-left: -2rem; margin-right: -2rem; } +.mxn4{ margin-left: -4rem; margin-right: -4rem; } + +.ml-auto{ margin-left:auto } +.mr-auto{ margin-right:auto } +.mx-auto{ margin-left:auto; margin-right:auto; } + +.p0{ padding:0 } +.pt0{ padding-top:0 } +.pr0{ padding-right:0 } +.pb0{ padding-bottom:0 } +.pl0{ padding-left:0 } +.px0{ padding-left:0; padding-right:0 } +.py0{ padding-top:0; padding-bottom:0 } + +.p1{ padding: .5rem } +.pt1{ padding-top: .5rem } +.pr1{ padding-right: .5rem } +.pb1{ padding-bottom: .5rem } +.pl1{ padding-left: .5rem } +.py1{ padding-top: .5rem; padding-bottom: .5rem } +.px1{ padding-left: .5rem; padding-right: .5rem } + +.p2{ padding: 1rem } +.pt2{ padding-top: 1rem } +.pr2{ padding-right: 1rem } +.pb2{ padding-bottom: 1rem } +.pl2{ padding-left: 1rem } +.py2{ padding-top: 1rem; padding-bottom: 1rem } +.px2{ padding-left: 1rem; padding-right: 1rem } + +.p3{ padding: 2rem } +.pt3{ padding-top: 2rem } +.pr3{ padding-right: 2rem } +.pb3{ padding-bottom: 2rem } +.pl3{ padding-left: 2rem } +.py3{ padding-top: 2rem; padding-bottom: 2rem } +.px3{ padding-left: 2rem; padding-right: 2rem } + +.p4{ padding: 4rem } +.pt4{ padding-top: 4rem } +.pr4{ padding-right: 4rem } +.pb4{ padding-bottom: 4rem } +.pl4{ padding-left: 4rem } +.py4{ padding-top: 4rem; padding-bottom: 4rem } +.px4{ padding-left: 4rem; padding-right: 4rem } + +.col{ + float:left; + box-sizing:border-box; +} + +.col-right{ + float:right; + box-sizing:border-box; +} + +.col-1{ + width:8.33333%; +} + +.col-2{ + width:16.66667%; +} + +.col-3{ + width:25%; +} + +.col-4{ + width:33.33333%; +} + +.col-5{ + width:41.66667%; +} + +.col-6{ + width:50%; +} + +.col-7{ + width:58.33333%; +} + +.col-8{ + width:66.66667%; +} + +.col-9{ + width:75%; +} + +.col-10{ + width:83.33333%; +} + +.col-11{ + width:91.66667%; +} + +.col-12{ + width:100%; +} +@media (min-width: 40em){ + + .sm-col{ + float:left; + box-sizing:border-box; + } + + .sm-col-right{ + float:right; + box-sizing:border-box; + } + + .sm-col-1{ + width:8.33333%; + } + + .sm-col-2{ + width:16.66667%; + } + + .sm-col-3{ + width:25%; + } + + .sm-col-4{ + width:33.33333%; + } + + .sm-col-5{ + width:41.66667%; + } + + .sm-col-6{ + width:50%; + } + + .sm-col-7{ + width:58.33333%; + } + + .sm-col-8{ + width:66.66667%; + } + + .sm-col-9{ + width:75%; + } + + .sm-col-10{ + width:83.33333%; + } + + .sm-col-11{ + width:91.66667%; + } + + .sm-col-12{ + width:100%; + } + +} +@media (min-width: 52em){ + + .md-col{ + float:left; + box-sizing:border-box; + } + + .md-col-right{ + float:right; + box-sizing:border-box; + } + + .md-col-1{ + width:8.33333%; + } + + .md-col-2{ + width:16.66667%; + } + + .md-col-3{ + width:25%; + } + + .md-col-4{ + width:33.33333%; + } + + .md-col-5{ + width:41.66667%; + } + + .md-col-6{ + width:50%; + } + + .md-col-7{ + width:58.33333%; + } + + .md-col-8{ + width:66.66667%; + } + + .md-col-9{ + width:75%; + } + + .md-col-10{ + width:83.33333%; + } + + .md-col-11{ + width:91.66667%; + } + + .md-col-12{ + width:100%; + } + +} +@media (min-width: 64em){ + + .lg-col{ + float:left; + box-sizing:border-box; + } + + .lg-col-right{ + float:right; + box-sizing:border-box; + } + + .lg-col-1{ + width:8.33333%; + } + + .lg-col-2{ + width:16.66667%; + } + + .lg-col-3{ + width:25%; + } + + .lg-col-4{ + width:33.33333%; + } + + .lg-col-5{ + width:41.66667%; + } + + .lg-col-6{ + width:50%; + } + + .lg-col-7{ + width:58.33333%; + } + + .lg-col-8{ + width:66.66667%; + } + + .lg-col-9{ + width:75%; + } + + .lg-col-10{ + width:83.33333%; + } + + .lg-col-11{ + width:91.66667%; + } + + .lg-col-12{ + width:100%; + } + +} +.flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } + +@media (min-width: 40em){ + .sm-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +@media (min-width: 52em){ + .md-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +@media (min-width: 64em){ + .lg-flex{ display:-webkit-box; display:-webkit-flex; display:-ms-flexbox; display:flex } +} + +.flex-column{ -webkit-box-orient:vertical; -webkit-box-direction:normal; -webkit-flex-direction:column; -ms-flex-direction:column; flex-direction:column } +.flex-wrap{ -webkit-flex-wrap:wrap; -ms-flex-wrap:wrap; flex-wrap:wrap } + +.items-start{ -webkit-box-align:start; -webkit-align-items:flex-start; -ms-flex-align:start; -ms-grid-row-align:flex-start; align-items:flex-start } +.items-end{ -webkit-box-align:end; -webkit-align-items:flex-end; -ms-flex-align:end; -ms-grid-row-align:flex-end; align-items:flex-end } +.items-center{ -webkit-box-align:center; -webkit-align-items:center; -ms-flex-align:center; -ms-grid-row-align:center; align-items:center } +.items-baseline{ -webkit-box-align:baseline; -webkit-align-items:baseline; -ms-flex-align:baseline; -ms-grid-row-align:baseline; align-items:baseline } +.items-stretch{ -webkit-box-align:stretch; -webkit-align-items:stretch; -ms-flex-align:stretch; -ms-grid-row-align:stretch; align-items:stretch } + +.self-start{ -webkit-align-self:flex-start; -ms-flex-item-align:start; align-self:flex-start } +.self-end{ -webkit-align-self:flex-end; -ms-flex-item-align:end; align-self:flex-end } +.self-center{ -webkit-align-self:center; -ms-flex-item-align:center; align-self:center } +.self-baseline{ -webkit-align-self:baseline; -ms-flex-item-align:baseline; align-self:baseline } +.self-stretch{ -webkit-align-self:stretch; -ms-flex-item-align:stretch; align-self:stretch } + +.justify-start{ -webkit-box-pack:start; -webkit-justify-content:flex-start; -ms-flex-pack:start; justify-content:flex-start } +.justify-end{ -webkit-box-pack:end; -webkit-justify-content:flex-end; -ms-flex-pack:end; justify-content:flex-end } +.justify-center{ -webkit-box-pack:center; -webkit-justify-content:center; -ms-flex-pack:center; justify-content:center } +.justify-between{ -webkit-box-pack:justify; -webkit-justify-content:space-between; -ms-flex-pack:justify; justify-content:space-between } +.justify-around{ -webkit-justify-content:space-around; -ms-flex-pack:distribute; justify-content:space-around } + +.content-start{ -webkit-align-content:flex-start; -ms-flex-line-pack:start; align-content:flex-start } +.content-end{ -webkit-align-content:flex-end; -ms-flex-line-pack:end; align-content:flex-end } +.content-center{ -webkit-align-content:center; -ms-flex-line-pack:center; align-content:center } +.content-between{ -webkit-align-content:space-between; -ms-flex-line-pack:justify; align-content:space-between } +.content-around{ -webkit-align-content:space-around; -ms-flex-line-pack:distribute; align-content:space-around } +.content-stretch{ -webkit-align-content:stretch; -ms-flex-line-pack:stretch; align-content:stretch } +.flex-auto{ + -webkit-box-flex:1; + -webkit-flex:1 1 auto; + -ms-flex:1 1 auto; + flex:1 1 auto; + min-width:0; + min-height:0; +} +.flex-none{ -webkit-box-flex:0; -webkit-flex:none; -ms-flex:none; flex:none } +.fs0{ flex-shrink: 0 } + +.order-0{ -webkit-box-ordinal-group:1; -webkit-order:0; -ms-flex-order:0; order:0 } +.order-1{ -webkit-box-ordinal-group:2; -webkit-order:1; -ms-flex-order:1; order:1 } +.order-2{ -webkit-box-ordinal-group:3; -webkit-order:2; -ms-flex-order:2; order:2 } +.order-3{ -webkit-box-ordinal-group:4; -webkit-order:3; -ms-flex-order:3; order:3 } +.order-last{ -webkit-box-ordinal-group:100000; -webkit-order:99999; -ms-flex-order:99999; order:99999 } + +.relative{ position:relative } +.absolute{ position:absolute } +.fixed{ position:fixed } + +.top-0{ top:0 } +.right-0{ right:0 } +.bottom-0{ bottom:0 } +.left-0{ left:0 } + +.z1{ z-index: 1 } +.z2{ z-index: 2 } +.z3{ z-index: 3 } +.z4{ z-index: 4 } + +.border{ + border-style:solid; + border-width: 1px; +} + +.border-top{ + border-top-style:solid; + border-top-width: 1px; +} + +.border-right{ + border-right-style:solid; + border-right-width: 1px; +} + +.border-bottom{ + border-bottom-style:solid; + border-bottom-width: 1px; +} + +.border-left{ + border-left-style:solid; + border-left-width: 1px; +} + +.border-none{ border:0 } + +.rounded{ border-radius: 3px } +.circle{ border-radius:50% } + +.rounded-top{ border-radius: 3px 3px 0 0 } +.rounded-right{ border-radius: 0 3px 3px 0 } +.rounded-bottom{ border-radius: 0 0 3px 3px } +.rounded-left{ border-radius: 3px 0 0 3px } + +.not-rounded{ border-radius:0 } + +.hide{ + position:absolute !important; + height:1px; + width:1px; + overflow:hidden; + clip:rect(1px, 1px, 1px, 1px); +} + +@media (max-width: 40em){ + .xs-hide{ display:none !important } +} + +@media (min-width: 40em) and (max-width: 52em){ + .sm-hide{ display:none !important } +} + +@media (min-width: 52em) and (max-width: 64em){ + .md-hide{ display:none !important } +} + +@media (min-width: 64em){ + .lg-hide{ display:none !important } +} + +.display-none{ display:none !important } + diff --git a/assets/fonts/EOT/SourceCodePro-Bold.eot b/assets/fonts/EOT/SourceCodePro-Bold.eot new file mode 100755 index 00000000..d24cc39f Binary files /dev/null and b/assets/fonts/EOT/SourceCodePro-Bold.eot differ diff --git a/assets/fonts/EOT/SourceCodePro-Regular.eot b/assets/fonts/EOT/SourceCodePro-Regular.eot new file mode 100755 index 00000000..09e94730 Binary files /dev/null and b/assets/fonts/EOT/SourceCodePro-Regular.eot differ diff --git a/assets/fonts/LICENSE.txt b/assets/fonts/LICENSE.txt new file mode 100755 index 00000000..d154618a --- /dev/null +++ b/assets/fonts/LICENSE.txt @@ -0,0 +1,93 @@ +Copyright 2010, 2012 Adobe Systems Incorporated (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe Systems Incorporated in the United States and/or other countries. + +This Font Software is licensed under the SIL Open Font License, Version 1.1. + +This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/assets/fonts/OTF/SourceCodePro-Bold.otf b/assets/fonts/OTF/SourceCodePro-Bold.otf new file mode 100755 index 00000000..f4e576ce Binary files /dev/null and b/assets/fonts/OTF/SourceCodePro-Bold.otf differ diff --git a/assets/fonts/OTF/SourceCodePro-Regular.otf b/assets/fonts/OTF/SourceCodePro-Regular.otf new file mode 100755 index 00000000..4e3b9d0b Binary files /dev/null and b/assets/fonts/OTF/SourceCodePro-Regular.otf differ diff --git a/assets/fonts/TTF/SourceCodePro-Bold.ttf b/assets/fonts/TTF/SourceCodePro-Bold.ttf new file mode 100755 index 00000000..e0c576f1 Binary files /dev/null and b/assets/fonts/TTF/SourceCodePro-Bold.ttf differ diff --git a/assets/fonts/TTF/SourceCodePro-Regular.ttf b/assets/fonts/TTF/SourceCodePro-Regular.ttf new file mode 100755 index 00000000..437f4728 Binary files /dev/null and b/assets/fonts/TTF/SourceCodePro-Regular.ttf differ diff --git a/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff b/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff new file mode 100755 index 00000000..cf960992 Binary files /dev/null and b/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff differ diff --git a/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff b/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff new file mode 100755 index 00000000..395436eb Binary files /dev/null and b/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff differ diff --git a/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff b/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff new file mode 100755 index 00000000..c65ba841 Binary files /dev/null and b/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff differ diff --git a/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff b/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff new file mode 100755 index 00000000..0af792a1 Binary files /dev/null and b/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff differ diff --git a/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 b/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 new file mode 100755 index 00000000..cbe38353 Binary files /dev/null and b/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 differ diff --git a/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 b/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 new file mode 100755 index 00000000..65cd591b Binary files /dev/null and b/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 differ diff --git a/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 b/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 new file mode 100755 index 00000000..b78d5235 Binary files /dev/null and b/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 differ diff --git a/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 b/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 new file mode 100755 index 00000000..18d2199e Binary files /dev/null and b/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 differ diff --git a/assets/fonts/source-code-pro.css b/assets/fonts/source-code-pro.css new file mode 100755 index 00000000..3abb4f09 --- /dev/null +++ b/assets/fonts/source-code-pro.css @@ -0,0 +1,23 @@ +@font-face{ + font-family: 'Source Code Pro'; + font-weight: 400; + font-style: normal; + font-stretch: normal; + src: url('EOT/SourceCodePro-Regular.eot') format('embedded-opentype'), + url('WOFF2/TTF/SourceCodePro-Regular.ttf.woff2') format('woff2'), + url('WOFF/OTF/SourceCodePro-Regular.otf.woff') format('woff'), + url('OTF/SourceCodePro-Regular.otf') format('opentype'), + url('TTF/SourceCodePro-Regular.ttf') format('truetype'); +} + +@font-face{ + font-family: 'Source Code Pro'; + font-weight: 700; + font-style: normal; + font-stretch: normal; + src: url('EOT/SourceCodePro-Bold.eot') format('embedded-opentype'), + url('WOFF2/TTF/SourceCodePro-Bold.ttf.woff2') format('woff2'), + url('WOFF/OTF/SourceCodePro-Bold.otf.woff') format('woff'), + url('OTF/SourceCodePro-Bold.otf') format('opentype'), + url('TTF/SourceCodePro-Bold.ttf') format('truetype'); +} diff --git a/assets/github.css b/assets/github.css new file mode 100644 index 00000000..8852abb4 --- /dev/null +++ b/assets/github.css @@ -0,0 +1,123 @@ +/* + +github.com style (c) Vasily Polovnyov + +*/ + +.hljs { + display: block; + overflow-x: auto; + padding: 0.5em; + color: #333; + background: #f8f8f8; + -webkit-text-size-adjust: none; +} + +.hljs-comment, +.diff .hljs-header, +.hljs-javadoc { + color: #998; + font-style: italic; +} + +.hljs-keyword, +.css .rule .hljs-keyword, +.hljs-winutils, +.nginx .hljs-title, +.hljs-subst, +.hljs-request, +.hljs-status { + color: #1184CE; +} + +.hljs-number, +.hljs-hexcolor, +.ruby .hljs-constant { + color: #ed225d; +} + +.hljs-string, +.hljs-tag .hljs-value, +.hljs-phpdoc, +.hljs-dartdoc, +.tex .hljs-formula { + color: #ed225d; +} + +.hljs-title, +.hljs-id, +.scss .hljs-preprocessor { + color: #900; + font-weight: bold; +} + +.hljs-list .hljs-keyword, +.hljs-subst { + font-weight: normal; +} + +.hljs-class .hljs-title, +.hljs-type, +.vhdl .hljs-literal, +.tex .hljs-command { + color: #458; + font-weight: bold; +} + +.hljs-tag, +.hljs-tag .hljs-title, +.hljs-rules .hljs-property, +.django .hljs-tag .hljs-keyword { + color: #000080; + font-weight: normal; +} + +.hljs-attribute, +.hljs-variable, +.lisp .hljs-body { + color: #008080; +} + +.hljs-regexp { + color: #009926; +} + +.hljs-symbol, +.ruby .hljs-symbol .hljs-string, +.lisp .hljs-keyword, +.clojure .hljs-keyword, +.scheme .hljs-keyword, +.tex .hljs-special, +.hljs-prompt { + color: #990073; +} + +.hljs-built_in { + color: #0086b3; +} + +.hljs-preprocessor, +.hljs-pragma, +.hljs-pi, +.hljs-doctype, +.hljs-shebang, +.hljs-cdata { + color: #999; + font-weight: bold; +} + +.hljs-deletion { + background: #fdd; +} + +.hljs-addition { + background: #dfd; +} + +.diff .hljs-change { + background: #0086b3; +} + +.hljs-chunk { + color: #aaa; +} diff --git a/assets/site.js b/assets/site.js new file mode 100644 index 00000000..a624be7b --- /dev/null +++ b/assets/site.js @@ -0,0 +1,168 @@ +/* global anchors */ + +// add anchor links to headers +anchors.options.placement = 'left'; +anchors.add('h3'); + +// Filter UI +var tocElements = document.getElementById('toc').getElementsByTagName('li'); + +document.getElementById('filter-input').addEventListener('keyup', function (e) { + var i, element, children; + + // enter key + if (e.keyCode === 13) { + // go to the first displayed item in the toc + for (i = 0; i < tocElements.length; i++) { + element = tocElements[i]; + if (!element.classList.contains('display-none')) { + location.replace(element.firstChild.href); + return e.preventDefault(); + } + } + } + + var match = function () { + return true; + }; + + var value = this.value.toLowerCase(); + + if (!value.match(/^\s*$/)) { + match = function (element) { + var html = element.firstChild.innerHTML; + return html && html.toLowerCase().indexOf(value) !== -1; + }; + } + + for (i = 0; i < tocElements.length; i++) { + element = tocElements[i]; + children = Array.from(element.getElementsByTagName('li')); + if (match(element) || children.some(match)) { + element.classList.remove('display-none'); + } else { + element.classList.add('display-none'); + } + } +}); + +var items = document.getElementsByClassName('toggle-sibling'); +for (var j = 0; j < items.length; j++) { + items[j].addEventListener('click', toggleSibling); +} + +function toggleSibling() { + var stepSibling = this.parentNode.getElementsByClassName('toggle-target')[0]; + var icon = this.getElementsByClassName('icon')[0]; + var klass = 'display-none'; + if (stepSibling.classList.contains(klass)) { + stepSibling.classList.remove(klass); + icon.innerHTML = '▾'; + } else { + stepSibling.classList.add(klass); + icon.innerHTML = '▸'; + } +} + +function showHashTarget(targetId) { + if (targetId) { + var hashTarget = document.getElementById(targetId); + // new target is hidden + if ( + hashTarget && + hashTarget.offsetHeight === 0 && + hashTarget.parentNode.parentNode.classList.contains('display-none') + ) { + hashTarget.parentNode.parentNode.classList.remove('display-none'); + } + } +} + +function scrollIntoView(targetId) { + // Only scroll to element if we don't have a stored scroll position. + if (targetId && !history.state) { + var hashTarget = document.getElementById(targetId); + if (hashTarget) { + hashTarget.scrollIntoView(); + } + } +} + +function gotoCurrentTarget() { + showHashTarget(location.hash.substring(1)); + scrollIntoView(location.hash.substring(1)); +} + +window.addEventListener('hashchange', gotoCurrentTarget); +gotoCurrentTarget(); + +var toclinks = document.getElementsByClassName('pre-open'); +for (var k = 0; k < toclinks.length; k++) { + toclinks[k].addEventListener('mousedown', preOpen, false); +} + +function preOpen() { + showHashTarget(this.hash.substring(1)); +} + +var split_left = document.querySelector('#split-left'); +var split_right = document.querySelector('#split-right'); +var split_parent = split_left.parentNode; +var cw_with_sb = split_left.clientWidth; +split_left.style.overflow = 'hidden'; +var cw_without_sb = split_left.clientWidth; +split_left.style.overflow = ''; + +Split(['#split-left', '#split-right'], { + elementStyle: function (dimension, size, gutterSize) { + return { + 'flex-basis': 'calc(' + size + '% - ' + gutterSize + 'px)' + }; + }, + gutterStyle: function (dimension, gutterSize) { + return { + 'flex-basis': gutterSize + 'px' + }; + }, + gutterSize: 20, + sizes: [33, 67] +}); + +// Chrome doesn't remember scroll position properly so do it ourselves. +// Also works on Firefox and Edge. + +function updateState() { + history.replaceState( + { + left_top: split_left.scrollTop, + right_top: split_right.scrollTop + }, + document.title + ); +} + +function loadState(ev) { + if (ev) { + // Edge doesn't replace change history.state on popstate. + history.replaceState(ev.state, document.title); + } + if (history.state) { + split_left.scrollTop = history.state.left_top; + split_right.scrollTop = history.state.right_top; + } +} + +window.addEventListener('load', function () { + // Restore after Firefox scrolls to hash. + setTimeout(function () { + loadState(); + // Update with initial scroll position. + updateState(); + // Update scroll positions only after we've loaded because Firefox + // emits an initial scroll event with 0. + split_left.addEventListener('scroll', updateState); + split_right.addEventListener('scroll', updateState); + }, 1); +}); + +window.addEventListener('popstate', loadState); diff --git a/assets/split.css b/assets/split.css new file mode 100644 index 00000000..2d7779ee --- /dev/null +++ b/assets/split.css @@ -0,0 +1,15 @@ +.gutter { + background-color: #f5f5f5; + background-repeat: no-repeat; + background-position: 50%; +} + +.gutter.gutter-vertical { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAFAQMAAABo7865AAAABlBMVEVHcEzMzMzyAv2sAAAAAXRSTlMAQObYZgAAABBJREFUeF5jOAMEEAIEEFwAn3kMwcB6I2AAAAAASUVORK5CYII='); + cursor: ns-resize; +} + +.gutter.gutter-horizontal { + background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAIklEQVQoU2M4c+bMfxAGAgYYmwGrIIiDjrELjpo5aiZeMwF+yNnOs5KSvgAAAABJRU5ErkJggg=='); + cursor: ew-resize; +} diff --git a/assets/split.js b/assets/split.js new file mode 100644 index 00000000..71f9a60b --- /dev/null +++ b/assets/split.js @@ -0,0 +1,782 @@ +/*! Split.js - v1.5.11 */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.Split = factory()); +}(this, (function () { 'use strict'; + + // The programming goals of Split.js are to deliver readable, understandable and + // maintainable code, while at the same time manually optimizing for tiny minified file size, + // browser compatibility without additional requirements, graceful fallback (IE8 is supported) + // and very few assumptions about the user's page layout. + var global = window; + var document = global.document; + + // Save a couple long function names that are used frequently. + // This optimization saves around 400 bytes. + var addEventListener = 'addEventListener'; + var removeEventListener = 'removeEventListener'; + var getBoundingClientRect = 'getBoundingClientRect'; + var gutterStartDragging = '_a'; + var aGutterSize = '_b'; + var bGutterSize = '_c'; + var HORIZONTAL = 'horizontal'; + var NOOP = function () { return false; }; + + // Figure out if we're in IE8 or not. IE8 will still render correctly, + // but will be static instead of draggable. + var isIE8 = global.attachEvent && !global[addEventListener]; + + // Helper function determines which prefixes of CSS calc we need. + // We only need to do this once on startup, when this anonymous function is called. + // + // Tests -webkit, -moz and -o prefixes. Modified from StackOverflow: + // http://stackoverflow.com/questions/16625140/js-feature-detection-to-detect-the-usage-of-webkit-calc-over-calc/16625167#16625167 + var calc = (['', '-webkit-', '-moz-', '-o-'] + .filter(function (prefix) { + var el = document.createElement('div'); + el.style.cssText = "width:" + prefix + "calc(9px)"; + + return !!el.style.length + }) + .shift()) + "calc"; + + // Helper function checks if its argument is a string-like type + var isString = function (v) { return typeof v === 'string' || v instanceof String; }; + + // Helper function allows elements and string selectors to be used + // interchangeably. In either case an element is returned. This allows us to + // do `Split([elem1, elem2])` as well as `Split(['#id1', '#id2'])`. + var elementOrSelector = function (el) { + if (isString(el)) { + var ele = document.querySelector(el); + if (!ele) { + throw new Error(("Selector " + el + " did not match a DOM element")) + } + return ele + } + + return el + }; + + // Helper function gets a property from the properties object, with a default fallback + var getOption = function (options, propName, def) { + var value = options[propName]; + if (value !== undefined) { + return value + } + return def + }; + + var getGutterSize = function (gutterSize, isFirst, isLast, gutterAlign) { + if (isFirst) { + if (gutterAlign === 'end') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } else if (isLast) { + if (gutterAlign === 'start') { + return 0 + } + if (gutterAlign === 'center') { + return gutterSize / 2 + } + } + + return gutterSize + }; + + // Default options + var defaultGutterFn = function (i, gutterDirection) { + var gut = document.createElement('div'); + gut.className = "gutter gutter-" + gutterDirection; + return gut + }; + + var defaultElementStyleFn = function (dim, size, gutSize) { + var style = {}; + + if (!isString(size)) { + if (!isIE8) { + style[dim] = calc + "(" + size + "% - " + gutSize + "px)"; + } else { + style[dim] = size + "%"; + } + } else { + style[dim] = size; + } + + return style + }; + + var defaultGutterStyleFn = function (dim, gutSize) { + var obj; + + return (( obj = {}, obj[dim] = (gutSize + "px"), obj )); + }; + + // The main function to initialize a split. Split.js thinks about each pair + // of elements as an independant pair. Dragging the gutter between two elements + // only changes the dimensions of elements in that pair. This is key to understanding + // how the following functions operate, since each function is bound to a pair. + // + // A pair object is shaped like this: + // + // { + // a: DOM element, + // b: DOM element, + // aMin: Number, + // bMin: Number, + // dragging: Boolean, + // parent: DOM element, + // direction: 'horizontal' | 'vertical' + // } + // + // The basic sequence: + // + // 1. Set defaults to something sane. `options` doesn't have to be passed at all. + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + // 3. Define the dragging helper functions, and a few helpers to go with them. + // 4. Loop through the elements while pairing them off. Every pair gets an + // `pair` object and a gutter. + // 5. Actually size the pair elements, insert gutters and attach event listeners. + var Split = function (idsOption, options) { + if ( options === void 0 ) options = {}; + + var ids = idsOption; + var dimension; + var clientAxis; + var position; + var positionEnd; + var clientSize; + var elements; + + // Allow HTMLCollection to be used as an argument when supported + if (Array.from) { + ids = Array.from(ids); + } + + // All DOM elements in the split should have a common parent. We can grab + // the first elements parent and hope users read the docs because the + // behavior will be whacky otherwise. + var firstElement = elementOrSelector(ids[0]); + var parent = firstElement.parentNode; + var parentStyle = getComputedStyle ? getComputedStyle(parent) : null; + var parentFlexDirection = parentStyle ? parentStyle.flexDirection : null; + + // Set default options.sizes to equal percentages of the parent element. + var sizes = getOption(options, 'sizes') || ids.map(function () { return 100 / ids.length; }); + + // Standardize minSize to an array if it isn't already. This allows minSize + // to be passed as a number. + var minSize = getOption(options, 'minSize', 100); + var minSizes = Array.isArray(minSize) ? minSize : ids.map(function () { return minSize; }); + + // Get other options + var expandToMin = getOption(options, 'expandToMin', false); + var gutterSize = getOption(options, 'gutterSize', 10); + var gutterAlign = getOption(options, 'gutterAlign', 'center'); + var snapOffset = getOption(options, 'snapOffset', 30); + var dragInterval = getOption(options, 'dragInterval', 1); + var direction = getOption(options, 'direction', HORIZONTAL); + var cursor = getOption( + options, + 'cursor', + direction === HORIZONTAL ? 'col-resize' : 'row-resize' + ); + var gutter = getOption(options, 'gutter', defaultGutterFn); + var elementStyle = getOption( + options, + 'elementStyle', + defaultElementStyleFn + ); + var gutterStyle = getOption(options, 'gutterStyle', defaultGutterStyleFn); + + // 2. Initialize a bunch of strings based on the direction we're splitting. + // A lot of the behavior in the rest of the library is paramatized down to + // rely on CSS strings and classes. + if (direction === HORIZONTAL) { + dimension = 'width'; + clientAxis = 'clientX'; + position = 'left'; + positionEnd = 'right'; + clientSize = 'clientWidth'; + } else if (direction === 'vertical') { + dimension = 'height'; + clientAxis = 'clientY'; + position = 'top'; + positionEnd = 'bottom'; + clientSize = 'clientHeight'; + } + + // 3. Define the dragging helper functions, and a few helpers to go with them. + // Each helper is bound to a pair object that contains its metadata. This + // also makes it easy to store references to listeners that that will be + // added and removed. + // + // Even though there are no other functions contained in them, aliasing + // this to self saves 50 bytes or so since it's used so frequently. + // + // The pair object saves metadata like dragging state, position and + // event listener references. + + function setElementSize(el, size, gutSize, i) { + // Split.js allows setting sizes via numbers (ideally), or if you must, + // by string, like '300px'. This is less than ideal, because it breaks + // the fluid layout that `calc(% - px)` provides. You're on your own if you do that, + // make sure you calculate the gutter size by hand. + var style = elementStyle(dimension, size, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + el.style[prop] = style[prop]; + }); + } + + function setGutterSize(gutterElement, gutSize, i) { + var style = gutterStyle(dimension, gutSize, i); + + Object.keys(style).forEach(function (prop) { + // eslint-disable-next-line no-param-reassign + gutterElement.style[prop] = style[prop]; + }); + } + + function getSizes() { + return elements.map(function (element) { return element.size; }) + } + + // Supports touch events, but not multitouch, so only the first + // finger `touches[0]` is counted. + function getMousePosition(e) { + if ('touches' in e) { return e.touches[0][clientAxis] } + return e[clientAxis] + } + + // Actually adjust the size of elements `a` and `b` to `offset` while dragging. + // calc is used to allow calc(percentage + gutterpx) on the whole split instance, + // which allows the viewport to be resized without additional logic. + // Element a's size is the same as offset. b's size is total size - a size. + // Both sizes are calculated from the initial parent percentage, + // then the gutter size is subtracted. + function adjust(offset) { + var a = elements[this.a]; + var b = elements[this.b]; + var percentage = a.size + b.size; + + a.size = (offset / this.size) * percentage; + b.size = percentage - (offset / this.size) * percentage; + + setElementSize(a.element, a.size, this[aGutterSize], a.i); + setElementSize(b.element, b.size, this[bGutterSize], b.i); + } + + // drag, where all the magic happens. The logic is really quite simple: + // + // 1. Ignore if the pair is not dragging. + // 2. Get the offset of the event. + // 3. Snap offset to min if within snappable range (within min + snapOffset). + // 4. Actually adjust each element in the pair to offset. + // + // --------------------------------------------------------------------- + // | | <- a.minSize || b.minSize -> | | + // | | | <- this.snapOffset || this.snapOffset -> | | | + // | | | || | | | + // | | | || | | | + // --------------------------------------------------------------------- + // | <- this.start this.size -> | + function drag(e) { + var offset; + var a = elements[this.a]; + var b = elements[this.b]; + + if (!this.dragging) { return } + + // Get the offset of the event from the first side of the + // pair `this.start`. Then offset by the initial position of the + // mouse compared to the gutter size. + offset = + getMousePosition(e) - + this.start + + (this[aGutterSize] - this.dragOffset); + + if (dragInterval > 1) { + offset = Math.round(offset / dragInterval) * dragInterval; + } + + // If within snapOffset of min or max, set offset to min or max. + // snapOffset buffers a.minSize and b.minSize, so logic is opposite for both. + // Include the appropriate gutter sizes to prevent overflows. + if (offset <= a.minSize + snapOffset + this[aGutterSize]) { + offset = a.minSize + this[aGutterSize]; + } else if ( + offset >= + this.size - (b.minSize + snapOffset + this[bGutterSize]) + ) { + offset = this.size - (b.minSize + this[bGutterSize]); + } + + // Actually adjust the size. + adjust.call(this, offset); + + // Call the drag callback continously. Don't do anything too intensive + // in this callback. + getOption(options, 'onDrag', NOOP)(); + } + + // Cache some important sizes when drag starts, so we don't have to do that + // continously: + // + // `size`: The total size of the pair. First + second + first gutter + second gutter. + // `start`: The leading side of the first element. + // + // ------------------------------------------------ + // | aGutterSize -> ||| | + // | ||| | + // | ||| | + // | ||| <- bGutterSize | + // ------------------------------------------------ + // | <- start size -> | + function calculateSizes() { + // Figure out the parent size minus padding. + var a = elements[this.a].element; + var b = elements[this.b].element; + + var aBounds = a[getBoundingClientRect](); + var bBounds = b[getBoundingClientRect](); + + this.size = + aBounds[dimension] + + bBounds[dimension] + + this[aGutterSize] + + this[bGutterSize]; + this.start = aBounds[position]; + this.end = aBounds[positionEnd]; + } + + function innerSize(element) { + // Return nothing if getComputedStyle is not supported (< IE9) + // Or if parent element has no layout yet + if (!getComputedStyle) { return null } + + var computedStyle = getComputedStyle(element); + + if (!computedStyle) { return null } + + var size = element[clientSize]; + + if (size === 0) { return null } + + if (direction === HORIZONTAL) { + size -= + parseFloat(computedStyle.paddingLeft) + + parseFloat(computedStyle.paddingRight); + } else { + size -= + parseFloat(computedStyle.paddingTop) + + parseFloat(computedStyle.paddingBottom); + } + + return size + } + + // When specifying percentage sizes that are less than the computed + // size of the element minus the gutter, the lesser percentages must be increased + // (and decreased from the other elements) to make space for the pixels + // subtracted by the gutters. + function trimToMin(sizesToTrim) { + // Try to get inner size of parent element. + // If it's no supported, return original sizes. + var parentSize = innerSize(parent); + if (parentSize === null) { + return sizesToTrim + } + + if (minSizes.reduce(function (a, b) { return a + b; }, 0) > parentSize) { + return sizesToTrim + } + + // Keep track of the excess pixels, the amount of pixels over the desired percentage + // Also keep track of the elements with pixels to spare, to decrease after if needed + var excessPixels = 0; + var toSpare = []; + + var pixelSizes = sizesToTrim.map(function (size, i) { + // Convert requested percentages to pixel sizes + var pixelSize = (parentSize * size) / 100; + var elementGutterSize = getGutterSize( + gutterSize, + i === 0, + i === sizesToTrim.length - 1, + gutterAlign + ); + var elementMinSize = minSizes[i] + elementGutterSize; + + // If element is too smal, increase excess pixels by the difference + // and mark that it has no pixels to spare + if (pixelSize < elementMinSize) { + excessPixels += elementMinSize - pixelSize; + toSpare.push(0); + return elementMinSize + } + + // Otherwise, mark the pixels it has to spare and return it's original size + toSpare.push(pixelSize - elementMinSize); + return pixelSize + }); + + // If nothing was adjusted, return the original sizes + if (excessPixels === 0) { + return sizesToTrim + } + + return pixelSizes.map(function (pixelSize, i) { + var newPixelSize = pixelSize; + + // While there's still pixels to take, and there's enough pixels to spare, + // take as many as possible up to the total excess pixels + if (excessPixels > 0 && toSpare[i] - excessPixels > 0) { + var takenPixels = Math.min( + excessPixels, + toSpare[i] - excessPixels + ); + + // Subtract the amount taken for the next iteration + excessPixels -= takenPixels; + newPixelSize = pixelSize - takenPixels; + } + + // Return the pixel size adjusted as a percentage + return (newPixelSize / parentSize) * 100 + }) + } + + // stopDragging is very similar to startDragging in reverse. + function stopDragging() { + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + if (self.dragging) { + getOption(options, 'onDragEnd', NOOP)(getSizes()); + } + + self.dragging = false; + + // Remove the stored event listeners. This is why we store them. + global[removeEventListener]('mouseup', self.stop); + global[removeEventListener]('touchend', self.stop); + global[removeEventListener]('touchcancel', self.stop); + global[removeEventListener]('mousemove', self.move); + global[removeEventListener]('touchmove', self.move); + + // Clear bound function references + self.stop = null; + self.move = null; + + a[removeEventListener]('selectstart', NOOP); + a[removeEventListener]('dragstart', NOOP); + b[removeEventListener]('selectstart', NOOP); + b[removeEventListener]('dragstart', NOOP); + + a.style.userSelect = ''; + a.style.webkitUserSelect = ''; + a.style.MozUserSelect = ''; + a.style.pointerEvents = ''; + + b.style.userSelect = ''; + b.style.webkitUserSelect = ''; + b.style.MozUserSelect = ''; + b.style.pointerEvents = ''; + + self.gutter.style.cursor = ''; + self.parent.style.cursor = ''; + document.body.style.cursor = ''; + } + + // startDragging calls `calculateSizes` to store the inital size in the pair object. + // It also adds event listeners for mouse/touch events, + // and prevents selection while dragging so avoid the selecting text. + function startDragging(e) { + // Right-clicking can't start dragging. + if ('button' in e && e.button !== 0) { + return + } + + // Alias frequently used variables to save space. 200 bytes. + var self = this; + var a = elements[self.a].element; + var b = elements[self.b].element; + + // Call the onDragStart callback. + if (!self.dragging) { + getOption(options, 'onDragStart', NOOP)(getSizes()); + } + + // Don't actually drag the element. We emulate that in the drag function. + e.preventDefault(); + + // Set the dragging property of the pair object. + self.dragging = true; + + // Create two event listeners bound to the same pair object and store + // them in the pair object. + self.move = drag.bind(self); + self.stop = stopDragging.bind(self); + + // All the binding. `window` gets the stop events in case we drag out of the elements. + global[addEventListener]('mouseup', self.stop); + global[addEventListener]('touchend', self.stop); + global[addEventListener]('touchcancel', self.stop); + global[addEventListener]('mousemove', self.move); + global[addEventListener]('touchmove', self.move); + + // Disable selection. Disable! + a[addEventListener]('selectstart', NOOP); + a[addEventListener]('dragstart', NOOP); + b[addEventListener]('selectstart', NOOP); + b[addEventListener]('dragstart', NOOP); + + a.style.userSelect = 'none'; + a.style.webkitUserSelect = 'none'; + a.style.MozUserSelect = 'none'; + a.style.pointerEvents = 'none'; + + b.style.userSelect = 'none'; + b.style.webkitUserSelect = 'none'; + b.style.MozUserSelect = 'none'; + b.style.pointerEvents = 'none'; + + // Set the cursor at multiple levels + self.gutter.style.cursor = cursor; + self.parent.style.cursor = cursor; + document.body.style.cursor = cursor; + + // Cache the initial sizes of the pair. + calculateSizes.call(self); + + // Determine the position of the mouse compared to the gutter + self.dragOffset = getMousePosition(e) - self.end; + } + + // adjust sizes to ensure percentage is within min size and gutter. + sizes = trimToMin(sizes); + + // 5. Create pair and element objects. Each pair has an index reference to + // elements `a` and `b` of the pair (first and second elements). + // Loop through the elements while pairing them off. Every pair gets a + // `pair` object and a gutter. + // + // Basic logic: + // + // - Starting with the second element `i > 0`, create `pair` objects with + // `a = i - 1` and `b = i` + // - Set gutter sizes based on the _pair_ being first/last. The first and last + // pair have gutterSize / 2, since they only have one half gutter, and not two. + // - Create gutter elements and add event listeners. + // - Set the size of the elements, minus the gutter sizes. + // + // ----------------------------------------------------------------------- + // | i=0 | i=1 | i=2 | i=3 | + // | | | | | + // | pair 0 pair 1 pair 2 | + // | | | | | + // ----------------------------------------------------------------------- + var pairs = []; + elements = ids.map(function (id, i) { + // Create the element object. + var element = { + element: elementOrSelector(id), + size: sizes[i], + minSize: minSizes[i], + i: i, + }; + + var pair; + + if (i > 0) { + // Create the pair object with its metadata. + pair = { + a: i - 1, + b: i, + dragging: false, + direction: direction, + parent: parent, + }; + + pair[aGutterSize] = getGutterSize( + gutterSize, + i - 1 === 0, + false, + gutterAlign + ); + pair[bGutterSize] = getGutterSize( + gutterSize, + false, + i === ids.length - 1, + gutterAlign + ); + + // if the parent has a reverse flex-direction, switch the pair elements. + if ( + parentFlexDirection === 'row-reverse' || + parentFlexDirection === 'column-reverse' + ) { + var temp = pair.a; + pair.a = pair.b; + pair.b = temp; + } + } + + // Determine the size of the current element. IE8 is supported by + // staticly assigning sizes without draggable gutters. Assigns a string + // to `size`. + // + // IE9 and above + if (!isIE8) { + // Create gutter elements for each pair. + if (i > 0) { + var gutterElement = gutter(i, direction, element.element); + setGutterSize(gutterElement, gutterSize, i); + + // Save bound event listener for removal later + pair[gutterStartDragging] = startDragging.bind(pair); + + // Attach bound event listener + gutterElement[addEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + gutterElement[addEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + + parent.insertBefore(gutterElement, element.element); + + pair.gutter = gutterElement; + } + } + + setElementSize( + element.element, + element.size, + getGutterSize( + gutterSize, + i === 0, + i === ids.length - 1, + gutterAlign + ), + i + ); + + // After the first iteration, and we have a pair object, append it to the + // list of pairs. + if (i > 0) { + pairs.push(pair); + } + + return element + }); + + function adjustToMin(element) { + var isLast = element.i === pairs.length; + var pair = isLast ? pairs[element.i - 1] : pairs[element.i]; + + calculateSizes.call(pair); + + var size = isLast + ? pair.size - element.minSize - pair[bGutterSize] + : element.minSize + pair[aGutterSize]; + + adjust.call(pair, size); + } + + elements.forEach(function (element) { + var computedSize = element.element[getBoundingClientRect]()[dimension]; + + if (computedSize < element.minSize) { + if (expandToMin) { + adjustToMin(element); + } else { + // eslint-disable-next-line no-param-reassign + element.minSize = computedSize; + } + } + }); + + function setSizes(newSizes) { + var trimmed = trimToMin(newSizes); + trimmed.forEach(function (newSize, i) { + if (i > 0) { + var pair = pairs[i - 1]; + + var a = elements[pair.a]; + var b = elements[pair.b]; + + a.size = trimmed[i - 1]; + b.size = newSize; + + setElementSize(a.element, a.size, pair[aGutterSize], a.i); + setElementSize(b.element, b.size, pair[bGutterSize], b.i); + } + }); + } + + function destroy(preserveStyles, preserveGutter) { + pairs.forEach(function (pair) { + if (preserveGutter !== true) { + pair.parent.removeChild(pair.gutter); + } else { + pair.gutter[removeEventListener]( + 'mousedown', + pair[gutterStartDragging] + ); + pair.gutter[removeEventListener]( + 'touchstart', + pair[gutterStartDragging] + ); + } + + if (preserveStyles !== true) { + var style = elementStyle( + dimension, + pair.a.size, + pair[aGutterSize] + ); + + Object.keys(style).forEach(function (prop) { + elements[pair.a].element.style[prop] = ''; + elements[pair.b].element.style[prop] = ''; + }); + } + }); + } + + if (isIE8) { + return { + setSizes: setSizes, + destroy: destroy, + } + } + + return { + setSizes: setSizes, + getSizes: getSizes, + collapse: function collapse(i) { + adjustToMin(elements[i]); + }, + destroy: destroy, + parent: parent, + pairs: pairs, + } + }; + + return Split; + +}))); diff --git a/assets/style.css b/assets/style.css new file mode 100644 index 00000000..0618f437 --- /dev/null +++ b/assets/style.css @@ -0,0 +1,147 @@ +.documentation { + font-family: Helvetica, sans-serif; + color: #666; + line-height: 1.5; + background: #f5f5f5; +} + +.black { + color: #666; +} + +.bg-white { + background-color: #fff; +} + +h4 { + margin: 20px 0 10px 0; +} + +.documentation h3 { + color: #000; +} + +.border-bottom { + border-color: #ddd; +} + +a { + color: #1184ce; + text-decoration: none; +} + +.documentation a[href]:hover { + text-decoration: underline; +} + +a:hover { + cursor: pointer; +} + +.py1-ul li { + padding: 5px 0; +} + +.max-height-100 { + max-height: 100%; +} + +.height-viewport-100 { + height: 100vh; +} + +section:target h3 { + font-weight: 700; +} + +.documentation td, +.documentation th { + padding: 0.25rem 0.25rem; +} + +h1:hover .anchorjs-link, +h2:hover .anchorjs-link, +h3:hover .anchorjs-link, +h4:hover .anchorjs-link { + opacity: 1; +} + +.fix-3 { + width: 25%; + max-width: 244px; +} + +.fix-3 { + width: 25%; + max-width: 244px; +} + +@media (min-width: 52em) { + .fix-margin-3 { + margin-left: 25%; + } +} + +.pre, +pre, +code, +.code { + font-family: Source Code Pro, Menlo, Consolas, Liberation Mono, monospace; + font-size: 14px; +} + +.fill-light { + background: #f9f9f9; +} + +.width2 { + width: 1rem; +} + +.input { + font-family: inherit; + display: block; + width: 100%; + height: 2rem; + padding: 0.5rem; + margin-bottom: 1rem; + border: 1px solid #ccc; + font-size: 0.875rem; + border-radius: 3px; + box-sizing: border-box; +} + +table { + border-collapse: collapse; +} + +.prose table th, +.prose table td { + text-align: left; + padding: 8px; + border: 1px solid #ddd; +} + +.prose table th:nth-child(1) { + border-right: none; +} +.prose table th:nth-child(2) { + border-left: none; +} + +.prose table { + border: 1px solid #ddd; +} + +.prose-big { + font-size: 18px; + line-height: 30px; +} + +.quiet { + opacity: 0.7; +} + +.minishadow { + box-shadow: 2px 2px 10px #f3f3f3; +} diff --git a/index.html b/index.html new file mode 100644 index 00000000..5484e98f --- /dev/null +++ b/index.html @@ -0,0 +1,3949 @@ + + + + + opossum 8.1.3 | Documentation + + + + + + + + +
+ +
+ + +
+ +

+ README +

+ + +

opossum

+

Node.js CI +Coverage Status +Known Vulnerabilities +dependencies Status

+

Opossum is a Node.js circuit breaker that executes asynchronous functions +and monitors their execution status. When things start failing, opossum +plays dead and fails fast. If you want, you can provide a fallback function +to be executed when in the failure state.

+

For more about the circuit breaker pattern, there are lots of resources +on the web - search it! Fowler's blog post is one place to +start reading.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Project Info
License:Apache-2.0
Documentation:https://nodeshift.dev/opossum/
Typings:https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/opossum
Issue tracker:https://github.com/nodeshift/opossum/issues
Engines:Node.js >= 16
+

Usage

+

Let's say you've got an API that depends on something that might fail - +a network operation, or disk read, for example. Wrap those functions up in a +CircuitBreaker and you have control over your destiny.

+

AbortController support

+

You can provide an AbortController (https://developer.mozilla.org/en-US/docs/Web/API/AbortController, https://nodejs.org/docs/latest/api/globals.html#globals_class_abortcontroller) for aborting on going request upon +reaching Opossum timeout.

+

Fallback

+

You can also provide a fallback function that will be executed in the +event of failure. To take some action when the fallback is performed, +listen for the fallback event.

+

Once the circuit has opened, a timeout is set based on options.resetTimeout. +When the resetTimeout expires, opossum will enter the halfOpen state. +Once in the halfOpen state, the next time the circuit is fired, the circuit's +action will be executed again. If successful, the circuit will close and emit +the close event. If the action fails or times out, it immediately re-enters +the open state.

+

When a fallback function is triggered, it's considered a failure, and the +fallback function will continue to be executed until the breaker is closed.

+

The fallback function accepts the same parameters as the fire function:

+

Breaker State Initialization

+

There may be times where you will need to initialize the state of a Circuit Breaker. Primary use cases for this are in a serverless environment such as Knative or AWS Lambda, or any container based platform, where the container being deployed is ephemeral.

+

The toJSON method is a helper function to get the current state and status of a breaker:

+
const breakerState = breaker.toJSON();
+
+

This will return an object that might look similar to this:

+
{
+  state: {
+    enabled: true,
+    name: 'functionName'
+    closed: true,
+    open: false,
+    halfOpen: false,
+    warmUp: false,
+    shutdown: false
+  },
+  status: {
+    ...
+  }
+};
+
+

A new circuit breaker instance can be created with this state by passing this object in:

+
const breaker = new CircuitBreaker({state: state});
+
+

Status Initialization

+

There may also be times where you will need to pre-populate the stats of the Circuit Breaker Status Object. Primary use cases for this are also in a serverless environment such as Knative or AWS Lambda, or any container based platform, where the container being deployed is ephemeral.

+

Getting the existing cumalative stats for a breaker can be done like this:

+
const stats = breaker.stats;
+
+

stats will be an object that might look similar to this:

+
{
+  failures: 11,
+  fallbacks: 0,
+  successes: 5,
+  rejects: 0,
+  fires: 16,
+  timeouts: 0,
+  cacheHits: 0,
+  cacheMisses: 0,
+  semaphoreRejections: 0,
+  percentiles: {
+    '0': 0,
+    '1': 0,
+    '0.25': 0,
+    '0.5': 0,
+    '0.75': 0,
+    '0.9': 0,
+    '0.95': 0,
+    '0.99': 0,
+    '0.995': 0
+  },
+  latencyTimes: [ 0 ],
+  latencyMean: 0
+}
+
+

To then re-import those stats, first create a new Status object with the previous stats and then pass that as an option to the CircuitBreaker constructor:

+
const statusOptions = {
+  stats: {....}
+};
+
+const newStatus = CircuitBreaker.newStatus(statusOptions);
+
+const breaker = new CircuitBreaker({status: newStatus});
+
+

Browser

+

Opossum really shines in a browser. You can use it to guard against network +failures in your AJAX calls.

+

We recommend using webpack to bundle your applications, +since it does not have the effect of polluting the window object with a global. +However, if you need it, you can access a circuitBreaker function in the global +namespace by doing something similar to what is shown in the below example.

+

Here is an example using hapi.js. See the +opossum-examples +repository for more detail.

+

Include opossum.js in your HTML file.

+

In your application, set a route to the file, pointing to +node_modules/opossum/dist/opossum-min.js.

+

In the browser's global scope will be a CircuitBreaker constructor. Use it +to create circuit breakers, guarding against network failures in your REST +API calls.

+

Events

+

A CircuitBreaker will emit events for important things that occur. +Here are the events you can listen for.

+
    +
  • fire - emitted when the breaker is fired.
  • +
  • reject - emitted when the breaker is open (or halfOpen).
  • +
  • timeout - emitted when the breaker action times out.
  • +
  • success - emitted when the breaker action completes successfully
  • +
  • failure - emitted when the breaker action fails, called with the error
  • +
  • open - emitted when the breaker state changes to open
  • +
  • close - emitted when the breaker state changes to closed
  • +
  • halfOpen - emitted when the breaker state changes to halfOpen
  • +
  • fallback - emitted when the breaker has a fallback function and executes it
  • +
  • semaphoreLocked - emitted when the breaker is at capacity and cannot execute the request
  • +
  • healthCheckFailed - emitted when a user-supplied health check function returns a rejected promise
  • +
  • shutdown - emitted when the breaker shuts down
  • +
+

Handling events gives a greater level of control over your application behavior.

+

Promises vs. Callbacks

+

The opossum API returns a Promise from CircuitBreaker.fire(). +But your circuit action - the async function that might fail - +doesn't have to return a promise. You can easily turn Node.js style +callback functions into something opossum understands by using the built in +Node core utility function util.promisify() .

+

And just for fun, your circuit doesn't even really have to be a function. +Not sure when you'd use this - but you could if you wanted to.

+

Calculating errorThresholdPercentage

+

The errorThresholdPercentage value is compared to the error rate. That rate is determined by dividing the number of failures by the number of times the circuit has been fired. You can see this comparison here:

+

The numbers for fires and failures come from the stats that are indeed governed by rollingCountTimeout and rollingCountBuckets. The timeout value is the total number of seconds for which the stats are being maintained, and the buckets value is the number of slots in the window. The defaults are 10 seconds and 10 buckets. So, the statistics that are being compared against errorThresholdPercentage are based on 10 samples, one per second over the last 10 seconds.

+

Example: a circuit is fired 24 times over 10 seconds with a somewhat bursty pattern, failing three times.

+
| fires: 2 | fires: 1 | fires: 3 | fires: 0 | fires: 9 | fires: 3 | fires: 2 | fires: 0 | fires: 4 | fires: 0 |
+| fails: 0 | fails: 0 | fails: 0 | fails: 0 | fails: 0 | fails: 3 | fails: 0 | fails: 0 | fails: 0 | fails: 0 |
+
+

The failure rate here is 3/24 or 1/8 or 12.5%. The default error threshold is 50%, so in this case, the circuit would not open. However, if you modified the rollingCountTimeout to 3 seconds, and the rollingCountBuckets to 3 (not recommended), then the stats array might look like these three seconds from above.

+
| fires: 3 | fires: 2 | fires: 0 |
+| fails: 3 | fails: 0 | fails: 0 |
+
+

Now, without changing errorThresholdPercentage our circuit will open because our error rate is now 3/5 or 60%. It's tricky to test this stuff because the array of statistics is a rolling count. Every second the oldest bucket is removed and a new one is added, so the totals change constantly in a way that may not be intuitive.

+

For example, if the first example is shifted right, dropping the first bucket and adding another with fires: 3 the total number of fires now in the stats is not 27 (24+3) but 25 (24-2+3).

+

The code that is summing the stats samples is here:

+

Typings

+

Typings are available here.

+

If you'd like to add them, run npm install @types/opossum in your project.

+

Metrics

+

Prometheus

+

The opossum-prometheus module +can be used to produce metrics that are consumable by Prometheus. +These metrics include information about the circuit itself, for example how many +times it has opened, as well as general Node.js statistics, for example event loop lag.

+

Hystrix

+

The opossum-hystrix module can +be used to produce metrics that are consumable by the Hystrix Dashboard.

+

Troubleshooting

+

You may run into issues related to too many listeners on an EventEmitter like this.

+

In some cases, seeing this error might indicate a bug in client code, where many CircuitBreakers are inadvertently being created. But there are legitimate scenarios where this may not be the case. For example, it could just be that you need more than 10 CircuitBreakers in your app. That's ok.

+

To get around the error, you can set the number of listeners on the stream.

+

Or it could be that you have a large test suite which exercises some code that creates CircuitBreakers and does so repeatedly. If the CircuitBreaker being created is only needed for the duration of the test, use breaker.shutdown() when the circuit is no longer in use to clean up all listeners.

+ + +
+ + + +
+ + +
+ +

+ CircuitBreaker +

+ + +
+ + +

Constructs a CircuitBreaker.

+ +
new CircuitBreaker(action: Function, options: Object)
+ + +

+ Extends + + EventEmitter + +

+ + + + + + + + + + +
Parameters
+
+ +
+
+ action (Function) + The action to fire for this +CircuitBreaker + +
+ +
+ +
+
+ options (Object) + Options for the +CircuitBreaker + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
options.status Status + A +Status + object that might +have pre-prime stats +
options.timeout Number + The time in milliseconds that action should +be allowed to execute before timing out. Timeout can be disabled by setting +this to +false +. Default 10000 (10 seconds) +
options.maxFailures Number + (Deprecated) The number of times the +circuit can fail before opening. Default 10. +
options.resetTimeout Number + The time in milliseconds to wait before +setting the breaker to +halfOpen + state, and trying the action again. +Default: 30000 (30 seconds) +
options.rollingCountTimeout Number + Sets the duration of the +statistical rolling window, in milliseconds. This is how long Opossum keeps +metrics for the circuit breaker to use and for publishing. Default: 10000 +
options.rollingCountBuckets Number + Sets the number of buckets the +rolling statistical window is divided into. So, if +options.rollingCountTimeout is 10000, and options.rollingCountBuckets is 10, +then the statistical window will be 1000/1 second snapshots in the +statistical window. Default: 10 +
options.name String + the circuit name to use when reporting stats. +Default: the name of the function this circuit controls. +
options.rollingPercentilesEnabled boolean + This property indicates +whether execution latencies should be tracked and calculated as percentiles. +If they are disabled, all summary statistics (mean, percentiles) are +returned as -1. Default: true +
options.capacity Number + the number of concurrent requests allowed. +If the number currently executing function calls is equal to +options.capacity, further calls to +fire() + are rejected until at least one +of the current requests completes. Default: +Number.MAX_SAFE_INTEGER +. +
options.errorThresholdPercentage Number + the error percentage at +which to open the circuit and start short-circuiting requests to fallback. +Default: 50 +
options.enabled boolean + whether this circuit is enabled upon +construction. Default: true +
options.allowWarmUp boolean + determines whether to allow failures +without opening the circuit during a brief warmup period (this is the + +rollingCountTimeout + property). Default: false +This can help in situations where no matter what your + +errorThresholdPercentage + is, if the first execution times out or fails, +the circuit immediately opens. +
options.volumeThreshold Number + the minimum number of requests within +the rolling statistical window that must exist before the circuit breaker +can open. This is similar to +options.allowWarmUp + in that no matter how many +failures there are, if the number of requests within the statistical window +does not exceed this threshold, the circuit will remain closed. Default: 0 +
options.errorFilter Function + an optional function that will be +called when the circuit's function fails (returns a rejected Promise). If +this function returns truthy, the circuit's failPure statistics will not be +incremented. This is useful, for example, when you don't want HTTP 404 to +trip the circuit, but still want to handle it as a failure case. +
options.cache boolean + whether the return value of the first +successful execution of the circuit's function will be cached. Once a value +has been cached that value will be returned for every subsequent execution: +the cache can be cleared using +clearCache +. (The metrics +cacheHit + and + +cacheMiss + reflect cache activity.) Default: false +
options.cacheTTL Number + the time to live for the cache +in milliseconds. Set 0 for infinity cache. Default: 0 (no TTL) +
options.cacheGetKey Function + function that returns the key to use +when caching the result of the circuit's fire. +Better to use custom one, because +JSON.stringify + is not good +from performance perspective. +Default: +(...args) => JSON.stringify(args) +
options.cacheTransport CacheTransport + custom cache transport +should implement +get +, +set + and +flush + methods. +
options.abortController AbortController + this allows Opossum to +signal upon timeout and properly abort your on going requests instead of +leaving it in the background +
options.enableSnapshots boolean + whether to enable the rolling +stats snapshots that opossum emits at the bucketInterval. Disable this +as an optimization if you don't listen to the 'snapshot' event to reduce +the number of timers opossum initiates. +
options.rotateBucketController EventEmitter + if you have multiple +breakers in your app, the number of timers across breakers can get costly. +This option allows you to provide an EventEmitter that rotates the buckets +so you can have one global timer in your app. Make sure that you are +emitting a 'rotate' event from this EventEmitter +
+ +
+ +
+ + + + + + + + + + + + + +
Static Members
+
+ +
+
+
+ + isOurError(error) +
+
+ +
+ +
+
+
+ + newStatus(options) +
+
+ +
+ +
+ + + + +
Instance Members
+
+ +
+
+
+ + close() +
+
+ +
+ +
+
+
+ + open() +
+
+ +
+ +
+
+
+ + shutdown() +
+
+ +
+ +
+
+
+ + isShutdown +
+
+ +
+ +
+
+
+ + name +
+
+ +
+ +
+
+
+ + group +
+
+ +
+ +
+
+
+ + pendingClose +
+
+ +
+ +
+
+
+ + closed +
+
+ +
+ +
+
+
+ + opened +
+
+ +
+ +
+
+
+ + halfOpen +
+
+ +
+ +
+
+
+ + status +
+
+ +
+ +
+
+
+ + stats +
+
+ +
+ +
+
+
+ + enabled +
+
+ +
+ +
+
+
+ + warmUp +
+
+ +
+ +
+
+
+ + volumeThreshold +
+
+ +
+ +
+
+
+ + fallback(func) +
+
+ +
+ +
+
+
+ + fire(args) +
+
+ +
+ +
+
+
+ + call(context, rest) +
+
+ +
+ +
+
+
+ + clearCache() +
+
+ +
+ +
+
+
+ + healthCheck(func, interval?) +
+
+ +
+ +
+
+
+ + enable() +
+
+ +
+ +
+
+
+ + disable() +
+
+ +
+ +
+ + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#halfOpen +

+ + +
+ + +

Emitted after options.resetTimeout has elapsed, allowing for +a single attempt to call the service again. If that attempt is +successful, the circuit will be closed. Otherwise it remains open.

+ +
CircuitBreaker#halfOpen
+ +

+ Type: + Number +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#close +

+ + +
+ + +

Emitted when the breaker is reset allowing the action to execute again

+ +
CircuitBreaker#close
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#open +

+ + +
+ + +

Emitted when the breaker opens because the action has +failure percentage greater than options.errorThresholdPercentage.

+ +
CircuitBreaker#open
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#shutdown +

+ + +
+ + +

Emitted when the circuit breaker has been shut down.

+ +
CircuitBreaker#shutdown
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#fire +

+ + +
+ + +

Emitted when the circuit breaker action is executed

+ +
CircuitBreaker#fire
+ +

+ Type: + any +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#cacheHit +

+ + +
+ + +

Emitted when the circuit breaker is using the cache +and finds a value.

+ +
CircuitBreaker#cacheHit
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#cacheMiss +

+ + +
+ + +

Emitted when the circuit breaker does not find a value in +the cache, but the cache option is enabled.

+ +
CircuitBreaker#cacheMiss
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#reject +

+ + +
+ + +

Emitted when the circuit breaker is open and failing fast

+ +
CircuitBreaker#reject
+ +

+ Type: + Error +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#timeout +

+ + +
+ + +

Emitted when the circuit breaker action takes longer than +options.timeout

+ +
CircuitBreaker#timeout
+ +

+ Type: + Error +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#success +

+ + +
+ + +

Emitted when the circuit breaker action succeeds

+ +
CircuitBreaker#success
+ +

+ Type: + any +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#semaphoreLocked +

+ + +
+ + +

Emitted when the rate limit has been reached and there +are no more locks to be obtained.

+ +
CircuitBreaker#semaphoreLocked
+ +

+ Type: + Error +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#healthCheckFailed +

+ + +
+ + +

Emitted with the user-supplied health check function +returns a rejected promise.

+ +
CircuitBreaker#healthCheckFailed
+ +

+ Type: + Error +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#fallback +

+ + +
+ + +

Emitted when the circuit breaker executes a fallback function

+ +
CircuitBreaker#fallback
+ +

+ Type: + any +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ CircuitBreaker#failure +

+ + +
+ + +

Emitted when the circuit breaker action fails

+ +
CircuitBreaker#failure
+ +

+ Type: + Error +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ Status +

+ + +
+ + +

Tracks execution status for a given CircuitBreaker. +A Status instance is created for every CircuitBreaker +and does not typically need to be created by a user.

+

A Status instance will listen for all events on the CircuitBreaker +and track them in a rolling statistical window. The window duration is +determined by the rollingCountTimeout option provided to the +CircuitBreaker. The window consists of an array of Objects, +each representing the counts for a CircuitBreaker's events.

+

The array's length is determined by the CircuitBreaker's +rollingCountBuckets option. The duration of each slice of the window +is determined by dividing the rollingCountTimeout by +rollingCountBuckets.

+ +
new Status(options: Object)
+ + +

+ Extends + + EventEmitter + +

+ + + + + + + + + + +
Parameters
+
+ +
+
+ options (Object) + for the status window + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
options.rollingCountBuckets Number + number of buckets in the window +
options.rollingCountTimeout Number + the duration of the window +
options.rollingPercentilesEnabled Boolean + whether to calculate +percentiles +
options.stats Object + object of previous stats +
+ +
+ +
+ + + + + + + +
Related
+ + + CircuitBreaker#status + + + + + + + + +
Example
+ + +
// Creates a 1 second window consisting of ten time slices,
+// each 100ms long.
+const circuit = circuitBreaker(fs.readFile,
+ { rollingCountBuckets: 10, rollingCountTimeout: 1000});
+
+// get the cumulative statistics for the last second
+circuit.status.stats;
+
+// get the array of 10, 1 second time slices for the last second
+circuit.status.window;
+ + + + + + +
Instance Members
+
+ +
+
+
+ + stats +
+
+ +
+ +
+
+
+ + window +
+
+ +
+ +
+ + + + + + +
+ + + + +
+ + +
+ +

+ Status#snapshot +

+ + +
+ + +

Emitted at each time-slice. Listeners for this +event will receive a cumulative snapshot of the current status window.

+ +
Status#snapshot
+ +

+ Type: + Object +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +

+ MemoryCache +

+ + +
+ + +

Simple in-memory cache implementation

+ +
new MemoryCache()
+ + + + + + + + + + + + + +
Properties
+
+ +
+ cache (Map) + : Cache map + + +
+ +
+ + + + + + + + + + + + + +
Instance Members
+
+ +
+
+
+ + get(key) +
+
+ +
+ +
+
+
+ + set(key, value, ttl) +
+
+ +
+ +
+
+
+ + flush() +
+
+ +
+ +
+ + + + + + +
+ + + +
+
+ + + + + diff --git a/opossum.md b/opossum.md new file mode 100644 index 00000000..12f7acde --- /dev/null +++ b/opossum.md @@ -0,0 +1,692 @@ + + +### Table of Contents + +* [CircuitBreaker][1] + * [Parameters][2] + * [close][3] + * [open][4] + * [shutdown][5] + * [isShutdown][6] + * [name][7] + * [group][8] + * [pendingClose][9] + * [closed][10] + * [opened][11] + * [halfOpen][12] + * [status][13] + * [stats][14] + * [enabled][15] + * [warmUp][16] + * [volumeThreshold][17] + * [fallback][18] + * [Parameters][19] + * [fire][20] + * [Parameters][21] + * [call][22] + * [Parameters][23] + * [clearCache][24] + * [healthCheck][25] + * [Parameters][26] + * [enable][27] + * [disable][28] + * [isOurError][29] + * [Parameters][30] + * [newStatus][31] + * [Parameters][32] +* [CircuitBreaker#halfOpen][33] +* [CircuitBreaker#close][34] +* [CircuitBreaker#open][35] +* [CircuitBreaker#shutdown][36] +* [CircuitBreaker#fire][37] +* [CircuitBreaker#cacheHit][38] +* [CircuitBreaker#cacheMiss][39] +* [CircuitBreaker#reject][40] +* [CircuitBreaker#timeout][41] +* [CircuitBreaker#success][42] +* [CircuitBreaker#semaphoreLocked][43] +* [CircuitBreaker#healthCheckFailed][44] +* [CircuitBreaker#fallback][45] +* [CircuitBreaker#failure][46] +* [Status][47] + * [Parameters][48] + * [Examples][49] + * [stats][50] + * [window][51] +* [Status#snapshot][52] +* [MemoryCache][53] + * [Properties][54] + * [get][55] + * [Parameters][56] + * [set][57] + * [Parameters][58] + * [flush][59] + +## CircuitBreaker + +**Extends EventEmitter** + +Constructs a [CircuitBreaker][1]. + +### Parameters + +* `action` **[Function][60]** The action to fire for this [CircuitBreaker][1] +* `options` **[Object][61]** Options for the [CircuitBreaker][1] + + * `options.status` **[Status][13]** A [Status][13] object that might + have pre-prime stats + * `options.timeout` **[Number][62]** The time in milliseconds that action should + be allowed to execute before timing out. Timeout can be disabled by setting + this to `false`. Default 10000 (10 seconds) + * `options.maxFailures` **[Number][62]** (Deprecated) The number of times the + circuit can fail before opening. Default 10. + * `options.resetTimeout` **[Number][62]** The time in milliseconds to wait before + setting the breaker to `halfOpen` state, and trying the action again. + Default: 30000 (30 seconds) + * `options.rollingCountTimeout` **[Number][62]** Sets the duration of the + statistical rolling window, in milliseconds. This is how long Opossum keeps + metrics for the circuit breaker to use and for publishing. Default: 10000 + * `options.rollingCountBuckets` **[Number][62]** Sets the number of buckets the + rolling statistical window is divided into. So, if + options.rollingCountTimeout is 10000, and options.rollingCountBuckets is 10, + then the statistical window will be 1000/1 second snapshots in the + statistical window. Default: 10 + * `options.name` **[String][63]** the circuit name to use when reporting stats. + Default: the name of the function this circuit controls. + * `options.rollingPercentilesEnabled` **[boolean][64]** This property indicates + whether execution latencies should be tracked and calculated as percentiles. + If they are disabled, all summary statistics (mean, percentiles) are + returned as -1. Default: true + * `options.capacity` **[Number][62]** the number of concurrent requests allowed. + If the number currently executing function calls is equal to + options.capacity, further calls to `fire()` are rejected until at least one + of the current requests completes. Default: `Number.MAX_SAFE_INTEGER`. + * `options.errorThresholdPercentage` **[Number][62]** the error percentage at + which to open the circuit and start short-circuiting requests to fallback. + Default: 50 + * `options.enabled` **[boolean][64]** whether this circuit is enabled upon + construction. Default: true + * `options.allowWarmUp` **[boolean][64]** determines whether to allow failures + without opening the circuit during a brief warmup period (this is the + `rollingCountTimeout` property). Default: false + This can help in situations where no matter what your + `errorThresholdPercentage` is, if the first execution times out or fails, + the circuit immediately opens. + * `options.volumeThreshold` **[Number][62]** the minimum number of requests within + the rolling statistical window that must exist before the circuit breaker + can open. This is similar to `options.allowWarmUp` in that no matter how many + failures there are, if the number of requests within the statistical window + does not exceed this threshold, the circuit will remain closed. Default: 0 + * `options.errorFilter` **[Function][60]** an optional function that will be + called when the circuit's function fails (returns a rejected Promise). If + this function returns truthy, the circuit's failPure statistics will not be + incremented. This is useful, for example, when you don't want HTTP 404 to + trip the circuit, but still want to handle it as a failure case. + * `options.cache` **[boolean][64]** whether the return value of the first + successful execution of the circuit's function will be cached. Once a value + has been cached that value will be returned for every subsequent execution: + the cache can be cleared using `clearCache`. (The metrics `cacheHit` and + `cacheMiss` reflect cache activity.) Default: false + * `options.cacheTTL` **[Number][62]** the time to live for the cache + in milliseconds. Set 0 for infinity cache. Default: 0 (no TTL) + * `options.cacheGetKey` **[Function][60]** function that returns the key to use + when caching the result of the circuit's fire. + Better to use custom one, because `JSON.stringify` is not good + from performance perspective. + Default: `(...args) => JSON.stringify(args)` + * `options.cacheTransport` **CacheTransport** custom cache transport + should implement `get`, `set` and `flush` methods. + * `options.abortController` **AbortController** this allows Opossum to + signal upon timeout and properly abort your on going requests instead of + leaving it in the background + * `options.enableSnapshots` **[boolean][64]** whether to enable the rolling + stats snapshots that opossum emits at the bucketInterval. Disable this + as an optimization if you don't listen to the 'snapshot' event to reduce + the number of timers opossum initiates. + * `options.rotateBucketController` **EventEmitter** if you have multiple + breakers in your app, the number of timers across breakers can get costly. + This option allows you to provide an EventEmitter that rotates the buckets + so you can have one global timer in your app. Make sure that you are + emitting a 'rotate' event from this EventEmitter + +### close + +Closes the breaker, allowing the action to execute again + +Returns **void** + +### open + +Opens the breaker. Each time the breaker is fired while the circuit is +opened, a failed Promise is returned, or if any fallback function +has been provided, it is invoked. + +If the breaker is already open this call does nothing. + +Returns **void** + +### shutdown + +Shuts down this circuit breaker. All subsequent calls to the +circuit will fail, returning a rejected promise. + +Returns **void** + +### isShutdown + +Determines if the circuit has been shutdown. + +Type: [Boolean][64] + +### name + +Gets the name of this circuit + +Type: [String][63] + +### group + +Gets the name of this circuit group + +Type: [String][63] + +### pendingClose + +Gets whether this circuit is in the `pendingClosed` state + +Type: [Boolean][64] + +### closed + +True if the circuit is currently closed. False otherwise. + +Type: [Boolean][64] + +### opened + +True if the circuit is currently opened. False otherwise. + +Type: [Boolean][64] + +### halfOpen + +True if the circuit is currently half opened. False otherwise. + +Type: [Boolean][64] + +### status + +The current [Status][13] of this [CircuitBreaker][1] + +Type: [Status][13] + +### stats + +* **See**: Status#stats + +Get the current stats for the circuit. + +Type: [Object][61] + +### enabled + +Gets whether the circuit is enabled or not + +Type: [Boolean][64] + +### warmUp + +Gets whether the circuit is currently in warm up phase + +Type: [Boolean][64] + +### volumeThreshold + +Gets the volume threshold for this circuit + +Type: [Boolean][64] + +### fallback + +Provide a fallback function for this [CircuitBreaker][1]. This +function will be executed when the circuit is `fire`d and fails. +It will always be preceded by a `failure` event, and `breaker.fire` returns +a rejected Promise. + +#### Parameters + +* `func` **([Function][60] | [CircuitBreaker][1])** the fallback function to execute + when the breaker has opened or when a timeout or error occurs. + +Returns **[CircuitBreaker][1]** this + +### fire + +Execute the action for this circuit. If the action fails or times out, the +returned promise will be rejected. If the action succeeds, the promise will +resolve with the resolved value from action. If a fallback function was +provided, it will be invoked in the event of any failure or timeout. + +Any parameters passed to this function will be proxied to the circuit +function. + +#### Parameters + +* `args` **...any** + +Returns **[Promise][65]\** promise resolves with the circuit function's return +value on success or is rejected on failure of the action. Use isOurError() +to determine if a rejection was a result of the circuit breaker or the +action. + +### call + +Execute the action for this circuit using `context` as `this`. +If the action fails or times out, the +returned promise will be rejected. If the action succeeds, the promise will +resolve with the resolved value from action. If a fallback function was +provided, it will be invoked in the event of any failure or timeout. + +Any parameters in addition to \`context will be passed to the +circuit function. + +#### Parameters + +* `context` **any** the `this` context used for function execution +* `rest` **any** the arguments passed to the action + +Returns **[Promise][65]\** promise resolves with the circuit function's return +value on success or is rejected on failure of the action. + +### clearCache + +Clears the cache of this [CircuitBreaker][1] + +Returns **void** + +### healthCheck + +Provide a health check function to be called periodically. The function +should return a Promise. If the promise is rejected the circuit will open. +This is in addition to the existing circuit behavior as defined by +`options.errorThresholdPercentage` in the constructor. For example, if the +health check function provided here always returns a resolved promise, the +circuit can still trip and open if there are failures exceeding the +configured threshold. The health check function is executed within the +circuit breaker's execution context, so `this` within the function is the +circuit breaker itself. + +#### Parameters + +* `func` **[Function][60]** a health check function which returns a promise. +* `interval` **[Number][62]?** the amount of time between calls to the health + check function. Default: 5000 (5 seconds) + + + +* Throws **[TypeError][66]** if `interval` is supplied but not a number + +Returns **void** + +### enable + +Enables this circuit. If the circuit is the disabled +state, it will be re-enabled. If not, this is essentially +a noop. + +Returns **void** + +### disable + +Disables this circuit, causing all calls to the circuit's function +to be executed without circuit or fallback protection. + +Returns **void** + +### isOurError + +Returns true if the provided error was generated here. It will be false +if the error came from the action itself. + +#### Parameters + +* `error` **[Error][67]** The Error to check. + +Returns **[Boolean][64]** true if the error was generated here + +### newStatus + +Create a new Status object, +helpful when you need to prime a breaker with stats + +#### Parameters + +* `options` **[Object][61]** * + + * `options.rollingCountBuckets` **[Number][62]** number of buckets in the window + * `options.rollingCountTimeout` **[Number][62]** the duration of the window + * `options.rollingPercentilesEnabled` **[Boolean][64]** whether to calculate + * `options.stats` **[Object][61]** user supplied stats + +Returns **[Status][13]** a new [Status][13] object + +## CircuitBreaker#halfOpen + +Emitted after `options.resetTimeout` has elapsed, allowing for +a single attempt to call the service again. If that attempt is +successful, the circuit will be closed. Otherwise it remains open. + +Type: [Number][62] + +## CircuitBreaker#close + +Emitted when the breaker is reset allowing the action to execute again + +## CircuitBreaker#open + +Emitted when the breaker opens because the action has +failure percentage greater than `options.errorThresholdPercentage`. + +## CircuitBreaker#shutdown + +Emitted when the circuit breaker has been shut down. + +## CircuitBreaker#fire + +Emitted when the circuit breaker action is executed + +Type: any + +## CircuitBreaker#cacheHit + +Emitted when the circuit breaker is using the cache +and finds a value. + +## CircuitBreaker#cacheMiss + +Emitted when the circuit breaker does not find a value in +the cache, but the cache option is enabled. + +## CircuitBreaker#reject + +Emitted when the circuit breaker is open and failing fast + +Type: [Error][67] + +## CircuitBreaker#timeout + +Emitted when the circuit breaker action takes longer than +`options.timeout` + +Type: [Error][67] + +## CircuitBreaker#success + +Emitted when the circuit breaker action succeeds + +Type: any + +## CircuitBreaker#semaphoreLocked + +Emitted when the rate limit has been reached and there +are no more locks to be obtained. + +Type: [Error][67] + +## CircuitBreaker#healthCheckFailed + +Emitted with the user-supplied health check function +returns a rejected promise. + +Type: [Error][67] + +## CircuitBreaker#fallback + +Emitted when the circuit breaker executes a fallback function + +Type: any + +## CircuitBreaker#failure + +Emitted when the circuit breaker action fails + +Type: [Error][67] + +## Status + +**Extends EventEmitter** + +* **See**: CircuitBreaker#status + +Tracks execution status for a given [CircuitBreaker][1]. +A Status instance is created for every [CircuitBreaker][1] +and does not typically need to be created by a user. + +A Status instance will listen for all events on the [CircuitBreaker][1] +and track them in a rolling statistical window. The window duration is +determined by the `rollingCountTimeout` option provided to the +[CircuitBreaker][1]. The window consists of an array of Objects, +each representing the counts for a [CircuitBreaker][1]'s events. + +The array's length is determined by the [CircuitBreaker][1]'s +`rollingCountBuckets` option. The duration of each slice of the window +is determined by dividing the `rollingCountTimeout` by +`rollingCountBuckets`. + +### Parameters + +* `options` **[Object][61]** for the status window + + * `options.rollingCountBuckets` **[Number][62]** number of buckets in the window + * `options.rollingCountTimeout` **[Number][62]** the duration of the window + * `options.rollingPercentilesEnabled` **[Boolean][64]** whether to calculate + percentiles + * `options.stats` **[Object][61]** object of previous stats + +### Examples + +```javascript +// Creates a 1 second window consisting of ten time slices, +// each 100ms long. +const circuit = circuitBreaker(fs.readFile, + { rollingCountBuckets: 10, rollingCountTimeout: 1000}); + +// get the cumulative statistics for the last second +circuit.status.stats; + +// get the array of 10, 1 second time slices for the last second +circuit.status.window; +``` + +### stats + +Get the cumulative stats for the current window + +Type: [Object][61] + +### window + +Gets the stats window as an array of time-sliced objects. + +Type: [Array][68] + +## Status#snapshot + +Emitted at each time-slice. Listeners for this +event will receive a cumulative snapshot of the current status window. + +Type: [Object][61] + +## MemoryCache + +Simple in-memory cache implementation + +### Properties + +* `cache` **[Map][69]** Cache map + +### get + +Get cache value by key + +#### Parameters + +* `key` **[string][63]** Cache key + +Returns **any** Response from cache + +### set + +Set cache key with value and ttl + +#### Parameters + +* `key` **[string][63]** Cache key +* `value` **any** Value to cache +* `ttl` **[number][62]** Time to live in milliseconds + +Returns **void** + +### flush + +Clear cache + +Returns **void** + +[1]: #circuitbreaker + +[2]: #parameters + +[3]: #close + +[4]: #open + +[5]: #shutdown + +[6]: #isshutdown + +[7]: #name + +[8]: #group + +[9]: #pendingclose + +[10]: #closed + +[11]: #opened + +[12]: #halfopen + +[13]: #status + +[14]: #stats + +[15]: #enabled + +[16]: #warmup + +[17]: #volumethreshold + +[18]: #fallback + +[19]: #parameters-1 + +[20]: #fire + +[21]: #parameters-2 + +[22]: #call + +[23]: #parameters-3 + +[24]: #clearcache + +[25]: #healthcheck + +[26]: #parameters-4 + +[27]: #enable + +[28]: #disable + +[29]: #isourerror + +[30]: #parameters-5 + +[31]: #newstatus + +[32]: #parameters-6 + +[33]: #circuitbreakerhalfopen + +[34]: #circuitbreakerclose + +[35]: #circuitbreakeropen + +[36]: #circuitbreakershutdown + +[37]: #circuitbreakerfire + +[38]: #circuitbreakercachehit + +[39]: #circuitbreakercachemiss + +[40]: #circuitbreakerreject + +[41]: #circuitbreakertimeout + +[42]: #circuitbreakersuccess + +[43]: #circuitbreakersemaphorelocked + +[44]: #circuitbreakerhealthcheckfailed + +[45]: #circuitbreakerfallback + +[46]: #circuitbreakerfailure + +[47]: #status-1 + +[48]: #parameters-7 + +[49]: #examples + +[50]: #stats-1 + +[51]: #window + +[52]: #statussnapshot + +[53]: #memorycache + +[54]: #properties + +[55]: #get + +[56]: #parameters-8 + +[57]: #set + +[58]: #parameters-9 + +[59]: #flush + +[60]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function + +[61]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object + +[62]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number + +[63]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String + +[64]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean + +[65]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise + +[66]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/TypeError + +[67]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error + +[68]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array + +[69]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map