(function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 1)) && !window.MSStream; let precisionValue = isIOS ? 'highp' : 'mediump' var pb = new PatchBay() var hydra = new HydraSynth({ pb: pb, canvas: canvas, autoLoop: false, precision: precisionValue}) var editor = new Editor() var menu = new Menu({ editor: editor, hydra: hydra}) log.init() // get initial code to fill gallery var sketches = new Gallery(function(code, sketchFromURL) { editor.setValue(code) repl.eval(code) // if a sketch was found based on the URL parameters, dont show intro window if(sketchFromURL) { menu.closeModal() } else { menu.openModal() } }) menu.sketches = sketches keymaps.init ({ editor: editor, gallery: sketches, menu: menu, repl: repl, log: log }) // define extra functions (eventually should be added to hydra-synth?) // hush clears what you see on the screen window.hush = () => { solid().out() solid().out(o1) solid().out(o2) solid().out(o3) render(o0) } pb.init(hydra.captureStream, { server: window.location.origin, room: 'iclc' }) var engine = loop(function(dt) { hydra.tick(dt) }).start() } window.onload = init },{"./keymaps.js":2,"./src/editor.js":5,"./src/gallery.js":7,"./src/log.js":8,"./src/menu.js":9,"./src/p5-wrapper.js":10,"./src/pb-live.js":11,"./src/repl.js":12,"hydra-synth":61,"raf-loop":94}],2:[function(require,module,exports){ module.exports = { init : ({ editor, gallery, menu, repl, log}) => { window.onkeydown = (e) => { // console.log(e) if ( e.ctrlKey === true ) { if ( e.shiftKey === true ) { console.log(e) // shift - ctrl - enter: evalAll if ( e.keyCode === 13) { e.preventDefault() // repl.eval(editor.getValue(), (string, err) => { // console.log('eval', err) // if(!err) gallery.saveLocally(editor.getValue()) // }) menu.runAll() } // shift - ctrl - G: share sketch if (e.keyCode === 71) { e.preventDefault() menu.shareSketch() } // shift - ctrl - F: format code if (e.keyCode === 70) { e.preventDefault() menu.formatCode() } // shift - ctrl - l: save to url if(e.keyCode === 76) { e.preventDefault() gallery.saveLocally(editor.getValue()) } // shift - ctrl - h: toggle editor if (e.keyCode === 72) { e.preventDefault() editor.toggle() log.toggle() } // shift - ctrl - s: screencap if (e.keyCode === 83) { e.preventDefault() screencap() } } else { // ctrl-enter: evalLine if ( e.keyCode === 13) { e.preventDefault() // console.log('eval line') repl.eval(editor.getLine()) } } // ctrl - /: toggle comment if (e.keyCode === 191) { e.preventDefault() editor.cm.toggleComment() } // Point Mutation Glitcher Key Commands and history commands (left and right arrows) // right arrow key if(e.keyCode === 39) { e.preventDefault() // if(e.shiftKey === true) { // editor.mutator.mutate({reroll: false}) // } else { window.history.forward() // } } // left arrow if(e.keyCode === 37) { e.preventDefault() // if(e.shiftKey === true) { // console.log('redoing') // editor.mutator.doUndo() // } else { window.history.back() // } // editor.mutator.doUndo() } // up arrow if(e.keyCode === 38) { e.preventDefault() editor.mutator.doRedo() } // down arrow if(e.keyCode === 40) { editor.mutator.mutate({reroll: true}) gallery.saveLocally(editor.getValue()) } } if (e.altKey === true) { // alt - enter: evalBlock if ( e.keyCode === 13) { e.preventDefault() repl.eval(editor.getCurrentBlock().text) } } } } } },{}],3:[function(require,module,exports){ const {Parser} = require("acorn"); const {generate} = require('astring'); const { defaultTraveler, attachComments, makeTraveler } = require('astravel'); const {UndoStack} = require('./UndoStack.js'); const repl = require('./repl.js') class Mutator { constructor(editor) { this.editor = editor; this.undoStack = new UndoStack(); this.initialVector = []; } mutate(options) { // Get text from CodeMirror. let text = this.editor.cm.getValue(); this.undoStack.push({text, lastLitX: this.lastLitX}); let needToRun = true; let tryCounter = 5; while (needToRun && tryCounter-- >= 0) { // Parse to AST var comments = []; let ast = Parser.parse(text, { locations: true, onComment: comments} ); // Modify the AST. this.transform(ast, options); // Put the comments back. attachComments(ast, comments); // Generate JS from AST and set back into CodeMirror editor. let regen = generate(ast, {comments: true}); this.editor.cm.setValue(regen); // Evaluate the updated expression. repl.eval(regen, (code, error) => { // If we got an error, keep trying something else. if (error) { console.log("Eval error: " + regen); } needToRun = error; }); } } doUndo() { // If the current text is unsaved, save it so we can redo if need be. if (this.undoStack.atTop()) { let text = this.editor.cm.getValue(); this.undoStack.push({text, lastLitX: this.lastLitX}); } // Then pop-off the info to restore. if (this.undoStack.canUndo()) { let {text, lastLitX} = this.undoStack.undo(); this.setText(text); this.lastLitX = lastLitX; } } doRedo() { if(this.undoStack.canRedo()) { let {text, lastLitX} = this.undoStack.redo(); this.setText(text); this.lastLitX = lastLitX; } } setText(text) { this.editor.cm.setValue(text); repl.eval(text, (code, error) => { }); } // The options object contains a flag that controls how the // Literal to mutate is determined. If reroll is false, we // pick one at random. If reroll is true, we use the same field // we did last time. transform(ast, options) { // An AST traveler that accumulates a list of Literal nodes. let traveler = makeTraveler({ go: function(node, state) { if (node.type === 'Literal') { state.literalTab.push(node); } else if (node.type === 'MemberExpression') { if (node.property && node.property.type === 'Literal') { // numeric array subscripts are ineligable return; } } else if (node.type === 'CallExpression') { if (node.callee && node.callee.property && node.callee.property.name && node.callee.property.name !== 'out') { state.functionTab.push(node); } } // Call the parent's `go` method this.super.go.call(this, node, state); } }); let state = {}; state.literalTab = []; state.functionTab = []; traveler.go(ast, state); let litCount = state.literalTab.length; let funCount = state.functionTab.length; if (litCount !== this.initialVector.length) { let nextVect = []; for(let i = 0; i < litCount; ++i) { nextVect.push(state.literalTab[i].value); } this.initialVector = nextVect; } let litx = 0; if (options.reroll) { if (this.lastLitX !== undefined) { litx = this.lastLitX; } } else { litx = Math.floor(Math.random() * litCount); this.lastLitX = litx; } let modLit = state.literalTab[litx]; if (modLit) { // let glitched = this.glitchNumber(modLit.value); let glitched = this.glitchRelToInit(modLit.value, this.initialVector[litx]); let was = modLit.raw; modLit.value = glitched; modLit.raw = "" + glitched; console.log("Literal: " + litx + " changed from: " + was + " to: " + glitched); } } glitchNumber(num) { if (num === 0) { num = 1; } let range = num * 2; let rndVal = Math.round(Math.random() * range * 1000) / 1000; return rndVal; } glitchRelToInit(num, initVal) { if (initVal === undefined) { return glitchNumber(num); } if (initVal === 0) { initVal = 0.5; } let rndVal = Math.round(Math.random() * initVal * 2 * 1000) / 1000; return rndVal; } } // End of class Mutator. module.exports = Mutator },{"./UndoStack.js":4,"./repl.js":12,"acorn":14,"astravel":17,"astring":20}],4:[function(require,module,exports){ // A generalized 'Undo stack' which can keep N levels of revertable state. class UndoStack { constructor(limit) { this.stack = []; this.index = -1; this.limit = limit; } atTop() { return this.index === -1; } canUndo() { if(this.stack.length === 0) return false; return this.index === -1 || this.index > 0; } canRedo() { if(this.stack.length === 0 || this.index === -1) return false; return this.index < this.stack.length - 1; } push(item) { if (this.index >= 0) { while (this.index < this.stack.length) this.stack.pop(); this.index = -1; } if (this.limit && this.stack.length > this.limit) { this.stack.shift(); } this.stack.push(item); } undo() { if (this.stack.length === 0) return undefined; if (this.index === -1) { // start one behind the redo buffer this.index = this.stack.length - 1; } if (this.index > 0) this.index--; let v = this.stack[this.index]; return v; } redo() { if (this.stack.length === 0 || this.index === -1) return undefined; let nextX = this.index + 1; if (nextX >= this.stack.length) return undefined; this.index = nextX; return this.stack[this.index]; } }; module.exports = {UndoStack} },{}],5:[function(require,module,exports){ /* eslint-disable no-eval */ var CodeMirror = require('codemirror/lib/codemirror') require('codemirror/mode/javascript/javascript') require('codemirror/addon/hint/javascript-hint') require('codemirror/addon/hint/show-hint') require('codemirror/addon/selection/mark-selection') require('codemirror/addon/comment/comment') var Mutator = require('./Mutator.js'); var isShowing = true var EditorClass = function () { console.log("*** Editor class created"); var self = this var container = document.createElement('div') container.setAttribute('id','editor-container') var el = document.createElement('TEXTAREA') document.body.appendChild(container) container.appendChild(el) this.mutator = new Mutator(this); this.cm = CodeMirror.fromTextArea(el, { theme: 'tomorrow-night-eighties', value: 'hello', mode: {name: 'javascript', globalVars: true}, lineWrapping: true, styleSelectedText: true }) console.log('code mirror', this.cm) //this.cm.removeKeyMap() this.cm.refresh() this.show() // TO DO: add show code param let searchParams = new URLSearchParams(window.location.search) let showCode = searchParams.get('show-code') if(showCode == "false") { console.log("not showing code") var l = document.getElementsByClassName('CodeMirror-scroll')[0] l.style.display = 'none' // self.logElement.style.display = 'none' isShowing = false } //} } EditorClass.prototype.clear = function () { this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter') } EditorClass.prototype.setValue = function (val) { this.cm.setValue(val) } EditorClass.prototype.getValue = function () { return this.cm.getValue() } EditorClass.prototype.hide = function () { var l = document.getElementsByClassName('CodeMirror-scroll')[0] var m = document.getElementById('modal-header') // l.style.opacity = 0 // // this.logElement.style.opacity = 0 // m.style.opacity = 0 l.style.display = 'none' m.style.display = 'none' this.isShowing = false } EditorClass.prototype.show = function () { var l = document.getElementsByClassName('CodeMirror-scroll')[0] var m = document.getElementById('modal-header') // l.style.opacity= 1 // m.style.opacity = 1 l.style.display = 'block' m.style.display = 'flex' // this.logElement.style.opacity = 1 this.isShowing = true } EditorClass.prototype.toggle = function () { if (this.isShowing) { this.hide() } else { this.show() } } EditorClass.prototype.getLine = function () { var c = this.cm.getCursor() var s = this.cm.getLine(c.line) // this.cm.markText({line: c.line, ch:0}, {line: c.line+1, ch:0}, {className: 'styled-background'}) this.flashCode({line: c.line, ch:0}, {line: c.line+1, ch:0}) return s } EditorClass.prototype.flashCode = function (start, end) { if(!start) start = {line: this.cm.firstLine(), ch:0} if(!end) end = {line: this.cm.lastLine() + 1, ch:0} var marker = this.cm.markText(start, end, {className: 'styled-background'}) setTimeout(() => marker.clear(), 300) } EditorClass.prototype.getCurrentBlock = function () { // thanks to graham wakefield + gibber var editor = this.cm var pos = editor.getCursor() var startline = pos.line var endline = pos.line while (startline > 0 && editor.getLine(startline) !== '') { startline-- } while (endline < editor.lineCount() && editor.getLine(endline) !== '') { endline++ } var pos1 = { line: startline, ch: 0 } var pos2 = { line: endline, ch: 0 } var str = editor.getRange(pos1, pos2) this.flashCode(pos1, pos2) return { start: pos1, end: pos2, text: str } } module.exports = EditorClass },{"./Mutator.js":3,"codemirror/addon/comment/comment":28,"codemirror/addon/hint/javascript-hint":29,"codemirror/addon/hint/show-hint":30,"codemirror/addon/selection/mark-selection":31,"codemirror/lib/codemirror":32,"codemirror/mode/javascript/javascript":33}],6:[function(require,module,exports){ module.exports=[ { "sketch_id": "example_0", "code": "JTJGJTJGRmxvciUyMGRlJTIwRnVlZ28lMEElMEFzaGFwZSgyMDAlMkMwLjUlMkMxLjUpJTBBLnNjYWxlKDAuNSUyQzAuNSklMEEuY29sb3IoJTVCMC41JTJDMiU1RC5zbW9vdGgoMSklMkMwLjMlMkMwKSUwQS5yZXBlYXQoMiUyQzIpJTBBLm1vZHVsYXRlU2NhbGUob3NjKDMlMkMwLjUpJTJDLTAuNiklMEEuYWRkKG8wJTJDMC41KSUwQS5zY2FsZSgwLjkpJTBBLm91dCgp" },{ "sketch_id": "example_3", "code":"JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTBBb3NjKDIwJTJDJTIwMC4wMyUyQyUyMDEuNykua2FsZWlkKCkubXVsdChvc2MoMjAlMkMlMjAwLjAwMSUyQyUyMDApLnJvdGF0ZSgxLjU4KSkuYmxlbmQobzAlMkMlMjAwLjk0KS5tb2R1bGF0ZVNjYWxlKG9zYygxMCUyQyUyMDApJTJDLTAuMDMpLnNjYWxlKDAuOCUyQyUyMCgpJTIwJTNEJTNFJTIwKDEuMDUlMjAlMkIlMjAwLjElMjAqJTIwTWF0aC5zaW4oMC4wNSp0aW1lKSkpLm91dChvMCk=" },{ "sketch_id": "example_4", "code":"JTJGJTJGJTIwYnklMjBOZWxzb24lMjBWZXJhJTBBJTJGJTJGJTIwdHdpdHRlciUzQSUyMCU0MG5lbF9zb25vbG9naWElMEElMEFvc2MoOCUyQy0wLjUlMkMlMjAxKS5jb2xvcigtMS41JTJDJTIwLTEuNSUyQyUyMC0xLjUpLmJsZW5kKG8wKS5yb3RhdGUoLTAuNSUyQyUyMC0wLjUpLm1vZHVsYXRlKHNoYXBlKDQpLnJvdGF0ZSgwLjUlMkMlMjAwLjUpLnNjYWxlKDIpLnJlcGVhdFgoMiUyQyUyMDIpLm1vZHVsYXRlKG8wJTJDJTIwKCklMjAlM0QlM0UlMjBtb3VzZS54JTIwKiUyMDAuMDAwNSkucmVwZWF0WSgyJTJDJTIwMikpLm91dChvMCklMEElMEElMEElMEElMEElMEE=" },{ "sketch_id": "example_6", "code":"JTJGJTJGJTIwYnklMjBEJUMzJUE5Ym9yYSUyMEZhbGxlaXJvcyUyMEdvbnphbGVzJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuZ29uemFsZXNkZWJvcmEuY29tJTJGJTBBJTBBb3NjKDUpLmFkZChub2lzZSg1JTJDJTIwMikpLmNvbG9yKDAlMkMlMjAwJTJDJTIwMykuY29sb3JhbWEoMC40KS5vdXQoKSUwQSUwQSUwQSUwQQ==" },{ "sketch_id": "example_8", "code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDEwNyUyQyUyMDAlMkMlMjAwLjcpLmNvbG9yKDElMkMlMjAwJTJDJTIwMSkucm90YXRlKDAlMkMlMjAtMC4wOCkubW9kdWxhdGVSb3RhdGUobzElMkMlMjAwLjQpLm91dChvMCklMEFvc2MoMzMpLnJvdGF0ZSgyJTJDJTIwMC44KS5tb2R1bGF0ZVJvdGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwKGEuZmZ0JTVCMCU1RCoyKSkub3V0KG8xKSUwQQ==" },{ "sketch_id": "example_9", "code":"JTJGJTJGJTIwYnklMjBSb2RyaWdvJTIwVmVsYXNjbyUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGeWVjdG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDE4JTJDJTIwMC4xJTJDJTIwMCkuY29sb3IoMiUyQyUyMDAuMSUyQyUyMDIpJTBBLm11bHQob3NjKDIwJTJDJTIwMC4wMSUyQyUyMDApKS5yZXBlYXQoMiUyQyUyMDIwKS5yb3RhdGUoMC41KS5tb2R1bGF0ZShvMSklMEEuc2NhbGUoMSUyQyUyMCgpJTIwJTNEJTNFJTIwJTIwKGEuZmZ0JTVCMCU1RCowLjklMjAlMkIlMjAyKSkuZGlmZihvMSkub3V0KG8wKSUwQW9zYygyMCUyQyUyMDAuMiUyQyUyMDApLmNvbG9yKDIlMkMlMjAwLjclMkMlMjAwLjEpLm11bHQob3NjKDQwKSkubW9kdWxhdGVSb3RhdGUobzAlMkMlMjAwLjIpJTBBLnJvdGF0ZSgwLjIpLm91dChvMSk=" },{ "sketch_id": "example_10", "code":"JTJGJTJGJTIwYnklMjBaYWNoJTIwS3JhbGwlMEElMkYlMkYlMjBodHRwJTNBJTJGJTJGemFjaGtyYWxsLm9ubGluZSUyRiUwQSUwQW9zYyglMjAyMTUlMkMlMjAwLjElMkMlMjAyJTIwKSUwQS5tb2R1bGF0ZSglMEElMjAlMjBvc2MoJTIwMiUyQyUyMC0wLjMlMkMlMjAxMDAlMjApJTBBJTIwJTIwLnJvdGF0ZSgxNSklMEEpJTBBLm11bHQoJTBBJTIwJTIwb3NjKCUyMDIxNSUyQyUyMC0wLjElMkMlMjAyKSUwQSUyMCUyMC5waXhlbGF0ZSglMjA1MCUyQyUyMDUwJTIwKSUwQSklMEEuY29sb3IoJTIwMC45JTJDJTIwMC4wJTJDJTIwMC45JTIwKSUwQS5tb2R1bGF0ZSglMEElMjAlMjBvc2MoJTIwNiUyQyUyMC0wLjElMjApJTBBJTIwJTIwLnJvdGF0ZSglMjA5JTIwKSUwQSklMEEuYWRkKCUwQSUyMCUyMG9zYyglMjAxMCUyQyUyMC0wLjklMkMlMjA5MDAlMjApJTBBJTIwJTIwLmNvbG9yKDElMkMwJTJDMSklMEEpJTBBLm11bHQoJTBBJTIwJTIwc2hhcGUoOTAwJTJDJTIwMC4yJTJDJTIwMSklMEElMjAlMjAubHVtYSgpJTBBJTIwJTIwLnJlcGVhdFgoMiklMEElMjAlMjAucmVwZWF0WSgyKSUwQSUyMCUyMC5jb2xvcmFtYSgxMCklMEEpJTBBLm1vZHVsYXRlKCUwQSUyMCUyMG9zYyglMjA5JTJDJTIwLTAuMyUyQyUyMDkwMCUyMCklMEElMjAlMjAucm90YXRlKCUyMDYlMjApJTBBKSUwQS5hZGQoJTBBJTIwJTIwb3NjKDQlMkMlMjAxJTJDJTIwOTApJTBBJTIwJTIwLmNvbG9yKDAuMiUyQzAlMkMxKSUwQSklMEEub3V0KCklMEE=" },{ "sketch_id": "example_11", "code": "JTJGJTJGJTIwYnklMjBaYWNoJTIwS3JhbGwlMEElMkYlMkYlMjBodHRwJTNBJTJGJTJGemFjaGtyYWxsLm9ubGluZSUyRiUwQSUwQW9zYygxMCUyQyUyMDAuOSUyQyUyMDMwMCklMEEuY29sb3IoMC45JTJDJTIwMC43JTJDJTIwMC44KSUwQS5kaWZmKCUwQSUyMCUyMG9zYyg0NSUyQyUyMDAuMyUyQyUyMDEwMCklMEElMjAlMjAuY29sb3IoMC45JTJDJTIwMC45JTJDJTIwMC45KSUwQSUyMCUyMC5yb3RhdGUoMC4xOCklMEElMjAlMjAucGl4ZWxhdGUoMTIpJTBBJTIwJTIwLmthbGVpZCgpJTBBKSUwQS5zY3JvbGxYKDEwKSUwQS5jb2xvcmFtYSgpJTBBLmx1bWEoKSUwQS5yZXBlYXRYKDQpJTBBLnJlcGVhdFkoNCklMEEubW9kdWxhdGUoJTBBJTIwJTIwb3NjKDElMkMlMjAtMC45JTJDJTIwMzAwKSUwQSklMEEuc2NhbGUoMiklMEEub3V0KCklMEE=" },{ "sketch_id": "example_13", "code":"JTJGJTJGJTIwYWNpZCUyMGJ1cyUyMHNlYXQlMEElMkYlMkYlMjBieSUyMFdpbGwlMjBIdW1waHJleXMlMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRmdpdGh1Yi5jb20lMkZUaGVXaXNweSUwQSUwQW9zYygxMDUpLmNvbG9yKDAuNSUyQzAuMSUyQzAuOCkucm90YXRlKDAuMTElMkMlMjAwLjEpLm1vZHVsYXRlKG9zYygxMCkucm90YXRlKDAuMykuYWRkKG8wJTJDJTIwMC4xKSkuYWRkKG9zYygyMCUyQzAuMDElMkMxKS5jb2xvcigwJTJDMC44JTJDMSkpLm91dChvMCklMEFvc2MoNTAlMkMwLjA1JTJDJTIwMC43KS5jb2xvcigxJTJDMC43JTJDMC41KS5kaWZmKG8wKS5tb2R1bGF0ZShvMSUyQzAuMDUpLm91dChvMSklMEFyZW5kZXIobzEp" }, { "sketch_id": "example_14", "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwJTQwX29qYWNrXyUwQSUwQW9zYygyMCUyQyUyMDAuMDElMkMlMjAxLjEpJTBBJTA5LmthbGVpZCg1KSUwQSUwOS5jb2xvcigyLjgzJTJDMC45MSUyQzAuMzkpJTBBJTA5LnJvdGF0ZSgwJTJDJTIwMC4xKSUwQSUwOS5tb2R1bGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwbW91c2UueCUyMColMjAwLjAwMDMpJTBBJTA5LnNjYWxlKDEuMDEpJTBBJTIwJTIwJTA5Lm91dChvMCk=" }, { "sketch_id": "example_15", "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoMTAwJTJDJTIwMC4wMSUyQyUyMDEuNCklMEElMDkucm90YXRlKDAlMkMlMjAwLjEpJTBBJTA5Lm11bHQob3NjKDEwJTJDJTIwMC4xKS5tb2R1bGF0ZShvc2MoMTApLnJvdGF0ZSgwJTJDJTIwLTAuMSklMkMlMjAxKSklMEElMDkuY29sb3IoMi44MyUyQzAuOTElMkMwLjM5KSUwQSUyMCUyMC5vdXQobzAp" }, { "sketch_id": "example_16", "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoNCUyQyUyMDAuMSUyQyUyMDAuOCkuY29sb3IoMS4wNCUyQzAlMkMlMjAtMS4xKS5yb3RhdGUoMC4zMCUyQyUyMDAuMSkucGl4ZWxhdGUoMiUyQyUyMDIwKS5tb2R1bGF0ZShub2lzZSgyLjUpJTJDJTIwKCklMjAlM0QlM0UlMjAxLjUlMjAqJTIwTWF0aC5zaW4oMC4wOCUyMColMjB0aW1lKSkub3V0KG8wKQ==" }, { "sketch_id": "example_17", "code": "JTJGJTJGJTIwbW9pcmUlMEElMkYlMkYlMjBieSUyME9saXZpYSUyMEphY2slMEElMkYlMkYlMjB0d2l0dGVyJTNBJTIwJTQwX29qYWNrXyUwQSUwQXBhdHRlcm4lMjAlM0QlMjAoKSUyMCUzRCUzRSUyMG9zYygyMDAlMkMlMjAwKS5rYWxlaWQoMjAwKS5zY2FsZSgxJTJDJTIwMC40KSUwQSUyRiUyRiUwQXBhdHRlcm4oKSUwQSUyMCUyMC5zY3JvbGxYKDAuMSUyQyUyMDAuMDEpJTBBJTIwJTIwLm11bHQocGF0dGVybigpKSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "example_18", "code": "JTJGJTJGJTIwYnklMjBPbGl2aWElMjBKYWNrJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZvamFjay5naXRodWIuaW8lMEElMEFvc2MoNiUyQyUyMDAlMkMlMjAwLjgpJTBBJTIwJTIwLmNvbG9yKDEuMTQlMkMlMjAwLjYlMkMuODApJTBBJTIwJTIwLnJvdGF0ZSgwLjkyJTJDJTIwMC4zKSUwQSUyMCUyMC5waXhlbGF0ZSgyMCUyQyUyMDEwKSUwQSUyMCUyMC5tdWx0KG9zYyg0MCUyQyUyMDAuMDMpLnRocmVzaCgwLjQpLnJvdGF0ZSgwJTJDJTIwLTAuMDIpKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvc2MoMjAlMkMlMjAwKS50aHJlc2goMC4zJTJDJTIwMC42KSUyQyUyMCgpJTIwJTNEJTNFJTIwMC4xJTIwJTJCJTIwbW91c2UueCUyMColMjAwLjAwMiklMEElMjAlMjAub3V0KG8wKQ==" }, { "sketch_id": "rangga_0", "code": "JTJGJTJGJTIwRHJlYW15JTIwRGlhbW9uZCUwQSUyRiUyRiUyMGJ5JTIwUmFuZ2dhJTIwUHVybmFtYSUyMEFqaSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGcmFuZ2dhcHVybmFtYWFqaTEud2l4c2l0ZS5jb20lMkZwb3J0Zm9saW8lMEElMEFvc2MoNyUyQy0wLjEyNSkubW9kdWxhdGUodm9yb25vaSgxKSkuZGlmZih2b3Jvbm9pKDEpLm11bHQoZ3JhZGllbnQoLTEpLmx1bWEoMC4xMjUpKSklMEElMjAlMjAubHVtYSgwLjEyNSklMEElMjAlMjAuYWRkKHNoYXBlKDclMkMlMjAwLjUpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwLm11bHQodm9yb25vaSgxMCUyQzIpLmJsZW5kKG8wKS5kaWZmKGdyYWRpZW50KDEpKS5tb2R1bGF0ZSh2b3Jvbm9pKCkpKSklMEElMjAlMjAuc2Nyb2xsWSgtMC4xKSUwQSUyMCUyMC5zY3JvbGxYKDAuMTI1KSUwQSUyMCUyMC5ibGVuZChvMCklMEElMjAlMjAuYmxlbmQobzApJTBBJTIwJTIwLm91dCgpJTBB" }, { "sketch_id": "rangga_1", "code": "JTJGJTJGJTIwVGFnJTIwJTI2JTIwU3dlZXAlMEElMkYlMkYlMjBieSUyMFJhbmdnYSUyMFB1cm5hbWElMjBBamklMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRnJhbmdnYXB1cm5hbWFhamkxLndpeHNpdGUuY29tJTJGcG9ydGZvbGlvJTBBJTBBb3NjKDUlMkMwLjEyNSkuY29sb3JhbWEoMSklMEElMjAlMjAubHVtYSgwLjEyNSkuYWRkKHNoYXBlKDElMkMwLjUpLmx1bWEoMikuZGlmZihncmFkaWVudCgxKSkpJTBBJTIwJTIwLmRpZmYob3NjKC0xJTJDLTAuMjUpKS5ibGVuZChvMCkuY29sb3IoMCUyQzIuNSUyQzEuNzUpJTBBJTIwJTIwLm91dCgp" }, { "sketch_id": "rangga_2", "code": "JTJGJTJGJTIwTW9ub2Nocm9tZSUyME1lbW9hciUwQSUyRiUyRiUyMGJ5JTIwUmFuZ2dhJTIwUHVybmFtYSUyMEFqaSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGcmFuZ2dhcHVybmFtYWFqaTEud2l4c2l0ZS5jb20lMkZwb3J0Zm9saW8lMEElMEF2b3Jvbm9pKDUwJTJDMSklMEElMjAlMjAubHVtYSgwLjUpLmFkZChzaGFwZSgxJTJDMSkubHVtYSgxKSklMEElMjAlMjAubW9kdWxhdGUob3NjKC0xMDAwJTJDLTEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLm1vZHVsYXRlKG9zYygpLmx1bWEoKSkpJTBBJTIwJTIwLmJsZW5kKG8wKSUwQSUyMCUyMC5ibGVuZChvMCklMEElMjAlMjAuYmxlbmQobzApJTBBJTIwJTIwLmJsZW5kKG8wKSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "rangga_3", "code": "JTJGJTJGJTIwR2FsYXh5JTIwVHJpcCUwQSUyRiUyRiUyMGJ5JTIwUmFuZ2dhJTIwUHVybmFtYSUyMEFqaSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGcmFuZ2dhcHVybmFtYWFqaTEud2l4c2l0ZS5jb20lMkZwb3J0Zm9saW8lMEElMEFzaGFwZSgxJTJDMSklMEElMjAlMjAubXVsdCh2b3Jvbm9pKDEwMDAlMkMyKSUwQSUyMCUyMC5ibGVuZChvMCkubHVtYSgpKSUwQSUyMCUyMC5hZGQoc2hhcGUoMyUyQzAuMTI1KSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMC5yb3RhdGUoMSUyQzEpLm11bHQodm9yb25vaSgxMDAwJTJDMSkubHVtYSgpKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMC5yb3RhdGUoMS41KSkuc2Nyb2xsWCglNUIwLjElMkMtMC4wNjI1JTJDMC4wMDUlMkMwLjAwMDAxJTVEJTJDMCklMEElMjAlMjAuc2Nyb2xsWSglNUIwLjElMkMtMC4wNjI1JTJDMC4wMDUlMkMwLjAwMDAxJTVEJTJDMCklMEElMjAlMjAub3V0KCk=" }, { "sketch_id": "rangga_4", "code": "JTJGJTJGJTIwU3VtZXQlMEElMkYlMkYlMjBieSUyMFJhbmdnYSUyMFB1cm5hbWElMjBBamklMEElMkYlMkYlMjBodHRwcyUzQSUyRiUyRnJhbmdnYXB1cm5hbWFhamkxLndpeHNpdGUuY29tJTJGcG9ydGZvbGlvJTBBJTBBb3NjKDAuNSUyQzEuMjUpLm11bHQoc2hhcGUoMSUyQzAuMDkpLnJvdGF0ZSgxLjUpKSUwQSUyMCUyMC5kaWZmKGdyYWRpZW50KCkpJTBBJTIwJTIwLmFkZChzaGFwZSgyJTJDMikuYmxlbmQoZ3JhZGllbnQoMSkpKSUwQSUyMCUyMC5tb2R1bGF0ZShub2lzZSgpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLm1vZHVsYXRlKG5vaXNlKCkuc2Nyb2xsWSgxJTJDMC4wNjI1KSkpJTBBJTIwJTIwLmJsZW5kKG8wKSUwQSUyMCUyMC5jb2xvcigxJTJDLTAuNSUyQy0wLjc1KSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "marianne_0", "code": "JTJGJTJGcG9ydCUwQSUyRiUyRmJ5JTIwTWFyaWFubmUlMjBUZWl4aWRvJTBBJTJGJTJGaHR0cHMlM0ElMkYlMkZtYXJpYW5uZXRlaXhpZG8uZ2l0aHViLmlvJTJGJTBBJTBBb3NjKDUlMkMlMjAwLjklMkMlMjAwLjAwMSklMEElMjAlMjAlMjAlMjAua2FsZWlkKCU1QjMlMkM0JTJDNSUyQzclMkM4JTJDOSUyQzEwJTVELmZhc3QoMC4xKSklMEElMjAlMjAlMjAlMjAuY29sb3IoMC41JTJDJTIwMC4zKSUwQSUyMCUyMCUyMCUyMC5jb2xvcmFtYSgwLjQpJTBBJTIwJTIwJTIwJTIwLnJvdGF0ZSgwLjAwOSUyQygpJTNEJTNFTWF0aC5zaW4odGltZSkqJTIwLTAuMDAxJTIwKSUwQSUyMCUyMCUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvMCUyQygpJTNEJTNFTWF0aC5zaW4odGltZSklMjAqJTIwMC4wMDMpJTBBJTIwJTIwJTIwJTIwLm1vZHVsYXRlKG8wJTJDJTIwMC45KSUwQSUyMCUyMCUyMCUyMC5zY2FsZSgwLjkpJTBBJTIwJTIwJTIwJTIwLm91dChvMCklMEElMEE=" }, { "sketch_id": "marianne_1", "code": "JTJGJTJGUGl4ZWxzY2FwZSUwQSUyRiUyRk1hcmlhbm5lJTIwVGVpeGlkbyUwQSUyRiUyRmh0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRk1hcmlhbm5lVGVpeGlkbyUwQSUwQXNyYyhvMCklMEElMjAuc2F0dXJhdGUoMS4wMSklMEElMjAuc2NhbGUoLjk5OSklMEElMjAuY29sb3IoMS4wMSUyQzEuMDElMkMxLjAxKSUwQSUyMC5odWUoLjAxKSUwQSUyMC5tb2R1bGF0ZUh1ZShzcmMobzEpLmh1ZSguMykucG9zdGVyaXplKC0xKS5jb250cmFzdCguNyklMkMyKSUwQSUyMCUyMC5sYXllcihzcmMobzEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLmx1bWEoKSUwQSUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMC5tdWx0KGdyYWRpZW50KDEpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwJTIwLnNhdHVyYXRlKC45KSkpJTBBJTIwJTIwLm91dChvMCklMEElMEFub2lzZSgxJTJDJTIwLjIpJTBBJTIwJTIwLnJvdGF0ZSgyJTJDLjUpJTBBJTIwJTIwLmxheWVyKHNyYyhvMCklMEElMjAlMjAuc2Nyb2xsWCguMikpJTBBJTIwJTIwLm91dChvMSklMEElMEFyZW5kZXIobzAp" }, { "sketch_id": "naoto_0", "code": "JTJGJTJGJTIwJTQwbmFvdG9faGllZGElMEFvc2MoMjAlMkMlMjAwLjElMkMlMjAwKS5jb2xvcigwJTJDJTIwMSUyQyUyMDIpLnJvdGF0ZSgxLjU3JTJGMikub3V0KG8xKSUwQW9zYygzMCUyQyUyMDAuMDElMkMlMjAwKS5jb2xvcigyJTJDJTIwMC43JTJDJTIwMSkubW9kdWxhdGUobzElMkMlMjAwKS5hZGQobzElMkMxKS5tb2R1bGF0ZVBpeGVsYXRlKG8xJTJDMSUyQzEwKS5vdXQobzAp" }, { "sketch_id": "naoto_1", "code": "JTJGJTJGJTIwJTQwbmFvdG9faGllZGElMEFzb2xpZCgwLjIlMkMwLjYlMkMwLjkpLmxheWVyKG9zYygzMS40JTJDMCkudGhyZXNoKDAuNykubHVtYSgpLm1vZHVsYXRlKG9zYyg0JTJDMSkucm90YXRlKDEpJTJDMC4wNSkuY29sb3IoMCUyQzAlMkMwKSkubGF5ZXIob3NjKDMxLjQlMkMwKS50aHJlc2goMC43KS5sdW1hKCkubW9kdWxhdGUob3NjKDQlMkMxKS5yb3RhdGUoMSklMkMwLjEpKS5vdXQoKQ==" }, { "sketch_id": "ritchse_0", "code": "JTJGJTJGcmFuZG9tJTIwdHJ5cG9waG9iaWElMjAtJTIwY2hhbmdlcyUyMGV2ZXJ5dGltZSUyMHlvdSUyMGxvYWQlMjBpdCElMEElMkYlMkZieSUyMFJpdGNoc2UlMEElMkYlMkZpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQWZ1bmN0aW9uJTIwcihtaW4lM0QwJTJDbWF4JTNEMSklMjAlN0IlMjByZXR1cm4lMjBNYXRoLnJhbmRvbSgpKihtYXgtbWluKSUyQm1pbiUzQiUyMCU3RCUwQSUyMCUwQXNvbGlkKDElMkMxJTJDMSklMEElMjAlMjAlMDkuZGlmZihzaGFwZSglNUI0JTJDNCUyQzQlMkMyNCU1RC5zbW9vdGgoKS5mYXN0KC41KSUyQ3IoMC42JTJDMC45MyklMkMuMDkpLnJlcGVhdCgyMCUyQzEwKSklMEElMDkubW9kdWxhdGVTY2FsZShvc2MoOCkucm90YXRlKHIoLS41JTJDLjUpKSUyQy41MiklMEElMDkuYWRkKCUwQSUyMCUyMCUwOSUwOXNyYyhvMCkuc2NhbGUoMC45NjUpLnJvdGF0ZSguMDEyKihNYXRoLnJvdW5kKHIoLTIlMkMxKSkpKSUwQSUyMCUyMCUwOSUwOS5jb2xvcihyKCklMkNyKCklMkNyKCkpJTBBJTIwJTIwJTIwJTIwJTA5Lm1vZHVsYXRlUm90YXRlKG8wJTJDcigwJTJDMC41KSklMEElMjAlMjAlMDklMDkuYnJpZ2h0bmVzcyguMTUpJTBBJTIwJTIwJTA5JTA5JTJDLjcpJTBBJTA5Lm91dCgp" }, { "sketch_id": "ritchse_1", "code": "JTJGJTJGY29ycnVwdGVkJTIwc2NyZWVuc2F2ZXIlMEElMkYlMkZieSUyMFJpdGNoc2UlMEElMkYlMkZpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQXZvcm9ub2koMzUwJTJDMC4xNSklMEElMjAlMjAlMDkubW9kdWxhdGVTY2FsZShvc2MoOCkucm90YXRlKE1hdGguc2luKHRpbWUpKSUyQy41KSUwQSUyMCUyMCUwOS50aHJlc2goLjgpJTBBJTA5Lm1vZHVsYXRlUm90YXRlKG9zYyg3KSUyQy40KSUwQSUwOS50aHJlc2goLjcpJTBBJTIwJTIwJTA5LmRpZmYoc3JjKG8wKS5zY2FsZSgxLjgpKSUwQSUwOS5tb2R1bGF0ZVNjYWxlKG9zYygyKS5tb2R1bGF0ZVJvdGF0ZShvMCUyQy43NCkpJTBBJTA5LmRpZmYoc3JjKG8wKS5yb3RhdGUoJTVCLS4wMTIlMkMuMDElMkMtLjAwMiUyQzAlNUQpLnNjcm9sbFkoMCUyQyU1Qi0xJTJGMTk5ODAwJTJDMCU1RC5mYXN0KDAuNykpKSUwQSUwOS5icmlnaHRuZXNzKCU1Qi0uMDIlMkMtLjE3JTVELnNtb290aCgpLmZhc3QoLjUpKSUwQSUwOS5vdXQoKQ==" }, { "sketch_id": "ritchse_2", "code": "JTJGJTJGdHJvcGljYWwlMjBqdWljZSUwQSUyRiUyRmJ5JTIwUml0Y2hzZSUwQSUyRiUyRmluc3RhZ3JhbS5jb20lMkZyaXRjaHNlJTBBJTIwJTBBdm9yb25vaSgyJTJDMC4zJTJDMC4yKS5zaGlmdCgwLjUpJTBBLm1vZHVsYXRlUGl4ZWxhdGUodm9yb25vaSg0JTJDMC4yKSUyQzMyJTJDMiklMEEuc2NhbGUoKCklM0QlM0UxJTJCKE1hdGguc2luKHRpbWUqMi41KSowLjA1KSklMEEuZGlmZih2b3Jvbm9pKDMpLnNoaWZ0KDAuNikpJTBBLmRpZmYob3NjKDIlMkMwLjE1JTJDMS4xKS5yb3RhdGUoKSklMEEuYnJpZ2h0bmVzcygwLjEpLmNvbnRyYXN0KDEuMikuc2F0dXJhdGUoMS4yKSUwQSUwOS5vdXQoKSUwQXNwZWVkJTIwJTNEJTIwMC44" }, { "sketch_id": "ritchse_3", "code": "JTJGJTJGdHJ5aW5nJTIwdG8lMjBnZXQlMjBjbG9zZXIlMEElMkYlMkZieSUyMFJpdGNoc2UlMEElMkYlMkZpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQW9zYyg2MCUyQy0wLjAxNSUyQzAuMykuZGlmZihvc2MoNjAlMkMwLjA4KS5yb3RhdGUoTWF0aC5QSSUyRjIpKSUwQSUwOS5tb2R1bGF0ZVNjYWxlKG5vaXNlKDMuNSUyQzAuMjUpLm1vZHVsYXRlU2NhbGUob3NjKDE1KS5yb3RhdGUoKCklM0QlM0VNYXRoLnNpbih0aW1lJTJGMikpKSUyQzAuNiklMEElMDkuY29sb3IoMSUyQzAuNSUyQzAuNCkuY29udHJhc3QoMS40KSUwQSUwOS5hZGQoc3JjKG8wKS5tb2R1bGF0ZShvMCUyQy4wNCklMkMuNiklMEElMDkuaW52ZXJ0KCkuYnJpZ2h0bmVzcygwLjEpLmNvbnRyYXN0KDEuMiklMEElMDkubW9kdWxhdGVTY2FsZShvc2MoMiklMkMtMC4yKSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "ritchse_4", "code": "JTJGJTJGJTIwZGlzaW50ZWdyYXRpb24lMEElMkYlMkYlMjBieSUyMFJpdGNoc2UlMEElMkYlMkYlMjBpbnN0YWdyYW0uY29tJTJGcml0Y2hzZSUwQSUyMCUwQW9zYyg1JTJDLjEpLm1vZHVsYXRlKG5vaXNlKDYpJTJDLjIyKS5kaWZmKG8wKSUwQSUyMCUyMCUwOS5tb2R1bGF0ZVNjcm9sbFkob3NjKDIpLm1vZHVsYXRlKG9zYygpLnJvdGF0ZSgpJTJDLjExKSklMEElMDkuc2NhbGUoLjcyKS5jb2xvcigwLjk5JTJDMS4wMTQlMkMxKSUwQSUyMCUyMCUwOS5vdXQoKQ== " }, { "sketch_id": "flor_0", "code": "JTJGJTJGRmxvciUyMGRlJTIwRnVlZ28lMEElMkYlMkZodHRwcyUzQSUyRiUyRmZsb3JkZWZ1ZWdvLmdpdGh1Yi5pbyUyRiUwQW9zYygzMCUyQzAuMDElMkMxKSUwQS5tdWx0KG9zYygyMCUyQy0wLjElMkMxKS5tb2R1bGF0ZShub2lzZSgzJTJDMSkpLnJvdGF0ZSgwLjcpKSUwQS5wb3N0ZXJpemUoJTVCMyUyQzEwJTJDMiU1RC5mYXN0KDAuNSkuc21vb3RoKDEpKSUwQS5tb2R1bGF0ZVJvdGF0ZShvMCUyQygpJTNEJTNFbW91c2UueCowLjAwMyklMEEub3V0KCk= " }, { "sketch_id": "mahalia_0", "code": "JTJGJTJGJTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwJTQwbW1faHJfJTBBJTBBc2hhcGUoMjAlMkMwLjElMkMwLjAxKSUwQSUyMCUyMC5zY2FsZSgoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjMpJTBBJTIwJTIwLnJlcGVhdCgoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjEwKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvMCklMEElMjAlMjAuc2NhbGUoKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSoyKSUwQSUyMCUyMC5tb2R1bGF0ZShub2lzZSgyJTJDMCkpJTBBJTIwJTIwLnJvdGF0ZSgwLjElMkMlMjAwLjkpJTBBLm91dChvMCklMEElMEFzcmMobzApJTBBLm1vZHVsYXRlKG9zYyg1MDAlMkMwJTJDMCkpJTBBLm91dChvMSklMEElMEFzcmMobzEpJTBBLm1vZHVsYXRlS2FsZWlkKHZvcm9ub2koKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSozJTJDMC4xJTJDMC4wMSklMkMoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjMpJTBBLnNjYWxlKCgpJTIwJTNEJTNFJTIwTWF0aC5zaW4odGltZSkqMyklMEEub3V0KG8yKSUwQSUwQXJlbmRlcihvMik=" }, { "sketch_id": "mahalia_1", "code": "JTJGJTJGJTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwJTQwbW1faHJfJTBBJTBBc2hhcGUoKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSUyQjEqMiklMEEucm90YXRlKCgpJTIwJTNEJTNFJTIwTWF0aC5QSSUyMColMjBtb3VzZS54JTIwJTJGMTgwKSUwQS5yZXBlYXRYKDMpJTBBLnJlcGVhdFkoKCklM0QlM0VNYXRoLnNpbih0aW1lKSo1KSUwQS5zY2FsZSgoKSUyMCUzRCUzRSUyME1hdGguUEklMkY0KSUwQS5ibGVuZChzcmMobzApLmNvbG9yKDElMkMwJTJDMCkpJTBBLm1vZHVsYXRlKG9zYygyMCUyQyUyMDAlMkMuNCkpJTBBLmthbGVpZCgyKSUwQSUyMC5vdXQobzApJTBBJTBBcmVuZGVyKG8wKQ==" }, { "sketch_id": "mahalia_2", "code": "JTJGJTJGJTIwVmVsdmV0JTIwUG9vbCUwQSUyRiUyRiUyMGJ5JTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwbW1faHJfJTBBJTBBJTBBbm9pc2UoKSUwQS5jb2xvcigoKSUyMCUzRCUzRSUyMGEuZmZ0JTVCMiU1RCoyJTJDMCUyQy42KSUwQS5tb2R1bGF0ZShub2lzZSgoKSUyMCUzRCUzRSUyMGEuZmZ0JTVCMCU1RCoxMCkpJTBBLnNjYWxlKCgpJTNEJTNFJTIwYS5mZnQlNUIyJTVEKjUpJTBBLmxheWVyKCUwQSUyMCUyMHNyYyhvMCklMEElMjAlMjAubWFzayhvc2MoMTApLm1vZHVsYXRlUm90YXRlKG9zYygpJTJDOTAlMkMwKSklMEElMjAlMjAuc2NhbGUoKCklMjAlM0QlM0UlMjBhLmZmdCU1QjAlNUQqMiklMEElMjAlMjAubHVtYSgwLjIlMkMwLjMpJTBBKSUwQS5ibGVuZChvMCklMEEub3V0KG8wKSUwQSUwQW9zYygpJTBBLm1vZHVsYXRlKG5vaXNlKCgpJTIwJTNEJTNFJTIwYS5mZnQlNUIxJTVEJTJCNSkpJTBBLmNvbG9yKDElMkMwJTJDMCklMEEub3V0KG8xKSUwQSUwQXNyYyhvMCklMEEubW9kdWxhdGUobzEpJTBBLmxheWVyKCUwQSUyMCUyMHNyYyhvMSklMEElMjAlMjAubWFzayhvMSklMEElMjAlMjAuc2F0dXJhdGUoNyklMEEpJTBBLm1vZHVsYXRlUm90YXRlKG8xKSUwQS5yb3RhdGUoKCU3QnRpbWUlN0QpJTIwJTNEJTNFJTIwdGltZSUyNTM2MCowLjA1KSUwQS5vdXQobzIpJTBBJTBBcmVuZGVyKG8yKQ==" }, { "sketch_id": "mahalia_3", "code": "JTJGJTJGJTIwYnklMjBNYWhhbGlhJTIwSC1SJTBBJTJGJTJGJTIwSUclM0ElMjBtbV9ocl8lMEElMEFzaGFwZSgoKSUzRCUzRU1hdGguc2luKHRpbWUpJTJCMSozJTJDJTIwLjUlMkMuMDEpJTBBLnJlcGVhdCg1JTJDMyUyQyUyMCgpJTNEJTNFYS5mZnQlNUIwJTVEKjIlMkMlMjAoKSUzRCUzRWEuZmZ0JTVCMSU1RCoyKSUwQS5zY3JvbGxZKC41JTJDMC4xKSUwQS5sYXllciglMEElMjAlMjBzcmMobzEpJTBBJTIwJTIwLm1hc2sobzApJTBBJTIwJTIwLmx1bWEoLjAxJTJDJTIwLjEpJTBBJTIwJTIwLmludmVydCguMiklMEEpJTBBLm1vZHVsYXRlKG8xJTJDLjAyKSUwQS5vdXQobzApJTBBJTBBb3NjKDQwJTJDJTIwMC4wOSUyQyUyMDAuOSklMEEuY29sb3IoLjklMkMwJTJDNSklMEEubW9kdWxhdGUob3NjKDEwKS5yb3RhdGUoMSUyQyUyMDAuNSkpJTBBLnJvdGF0ZSgxJTJDJTIwMC4yKSUwQS5vdXQobzEpJTBBJTBBcmVuZGVyKG8wKSUwQSUwQQ==" }, { "sketch_id": "mahalia_4", "code": "JTJGJTJGJTIwQ2VsbHVsYXIlMjAlMjYlMjBCbG9idWxhciUwQSUyRiUyRiUyMGJ5JTIwTWFoYWxpYSUyMEgtUiUwQSUyRiUyRiUyMElHJTNBJTIwbW1faHJfJTBBJTBBc3BlZWQlMjAlM0QlMjAwLjMlMEElMEFzaGFwZSgyMCUyQzAuMiUyQzAuMyklMEEuY29sb3IoMC41JTJDMC44JTJDNTApJTBBJTIwJTIwLnNjYWxlKCgpJTIwJTNEJTNFJTIwTWF0aC5zaW4odGltZSklMkIxKjIpJTBBJTIwJTIwLnJlcGVhdCgoKSUyMCUzRCUzRSUyME1hdGguc2luKHRpbWUpKjEwKSUwQSUyMCUyMC5tb2R1bGF0ZVJvdGF0ZShvMCklMEElMjAlMjAuc2NhbGUoKCklMjAlM0QlM0UlMjBNYXRoLnNpbih0aW1lKSUyQjElMjAqMS41KSUwQSUyMCUyMC5tb2R1bGF0ZShub2lzZSgyJTJDMikpJTBBJTIwJTIwLnJvdGF0ZSgxJTJDJTIwLjIpJTBBJTIwJTIwJTJGJTJGJTIwLmludmVydCgyLjQpJTBBLm91dChvMCklMEE=" }, { "sketch_id": "andromeda_0", "code": "JTJGJTJGJTIwMy4wJTBBJTJGJTJGJTIwYnklMjAlQ0UlOTRORFIwTTNEJUNFJTk0JTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuaW5zdGFncmFtLmNvbSUyRmFuZHJvbTNfZGElMkYlMEElMEElMEFub2lzZSgzJTJDMC4zJTJDMykudGhyZXNoKDAuMyUyQzAuMDMpLmRpZmYobzMlMkMwLjMpLm91dChvMSklMEFncmFkaWVudCglNUIwLjMlMkMwLjMlMkMzJTVEKS5kaWZmKG8wKS5ibGVuZChvMSkub3V0KG8zKSUwQXZvcm9ub2koMzMlMkMzJTJDMzApLnJvdGF0ZSgzJTJDMC4zJTJDMCkubW9kdWxhdGVTY2FsZShvMiUyQzAuMykuY29sb3IoLTMlMkMzJTJDMCkuYnJpZ2h0bmVzcygzKS5vdXQobzApJTBBc2hhcGUoMzAlMkMwLjMlMkMxKS5pbnZlcnQoKCU3QnRpbWUlN0QpJTNEJTNFTWF0aC5zaW4odGltZSkqMykub3V0KG8yKSUwQSUwQXJlbmRlcihvMyklMEE=" }, { "sketch_id": "andromeda_1", "code": "JTJGJTJGJTIwMy4zJTBBJTJGJTJGJTIwYnklMjAlQ0UlOTRORFIwTTNEJUNFJTk0JTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZ3d3cuaW5zdGFncmFtLmNvbSUyRmFuZHJvbTNfZGElMkYlMEElMEFvc2MoKS5tb2R1bGF0ZVJvdGF0ZShvMCUyQzAuMykub3V0KCklMEFvc2MoMzMlMkMwLjMlMkMwLjMpLmRpZmYobzMlMkMzKS5vdXQobzEpJTBBb3NjKDMlMkMwLjMlMkMzMykubW9kdWxhdGVLYWxlaWQobzMlMkMzKS5kaWZmKG8wKS5vdXQobzIpJTBBc3JjKG8wJTJDMykubXVsdChvMSUyQzMpLmthbGVpZCgzKS5vdXQobzMpJTBBcmVuZGVyKG8yKQ==" }, { "sketch_id": "asdrubal_0", "code": "JTJGJTJGQXNkciVDMyVCQWJhbCUyMEdvbWV6JTBBJTBBbm9pc2UoMyUyQzAuMSUyQzcpJTBBLnJvdGF0ZSgxJTJDLTElMkMtMikubWFzayhzaGFwZSgyMCkpJTBBLmNvbG9yYW1hKDAuNSklMEEubW9kdWxhdGVTY2FsZShvMCklMEEubW9kdWxhdGVTY2FsZShvMCUyQzElMkMpJTBBLmJsZW5kKG8wKSUwQS5ibGVuZChvMCklMEEuYmxlbmQobzApJTBBLmJsZW5kKG8wKSUwQS5vdXQobzApJTBB" }, { "sketch_id": "flor_1", "code": "JTJGJTJGSHlkcmElMjBHbGl0Y2h5JTIwU2xpdCUyMFNjYW4lMEElMkYlMkZGbG9yJTIwZGUlMjBGdWVnbyUwQSUyRiUyRmh0dHBzJTNBJTJGJTJGZmxvcmRlZnVlZ28uZ2l0aHViLmlvJTJGJTIwJTBBczAuaW5pdENhbSgpJTBBc3JjKHMwKS5zYXR1cmF0ZSgyKS5jb250cmFzdCgxLjMpLmxheWVyKHNyYyhvMCkubWFzayhzaGFwZSg0JTJDMikuc2NhbGUoMC41JTJDMC43KS5zY3JvbGxYKDAuMjUpKS5zY3JvbGxYKDAuMDAxKSkubW9kdWxhdGUobzAlMkMwLjAwMSkub3V0KG8wKSUwQSUwQQ==" }, { "sketch_id": "flor_2", "code": "JTJGJTJGR2xpdGNoJTIwUml2ZXIlMEElMkYlMkZGbG9yJTIwZGUlMjBGdWVnbyUwQSUyRiUyRmh0dHBzJTNBJTJGJTJGZmxvcmRlZnVlZ28uZ2l0aHViLmlvJTJGJTBBdm9yb25vaSg4JTJDMSklMEEubXVsdChvc2MoMTAlMkMwLjElMkMoKSUzRCUzRU1hdGguc2luKHRpbWUpKjMpLnNhdHVyYXRlKDMpLmthbGVpZCgyMDApKSUwQS5tb2R1bGF0ZShvMCUyQzAuNSklMEEuYWRkKG8wJTJDMC44KSUwQS5zY3JvbGxZKC0wLjAxKSUwQS5zY2FsZSgwLjk5KSUwQS5tb2R1bGF0ZSh2b3Jvbm9pKDglMkMxKSUyQzAuMDA4KSUwQS5sdW1hKDAuMyklMEEub3V0KCklMEElMEElMEFzcGVlZCUyMCUzRCUyMDAuMSUwQSUwQSUwQSUwQQ==" }, { "sketch_id": "nesso_0", "code": "JTBBJTJGJTJGY2xvdWRzJTIwb2YlMjBwYXNzYWdlJTBBJTJGJTJGYnklMjBOZXNzbyUwQSUyRiUyRnd3dy5uZXNzby54eXolMEElMEFzaGFwZSglNUI0JTJDNSUyQzYlNUQuZmFzdCgwLjEpLnNtb290aCgxKSUyQzAuMDAwMDAxJTJDJTVCMC4yJTJDMC43JTVELnNtb290aCgxKSklMEEuY29sb3IoMC4yJTJDMC40JTJDMC4zKSUwQS5zY3JvbGxYKCgpJTNEJTNFTWF0aC5zaW4odGltZSowLjI3KSklMEEuYWRkKCUwQSUyMCUyMHNoYXBlKCU1QjQlMkM1JTJDNiU1RC5mYXN0KDAuMSkuc21vb3RoKDEpJTJDMC4wMDAwMDElMkMlNUIwLjIlMkMwLjclMkMwLjUlMkMwLjMlNUQuc21vb3RoKDEpKSUwQSUyMCUyMC5jb2xvcigwLjYlMkMwLjIlMkMwLjUpJTBBJTIwJTIwLnNjcm9sbFkoMC4zNSklMEElMjAlMjAuc2Nyb2xsWCgoKSUzRCUzRU1hdGguc2luKHRpbWUqMC4zMykpKSUwQS5hZGQoJTBBJTIwJTIwc2hhcGUoJTVCNCUyQzUlMkM2JTVELmZhc3QoMC4xKS5zbW9vdGgoMSklMkMwLjAwMDAwMSUyQyU1QjAuMiUyQzAuNyUyQzAuMyU1RC5zbW9vdGgoMSkpJTBBJTIwJTIwLmNvbG9yKDAuMiUyQzAuNCUyQzAuNiklMEElMjAlMjAuc2Nyb2xsWSgtMC4zNSklMEElMjAlMjAuc2Nyb2xsWCgoKSUzRCUzRU1hdGguc2luKHRpbWUqMC40MSkqLTEpKSUwQS5hZGQoJTBBJTIwJTIwJTIwJTIwJTIwJTIwc3JjKG8wKS5zaGlmdCgwLjAwMSUyQzAuMDElMkMwLjAwMSklMEElMjAlMjAlMjAlMjAlMjAlMjAuc2Nyb2xsWCglNUIwLjA1JTJDLTAuMDUlNUQuZmFzdCgwLjEpLnNtb290aCgxKSklMEElMjAlMjAlMjAlMjAlMjAlMjAuc2NhbGUoJTVCMS4wNSUyQzAuOSU1RC5mYXN0KDAuMykuc21vb3RoKDEpJTJDJTVCMS4wNSUyQzAuOSUyQzElNUQuZmFzdCgwLjI5KS5zbW9vdGgoMSkpJTBBJTIwJTIwJTIwJTIwJTIwJTIwJTJDMC44NSklMEEubW9kdWxhdGUodm9yb25vaSgxMCUyQzIlMkMyKSklMEEub3V0KCk=" }, { "sketch_id": "malitzin_0", "code": "JTJGJTJGQ05EU0QlMEElMkYlMkZodHRwJTNBJTJGJTJGbWFsaXR6aW5jb3J0ZXMubmV0JTJGJTBBJTJGJTJGJTIwc2FuZCUyMHNwaXJhbHMlMEElMEFvc2MoMyUyQyUyMDAuMDElMkMlMjAwLjQpJTBBLmNvbG9yKDEuMiUyQzEuMiUyQzEuMyklMEEuc2F0dXJhdGUoMC40KSUwQS5tb2R1bGF0ZVJlcGVhdChvc2MoMiklMkMxJTJDJTIwMiUyQyUyMDQlMkMlMjAzKSUwQS5tb2R1bGF0ZUthbGVpZChvc2MoMTIlMkMwLjA1JTJDMCklMkMxKSUwQS5sdW1hJTIwKDAuNCklMEEucm90YXRlKDQlMkMlMjAwLjElMkMwKSUwQS5tb2R1bGF0ZShvMCUyQyUyMCgpJTIwJTNEJTNFJTIwbW91c2UueSUyMCowLjAwMDIlMjApJTBBLnNjYWxlKDEpLmRpZmYobzEpJTBBLm91dChvMCk=" }, { "sketch_id": "malitzin_1", "code": "JTJGJTJGQ05EU0QlMEElMkYlMkZodHRwJTNBJTJGJTJGbWFsaXR6aW5jb3J0ZXMubmV0JTJGJTBBJTJGJTJGYW1lYmElMEElMEFvc2MoMTUlMkMlMjAwLjAxJTJDJTIwMC4xKS5tdWx0KG9zYygxJTJDJTIwLTAuMSkubW9kdWxhdGUob3NjKDIpLnJvdGF0ZSg0JTJDMSklMkMlMjAyMCkpJTBBLmNvbG9yKDAlMkMyLjQlMkM1KSUwQS5zYXR1cmF0ZSgwLjQpJTBBLmx1bWEoMSUyQzAuMSUyQyUyMCg2JTJDJTIwKCklM0QlM0UlMjAxJTIwJTJCJTIwYS5mZnQlNUIzJTVEKSklMEEuc2NhbGUoMC43JTJDJTIwKCklM0QlM0UlMjAwLjclMjAlMkIlMjBhLmZmdCU1QjMlNUQpJTBBLmRpZmYobzApJTJGJTJGJTIwbzAlMEEub3V0KG8wKSUyRiUyRiUyMG8x" }, { "sketch_id": "malitzin_2", "code": "JTJGJTJGQ05EU0QlMEElMkYlMkZodHRwJTNBJTJGJTJGbWFsaXR6aW5jb3J0ZXMubmV0JTJGJTBBJTJGJTJGY3JhenklMjBzcXVhcmVzJTBBJTBBc2hhcGUoNCUyQyUyMCgwLjAxJTJDJTIwKCklM0QlM0UlMjAwLjIlMjAlMkIlMjBhLmZmdCU1QjIlNUQpJTJDMSklMEEubXVsdChvc2MoMSUyQyUyMDEpLm1vZHVsYXRlKG9zYyg1KS5yb3RhdGUoMS40JTJDMSklMkMzKSklMEEuY29sb3IoMSUyQzIlMkM0KSUwQS5zYXR1cmF0ZSgwLjIpJTBBLmx1bWEoMS4yJTJDMC4wNSUyQyUyMCg1JTJDJTIwKCklM0QlM0UlMjAyJTIwJTJCJTIwYS5mZnQlNUIzJTVEKSklMEEuc2NhbGUoMC42JTJDJTIwKCklM0QlM0UlMjAwLjklMjAlMkIlMjBhLmZmdCU1QjMlNUQpJTBBLmRpZmYobzApJTJGJTJGJTIwbzAlMEEub3V0KG8wKSUyRiUyRiUyMG8x" }, { "sketch_id": "khoparzi_0", "code": "JTJGJTJGJTIwSGFwcHklMjBNYW5kYWxhJTBBJTJGJTJGJTIwQnklMjBBYmhpbmF5JTIwS2hvcGFyemklMEElMkYlMkYlMjB0d2l0dGVyJTJGZ2l0aHViJTJGaW5zdGFncmFtJTNBJTIwJTQwa2hvcGFyemklMEF2b3Jvbm9pKDUlMkMtMC4xJTJDNSklMEEuYWRkKG9zYygxJTJDMCUyQzEpKS5rYWxlaWQoMjEpJTBBLnNjYWxlKDElMkMxJTJDMikuY29sb3JhbWEoKS5vdXQobzEpJTBBc3JjKG8xKS5tdWx0KHNyYyhzMCkubW9kdWxhdGVSb3RhdGUobzElMkMxMDApJTJDJTIwLTAuNSklMEElMjAlMjAub3V0KG8wKSUwQSUwQQ==" }, { "sketch_id": "khoparzi_1", "code": "JTJGJTJGJTIwUGVycGV0dWFsJTIwZWxldmF0b3IlMjBidXR0b25zJTBBJTJGJTJGJTIwQnklMjBLaG9wYXJ6aSUwQSUyRiUyRiUyMGh0dHAlM0ElMkYlMkZraG9wYXJ6aS5jb20lMEElMEFzaGFwZSgzKS5hZGQob3NjKDElMkMwLjUlMkMxKSUyQyUyMDEpJTBBJTA5LmFkZChvMSUyQyUyMCgpJTIwJTNEJTNFJTIwKE1hdGguc2luKHRpbWUlMkY0KSUyMColMjAwLjclMjAlMkIlMjAwLjEpKSUwQSUwOSUyRiUyRi5yZXBlYXQoNSklMEElMjAlMjAlMDkuc2NhbGUoKCklM0QlM0VNYXRoLnNpbih0aW1lJTIwJTJGJTIwMTYpKS5yb3RhdGUoMCUyQyUyMC0wLjEpJTBBJTA5Lm91dChvMSklMEElMEFzcmMobzEpJTBBJTIwJTIwLnJvdGF0ZSgwJTJDMC4xKSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "khoparzi_2", "code": "JTJGJTJGJTIwUmVhbGx5JTIwTG92ZSUwQSUyRiUyRiUyMGJ5JTIwQWJoaW5heSUyMEtob3BhcnppJTBBJTJGJTJGJTIwaHR0cCUzQSUyRiUyRmtob3BhcnppLmNvbSUwQW9zYygxMDAlMkMtMC4wMTI0NSUyQzEpLnBpeGVsYXRlKDUwKS5rYWxlaWQoKCklM0QlM0UoTWF0aC5zaW4odGltZSUyRjgpKjklMkIzKSkucm90YXRlKDAlMkMwLjEyNSklMEEubW9kdWxhdGVSb3RhdGUoc2hhcGUoMykuc2NhbGUoKCklM0QlM0UoTWF0aC5jb3ModGltZSkqMikpLnJvdGF0ZSgwJTJDLTAuMjUpKS5kaWZmKHNyYyhvMCkuYnJpZ2h0bmVzcygwLjMpKSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "khoparzi_3", "code": "JTJGJTJGJTIwQXFhdXRpYyUyMGJsdWJzJTBBJTJGJTJGJTIwQnklMjBLaG9wYXJ6aSUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGa2hvcGFyemkuY29tJTBBJTBBZ3JhZGllbnQoMC4yNSklMEEuYWRkKG5vaXNlKCklMkMlMjAoKSUzRCUzRU1hdGguY29zKHRpbWUpKSUwQS5tb2R1bGF0ZVJvdGF0ZShzcmMobzApLnJvdGF0ZSgwJTJDJTIwLTAuNTIpJTJDJTIwMC4yKS5tdWx0KHNoYXBlKDM2MCklMkMlMjAwLjgpJTBBLnJlcGVhdCgxMCUyQzUpLm11bHQoc2hhcGUoMzYwKS5zY2FsZSgoKSUzRCUzRU1hdGguc2luKHRpbWUpKSUyQyUyMDAuOCkucm90YXRlKDAlMkMlMjAwLjIpJTBBLmRpZmYoc3JjKG8wKS5yb3RhdGUoMCUyQyUyMC0wLjIpJTJDJTIwMC4yKSUwQS5vdXQoKQ==" }, { "sketch_id": "celeste_0", "code": "JTBBJTIwJTJGJTJGJTIwUHVlcnRhcyUyMElJJTBBJTJGJTJGJTIwcG9yJTIwQ2VsZXN0ZSUyMEJldGFuY3VyJTBBJTJGJTJGJTIwaHR0cHMlM0ElMkYlMkZnaXRodWIuY29tJTJGZXNzdGViYW4lMEElMEFvc2MoMTMlMkMwJTJDMSklMEElMjAlMjAua2FsZWlkKCklMEElMjAlMjAubWFzayhzaGFwZSg0JTJDMC4zJTJDMSkpJTBBJTIwJTIwLm1vZHVsYXRlUm90YXRlKHNoYXBlKDQlMkMwLjElMkMxKSklMEElMjAlMjAubW9kdWxhdGVSb3RhdGUoc2hhcGUoNCUyQzAuMSUyQzAuOSkpJTBBJTIwJTIwLm1vZHVsYXRlUm90YXRlKHNoYXBlKDQlMkMwLjElMkMwLjgpKSUwQSUyMCUyMC5zY2FsZSgwLjMpJTBBJTIwJTIwLmFkZChzaGFwZSg0JTJDMC4yJTJDMSkuY29sb3IoMC4zJTJDMSUyQzElMkMwLjUpKSUwQSUyMCUyMC5yb3RhdGUoKCklM0QlM0V0aW1lKSUwQSUyMCUyMC5vdXQoKQ==" }, { "sketch_id": "celeste_1", "code": "JTJGJTJGJTIwUHVlcnRhcyUyMElJSSUwQSUyRiUyRiUyMHBvciUyMENlbGVzdGUlMjBCZXRhbmN1ciUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmVzc3RlYmFuJTBBJTIwJTBBb3NjKDQwJTJDMC4yJTJDMSklMEElMjAlMjAubW9kdWxhdGVTY2FsZShvc2MoNDAlMkMwJTJDMSkua2FsZWlkKDgpKSUwQSUyMCUyMC5yZXBlYXQoMiUyQzQpJTBBJTIwJTIwLm1vZHVsYXRlKG8wJTJDMC4wNSklMEElMjAlMjAubW9kdWxhdGVLYWxlaWQoc2hhcGUoNCUyQzAuMSUyQzEpKSUwQSUyMCUyMC5vdXQobzAp" }, { "sketch_id": "celeste_2", "code": "JTBBJTIwJTJGJTJGJTIwUHVlcnRhcyUwQSUyRiUyRiUyMHBvciUyMENlbGVzdGUlMjBCZXRhbmN1ciUwQSUyRiUyRiUyMGh0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmVzc3RlYmFuJTBBJTBBb3NjKDEzJTJDMCUyQzEpJTBBJTIwJTIwLm1vZHVsYXRlKG9zYygyMSUyQzAuMjUlMkMwKSklMEElMjAlMjAubW9kdWxhdGVTY2FsZShvc2MoMzQpKSUwQSUyMCUyMC5tb2R1bGF0ZUthbGVpZChvc2MoNTUpJTJDMC4xJTJDMSklMEElMjAlMjAub3V0KCk=" }, { "sketch_id": "alexandre_0", "code": "JTJGJTJGJTIwJTIydGhlLXdhbGwlMjIlMEElMkYlMkYlMjBBbGV4YW5kcmUlMjBSYW5nZWwlMEElMkYlMkYlMjB3d3cuYWxleGFuZHJlcmFuZ2VsLmFydC5iciUyRmh5ZHJhLmh0bWwlMEElMEFzcGVlZCUzRC4wMjIyJTBBb3NjKDQ4JTJDLS4xJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguNzUpJTJDMCkuY29sb3IoMCUyQzAlMkMxKSUwQSUwQS5hZGQoJTBBJTIwJTIwJTIwJTIwb3NjKDI4JTJDLjElMkMwKS50aHJlc2goJTVCLjMlMkMuNyU1RC5mYXN0KC43NSklMkMwKS5yb3RhdGUoMy4xNCUyRjQpJTBBJTIwJTIwJTIwJTIwLmNvbG9yKDElMkMwJTJDMCklMEElMjAlMjAlMjAlMjAubW9kdWxhdGVTY2FsZSglMjBvc2MoNjQlMkMtLjAxJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguNzUpJTJDMCklMjApJTBBKSUwQS5kaWZmKCUwQSUyMCUyMCUyMCUyMG9zYygyOCUyQy4xJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguNSklMkMwKS5yb3RhdGUoMy4xNCUyRjIpJTBBJTIwJTIwJTIwJTIwLmNvbG9yKDElMkMwJTJDMSklMEElMjAlMjAlMjAlMjAubW9kdWxhdGVTY2FsZSglMjBvc2MoNjQlMkMtLjAxNSUyQzApLnRocmVzaCglNUIuMyUyQy43JTVELmZhc3QoLjUpJTJDMCklMjApJTBBKSUwQS5tb2R1bGF0ZVJvdGF0ZSglMjBvc2MoNTQlMkMtLjAwNSUyQzApLnRocmVzaCglNUIuMyUyQy43JTVELmZhc3QoLjI1KSUyQzApJTIwKSUwQS5tb2R1bGF0ZVNjYWxlKCUyMG9zYyg0NCUyQy0uMDIwJTJDMCkudGhyZXNoKCU1Qi4zJTJDLjclNUQuZmFzdCguMjUpJTJDMCklMjApJTBBLmNvbG9yYW1hKCUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjI3KSouMDEyMjIlMkI5Ljg5KSUwQS5zY2FsZSgyLjEyMiklMEElMEEub3V0KCk=" }, { "sketch_id": "alexandre_1", "code": "JTBBJTIwJTJGJTJGJTIwJTIyZXllJTIwb2YlMjB0aGUlMjBiZWhvbGRlciUyMiUwQSUyRiUyRiUyMEFsZXhhbmRyZSUyMFJhbmdlbCUwQSUyRiUyRiUyMHd3dy5hbGV4YW5kcmVyYW5nZWwuYXJ0LmJyJTJGaHlkcmEuaHRtbCUwQSUwQW5vaXNlKDYlMkMuMDUpJTBBLm11bHQoJTIwb3NjKDklMkMwJTJDJTIwKCklM0QlM0VNYXRoLnNpbih0aW1lJTJGMS41KSUyQjIlMjApJTIwKSUwQS5tdWx0KCUwQSUyMCUyMCUyMCUyMG5vaXNlKDklMkMuMDMpLmJyaWdodG5lc3MoMS4yKS5jb250cmFzdCgyKSUwQSUyMCUyMCUyMCUyMC5tdWx0KCUyMG9zYyg5JTJDMCUyQyUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjMpJTJCMTMlMjApJTIwKSUwQSklMEEuZGlmZiglMEElMjAlMjAlMjAlMjBub2lzZSgxNSUyQy4wNCkuYnJpZ2h0bmVzcyguMikuY29udHJhc3QoMS4zKSUwQSUyMCUyMCUyMCUyMC5tdWx0KCUyMG9zYyg5JTJDMCUyQyUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjUpJTJCMTMlMjApJTIwKSUwQSUyMCUyMCUyMCUyMC5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGMzMlMjApJTBBKSUwQS5zY2FsZSglMjAoKSUzRCUzRU1hdGguc2luKHRpbWUlMkY2LjIpKi4xMiUyQi4xNSUyMCklMEEubW9kdWxhdGVTY2FsZSglMEElMjAlMjAlMjAlMjBvc2MoMyUyQzAlMkMwKS5tdWx0KCUyMG9zYygzJTJDMCUyQzApLnJvdGF0ZSgzLjE0JTJGMiklMjApJTBBJTIwJTIwJTIwJTIwLnJvdGF0ZSglMjAoKSUzRCUzRXRpbWUlMkYyNSUyMCkuc2NhbGUoLjM5KS5zY2FsZSgxJTJDLjYlMkMxKS5pbnZlcnQoKSUwQSUyMCUyMCUyMCUyMCUyQyUyMCgpJTNEJTNFTWF0aC5zaW4odGltZSUyRjUuMykqMS41JTJCMyUyMCUyMCklMEEucm90YXRlKCUyMCgpJTNEJTNFdGltZSUyRjIyJTIwKSUwQS5tdWx0KCUyMHNoYXBlKDEwMCUyQy45JTJDLjAxKS5zY2FsZSgxJTJDLjYlMkMxKSUyMCklMEEub3V0KCk=" }, { "sketch_id": "alexandre_2", "code": "JTJGJTJGJTIwJTIyZWdnJTIwb2YlMjB0aGUlMjBwaG9lbml4JTIyJTBBJTJGJTJGJTIwQWxleGFuZHJlJTIwUmFuZ2VsJTBBJTJGJTJGJTIwd3d3LmFsZXhhbmRyZXJhbmdlbC5hcnQuYnIlMkZoeWRyYS5odG1sJTBBJTBBc3BlZWQlM0QxLjIlMEFzaGFwZSg5OSUyQy4xNSUyQy41KS5jb2xvcigwJTJDMSUyQzIpJTBBJTBBLmRpZmYoJTIwc2hhcGUoMjQwJTJDLjUlMkMwKS5zY3JvbGxYKC4wNSkucm90YXRlKCUyMCgpJTNEJTNFdGltZSUyRjEwJTIwKS5jb2xvcigxJTJDMCUyQy43NSklMjApJTBBLmRpZmYoJTIwc2hhcGUoOTklMkMuNCUyQy4wMDIpLnNjcm9sbFgoLjEwKS5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGMjAlMjApLmNvbG9yKDElMkMwJTJDLjc1KSUyMCklMEEuZGlmZiglMjBzaGFwZSg5OSUyQy4zJTJDLjAwMikuc2Nyb2xsWCguMTUpLnJvdGF0ZSglMjAoKSUzRCUzRXRpbWUlMkYzMCUyMCkuY29sb3IoMSUyQzAlMkMuNzUpJTIwKSUwQS5kaWZmKCUyMHNoYXBlKDk5JTJDLjIlMkMuMDAyKS5zY3JvbGxYKC4yMCkucm90YXRlKCUyMCgpJTNEJTNFdGltZSUyRjQwJTIwKS5jb2xvcigxJTJDMCUyQy43NSklMjApJTBBLmRpZmYoJTIwc2hhcGUoOTklMkMuMSUyQy4wMDIpLnNjcm9sbFgoLjI1KS5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGNTAlMjApLmNvbG9yKDElMkMwJTJDLjc1KSUyMCklMEElMEEubW9kdWxhdGVTY2FsZSglMEElMjAlMjBzaGFwZSgyNDAlMkMuNSUyQzApLnNjcm9sbFgoLjA1KS5yb3RhdGUoJTIwKCklM0QlM0V0aW1lJTJGMTAlMjApJTBBJTIwJTIwJTJDJTIwKCklM0QlM0UoTWF0aC5zaW4odGltZSUyRjMpKi4yKSUyQi4yJTIwKSUwQSUwQS5zY2FsZSgxLjYlMkMuNiUyQzEpJTBBLm91dCgp" },{ "sketch_id": "afalfl_0", "code": "JTJGJTJGZmlsZXQlMjBtaWdub24lMEElMkYlMkYlMjBBRkFMRkwlMEElMkYlMkYlMjBpbnN0YWdyYW0lMkZhX2ZfYWxmbCUyMCUwQSUwQW9zYygxMDAlMkMtMC4wMDE4JTJDMC4xNykuZGlmZihvc2MoMjAlMkMwLjAwMDA4KS5yb3RhdGUoTWF0aC5QSSUyRjAuMDAwMDMpKSUwQS5tb2R1bGF0ZVNjYWxlKG5vaXNlKDEuNSUyQzAuMTgpLm1vZHVsYXRlU2NhbGUob3NjKDEzKS5yb3RhdGUoKCklM0QlM0VNYXRoLnNpbih0aW1lJTJGMjIpKSklMkMzKSUwQS5jb2xvcigxMSUyQzAuNSUyQzAuNCUyQyUyMDAuOSUyQyUyMDAuMiUyQyUyMDAuMDExJTJDJTIwNSUyQyUyMDIyJTJDJTIwJTIwMC41JTJDJTIwLTEpLmNvbnRyYXN0KDEuNCklMEEuYWRkKHNyYyhvMCkubW9kdWxhdGUobzAlMkMuMDQpJTJDLjYlMkMlMjAuOSklMEElMjAlMjAlMkYlMkYucGl4ZWxhdGUoMC40JTJDJTIwMC4yJTJDJTIwMC4xKSUwQS5pbnZlcnQoKS5icmlnaHRuZXNzKDAuMDAwMyUyQyUyMDIpLmNvbnRyYXN0KCUyMDAuNSUyQyUyMDIlMkMlMjAwLjElMkMlMjAyKS5jb2xvcig0JTJDJTIwLTIlMkMlMjAwLjEpJTBBLm1vZHVsYXRlU2NhbGUob3NjKDIpJTJDLTAuMiUyQyUyMDIlMkMlMjAxJTJDJTIwMC4zKSUwQSUyMC5wb3N0ZXJpemUoMjAwKSUyMC5yb3RhdGUoMSUyQyUyMDAuMiUyQyUyMDAuMDElMkMlMjAwLjAwMSklMEElMjAuY29sb3IoMjIlMkMlMjAtMiUyQyUyMDAuNSUyQyUyMDAuNSUyQyUyMDAuMDAwMSUyQyUyMCUyMDAuMSUyQyUyMDAuMiUyQyUyMDgpLmNvbnRyYXN0KDAuMTglMkMlMjAwLjMlMkMlMjAwLjElMkMlMjAwLjIlMkMlMjAwLjAzJTJDJTIwMSklMjAuJTIwYnJpZ2h0bmVzcygwLjAwMDElMkMlMjAtMSUyQyUyMDEwKSUwQSUwOS5vdXQoKQ==" }, { "sketch_id": "eerie_ear_0", "code": "JTJGJTJGJTIwZWVfMiUyMC4lMjBNVUxUSVZFUlNFJTIwLiUyMHRpbWUlMjBhbmQlMjBmZWVkYmFjayUwQSUyRiUyRiUyMGVfZSUyMCUyRiUyRiUyMCU0MGVlcmllX2VhciUwQXBhdCUyMCUzRCUyMCgpJTNEJTNFJTBBc29saWQoKSUwQS5sYXllcihzb2xpZCgpLmRpZmYoJTBBJTIwJTIwb3NjKCh0aW1lJTJGMTYpJTIwKiUyMDElMkMlMjAodGltZSUyRjEwMDApJTIwKiUyMDAuMiUyMCUyMCklMEElMjAlMjAlMjAlMjAubXVsdChvc2MoKHRpbWUlMkY4KSUyMColMjAxJTJDJTIwKHRpbWUlMkYxMDA2KSUyMColMjAwLjIlMjAlMjApLnJvdGF0ZSgxLjU3KSklMEElMjAlMjAlMjAlMjAubW9kdWxhdGUoKHNoYXBlKDEwNiUyQzElMkMwLjA1KSkpJTBBJTIwJTIwJTIwJTIwLm11bHQoc2hhcGUoMTA2JTJDMSUyQzAuMDUpKSUwQSUyMCUyMCkpJTBBJTIwJTIwLm1vZHVsYXRlU2NhbGUob3NjKDIlMkMwLjEyNSklMkMwLjEyNSklMEElMkYlMkYlMEFzb2xpZCgpJTBBLmxheWVyKHNvbGlkKDElMkMxJTJDMSklMEElMjAlMjAubXVsdChwYXQoKSUwQSUyMCUyMC5kaWZmKHNyYyhvMCkuc2NhbGUoMC4yKS5tdWx0KHNvbGlkKCklMkMlNUIwLjclMkMwLjYlMkMwLjQlMkMwLjYlNUQpLmthbGVpZCgxLjAxKS5zYXR1cmF0ZSgwLjMpKSUwQSklMEEubGF5ZXIoc29saWQoMSUyQzElMkMxKSUwQSUyMCUyMCUyMCUyMC5tYXNrKCUwQSUyMCUyMCUyMCUyMCUyMCUyMG5vaXNlKDIlMkMwLjA1KSUwQSUyMCUyMCUyMCUyMCUyMCUyMC5pbnZlcnQoKS5jb2xvcmFtYSgyKS5wb3N0ZXJpemUoOCUyQzQpLmx1bWEoMC4yNSkudGhyZXNoKDAuNSklMEElMjAlMjAlMjAlMjAlMjAlMjAubW9kdWxhdGVSb3RhdGUob3NjKDElMkMwLjUpKSUwQSUyMCUyMCUyMCUyMCklMEElMjAlMjAlMjAlMjAubXVsdChncmFkaWVudCgwLjUpLmthbGVpZCgxKS5jb2xvcmFtYSgyKS5zYXR1cmF0ZSgxLjEpLmNvbnRyYXN0KDEuNikubXVsdChzb2xpZCgpJTJDMC40NSkpJTBBJTIwJTIwKSklMEElMjAlMjAub3V0KCklMEElMkYlMkYlMEFzcGVlZCUzRCUyMDAuNSUwQQ==" }, { "sketch_id": "eerie_ear_1", "code": "JTJGJTJGJTIwZWVfMyUyMCUyRiUyRkxJTkVTJTBBJTJGJTJGJTIwZV9lJTIwJTJGJTJGJTIwJTQwZWVyaWVfZWFyJTBBJTJGJTJGJTBBJTJGJTJGYmFzZWQlMjBvbiUwQSUyRiUyRiU0MG5hb3RvX2hpZWRhJTBBJTJGJTJGaHR0cHMlM0ElMkYlMkZuYW90b2hpZWRhLmNvbSUyRmJsb2clMkZoeWRyYS1ib29rJTJGJTBBJTJGJTJGJTBBbiUyMCUzRCUyMDglMEFhJTIwJTNEJTIwKCklMjAlM0QlM0UlMjBzaGFwZSg0JTJDMC4yNSUyQzAuMDA5KS5yb3RhdGUoKCklM0QlM0V0aW1lJTJGLTQwKS5yZXBlYXQobiUyQ24pJTBBYSgpLmFkZChhKCkuc2Nyb2xsWCgwLjUlMkZuKS5zY3JvbGxZKDAuNSUyRm4pJTJDMSkubW9kdWxhdGUobzElMkMwLjEpLm1vZHVsYXRlKHNyYyhvMSkuY29sb3IoMTAlMkMxMCkuYWRkKHNvbGlkKC0xNCUyQy0xNCkpLnJvdGF0ZSgoKSUzRCUzRXRpbWUlMkY0MCklMkMwLjAwNSkuYWRkKHNyYyhvMSkuc2Nyb2xsWSgwLjAxMiUyQzAuMDIpJTJDMC41KS5vdXQobzEpJTBBc3JjKG8xKS5jb2xvcmFtYSgxLjIpLnBvc3Rlcml6ZSg0KS5zYXR1cmF0ZSgwLjcpLmNvbnRyYXN0KDYpLm11bHQoc29saWQoKSUyQzAuMTUpLm91dChvMCklMEElMEElMEE=" }, { "sketch_id": "eerie_ear_2", "code": "JTJGJTJGZWVfNSUyMC4lMjBGVUdJVElWRSUyMEdFT01FVFJZJTIwVkhTJTIwLiUyMGF1ZGlvcmVhY3RpdmUlMjBzaGFwZXMlMjBhbmQlMjBncmFkaWVudHMlMEElMkYlMkYlMjBlX2UlMjAlMkYlMkYlMjAlNDBlZXJpZV9lYXIlMEElMkYlMkYlMEFzJTNEJTIwKCklM0QlM0UlMEElMjAlMjBzaGFwZSg0KSUwQS5zY3JvbGxYKCU1Qi0wLjUlMkMtMC4yJTJDMC4zJTJDLTAuMSUyQy0wLjElNUQuc21vb3RoKDAuMSkuZmFzdCgwLjMpKSUwQS5zY3JvbGxZKCU1QjAuMjUlMkMtMC4yJTJDMC4zJTJDLTAuMSUyQzAuMiU1RC5zbW9vdGgoMC45KS5mYXN0KDAuMTUpKSUwQSUyRiUyRiUwQXNvbGlkKCklMEEuYWRkKGdyYWRpZW50KDMlMkMwLjA1KS5yb3RhdGUoMC4wNSUyQy0wLjIpLnBvc3Rlcml6ZSgyKS5jb250cmFzdCgwLjYpJTJDJTVCMSUyQzAlMkMxJTJDMC41JTJDMCUyQzAuNiU1RC5zbW9vdGgoMC45KSklMEEuYWRkKHMoKSklMEEubXVsdChzKCkuc2NhbGUoMC44KS5zY3JvbGxYKDAuMDEpLnNjcm9sbFkoLTAuMDEpLnJvdGF0ZSgwLjIlMkMwLjA2KS5hZGQoZ3JhZGllbnQoMykuY29udHJhc3QoMC42KSUyQyU1QjElMkMwJTJDMSUyQzAuNSU1RC5zbW9vdGgoMC45KSUyQzAuNSkubXVsdChzcmMobzApLnNjYWxlKDAuOTgpJTJDKCklM0QlM0VhLmZmdCU1QjAlNUQqOSklMEElMjAlMjAlMjAlMjAlMjApJTBBLmRpZmYocygpLm1vZHVsYXRlKHNoYXBlKDUwMCkpLnNjYWxlKCU1QjEuNyUyQzEuMiU1RC5zbW9vdGgoMC45KS5mYXN0KDAuMDUpKSklMEEuYWRkKGdyYWRpZW50KDIpLmludmVydCgpJTJDKCklM0QlM0VhLmZmdCU1QjIlNUQpJTBBLm11bHQoZ3JhZGllbnQoKCklM0QlM0VhLmZmdCU1QjMlNUQqOCkpJTBBLmJsZW5kKHNyYygobzApJTJDKCklM0QlM0VhLmZmdCU1QjElNUQqNDApKSUwQS5hZGQodm9yb25vaSgoKSUzRCUzRWEuZmZ0JTVCMSU1RCUyQygpJTNEJTNFYS5mZnQlNUIzJTVEJTJDKCklM0QlM0VhLmZmdCU1QjAlNUQpLnRocmVzaCgwLjcpLnBvc3Rlcml6ZSgyJTJDNCkubHVtYSgwLjkpLnNjcm9sbFkoMSUyQygpJTNEJTNFYS5mZnQlNUIwJTVEJTJGMzApLmNvbG9yYW1hKDMpLnRocmVzaCgoKSUzRCUzRWEuZmZ0JTVCMSU1RCkuc2NhbGUoKCklM0QlM0VhLmZmdCU1QjMlNUQqMiklMkMoKSUzRCUzRWEuZmZ0JTVCMCU1RCUyRjIpJTBBJTIwJTIwLm91dCgpJTBBJTJGJTJGJTBBc3BlZWQlM0QlMjAxJTBBJTBBYS5zZXRTbW9vdGgoMC45Nik=" }, { "sketch_id": "eerie_ear_3", "code": "JTJGJTJGJTIwZWVfMSUyMC4lMjBFWUUlMjBJTiUyMFRIRSUyMFNLWSUwQSUyRiUyRmV4YW1wbGUlMjBvZiUyMG1hc2slMjBhbmQlMjBmdW5jdGlvbiUyMG1vZHVsYXRpb24lMEElMkYlMkYlMjBlX2UlMjAlMkYlMkYlMjAlNDBlZXJpZV9lYXIlMEFub2lzZSgxOCklMEElMjAlMjAuY29sb3JhbWEoMSklMEElMjAlMjAucG9zdGVyaXplKDIpJTBBJTIwJTIwLmthbGVpZCg1MCklMEElMjAlMjAubWFzayglMEElMjAlMjAlMjAlMjBzaGFwZSgyNSUyQyUyMDAuMjUpLm1vZHVsYXRlU2NhbGUoJTBBJTIwJTIwJTIwJTIwJTIwJTIwbm9pc2UoNDAwLjUlMkMlMjAwLjUpJTBBJTIwJTIwJTIwJTIwKSUwQSUyMCUyMCklMEElMjAlMjAubWFzayhzaGFwZSg0MDAlMkMlMjAxJTJDJTIwMi4xMjUpKSUwQSUyMCUyMC5tb2R1bGF0ZVNjYWxlKG9zYyg2JTJDJTIwMC4xMjUlMkMlMjAwLjA1KS5rYWxlaWQoNTApKSUwQSUyMCUyMC5tdWx0KG9zYygyMCUyQyUyMDAuMDUlMkMlMjAyLjQpLmthbGVpZCg1MCklMkMlMjAwLjI1KSUwQSUyMCUyMC5zY2FsZSgxLjc1JTJDJTIwMC42NSUyQyUyMDAuNSklMEElMjAlMjAubW9kdWxhdGUobm9pc2UoMC41KSklMEElMjAlMjAuc2F0dXJhdGUoNiklMEElMjAlMjAucG9zdGVyaXplKDQlMkMlMjAwLjIpJTBBJTIwJTIwLnNjYWxlKDEuNSklMEElMjAlMjAub3V0KCklM0IlMEE=" } ] },{}],7:[function(require,module,exports){ const request = require('superagent') const examples = require('./examples.json') const sketches = [] class Gallery { constructor (callback) { this.sketches = [] this.examples = [] this.current = null this.code = null this.exampleIndex = null // request.get('/sketches').end((err, res) => { // console.log('got sketches', res.text, err) // if(err) { // console.log('err getting sketches', err) // } else { // this.sketches = JSON.parse(res.text) // } this.examples = examples this.setSketchFromURL(callback) // callback(this.code, this.foundSketch) // }) window.addEventListener('popstate', (event) => { this.setSketchFromURL(callback) console.log("location: " + document.location + ", state: " + JSON.stringify(event.state)); }); this.setRandomSketch = this.setRandomSketch.bind(this) } clear() { this.current = null this.code = null //this.exampleIndex = null let newurl = window.location.protocol + '//' + window.location.host + window.location.pathname window.history.pushState({ path: newurl }, '', newurl) this.url = newurl } setSketchFromURL(callback) { hush() render(o0) let searchParams = new URLSearchParams(window.location.search) let base64Code = searchParams.get('code') // if(!base64Code) base64Code = searchParams.get('id') // backwards compatibility with earlier form of naming. id is now called code let sketch_id = searchParams.get('sketch_id') let code = '' console.log("id", sketch_id, "code", base64Code) // boolean to determine whether a sketch was found based on the URL, either through looking through the database or rendering the code this.foundSketch = false // if contains a sketch id, set sketch from id if(sketch_id) { var sketch = this.getExampleById(sketch_id) if(sketch) { console.log('found', sketch) this.setSketch(sketch) callback(this.code, false) } else { request .get('/sketchById') .query({sketch_id: sketch_id}) .end((err, res) => { console.log('got sketches', res.text, err) if(err) { console.log('err getting sketches', err) this.setSketchFromCode(base64Code, callback) } else { this.sketches = JSON.parse(res.text) if(this.sketches.length > 0) { this.setSketch(this.sketches[0]) //this.code = this.decodeBase64(this.sketches[0].code) this.foundSketch = true callback(this.code, this.foundSketch) } else { this.setSketchFromCode(base64Code, callback) } } }) } } else { this.setSketchFromCode(base64Code, callback) } // // // console.log('found ', sketch) // // if(sketch) { // // this.setSketch(sketch) // // this. = true0 // // } else if (base64Code){ // // this.code = this.decodeBase64(base64Code) // // this.foundSketch = true // // } else { // // console.log('id not found', sketch_id) // // this.setRandomSketch() // // } // // // // backwards combaitbility with earlier shareable URLS // } else { // // if (base64Code) { // this.code = this.decodeBase64(base64Code) // this.foundSketch = true // } else { // this.setRandomSketch() // } // } } setSketchFromCode(base64Code, callback){ if (base64Code) { this.code = this.decodeBase64(base64Code) this.foundSketch = true } else { this.setRandomSketch() } callback(this.code, this.foundSketch) } saveImage() { } setToURL(params){ // console.log(base64) console.log('params', params) // keep code in url for backwards compatibility / compatibility between local and public versions var url_params if(params.sketch_id) { url_params = `sketch_id=${params.sketch_id}` } else { url_params = `sketch_id=${params.sketch_id}&code=${params.code}` } // } else { // url_params = params.map( (param, index) => `${param.label}=${param.value}`).join('&') // } // console.log('url params', url_params) let newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + url_params // window.location.href = newurl window.history.replaceState({ path: newurl }, '', newurl) this.url = newurl } encodeBase64(text) { return btoa(encodeURIComponent(text)) } decodeBase64(base64Code) { return decodeURIComponent(atob(base64Code)) } setSketch(sketch) { this.code = this.decodeBase64(sketch.code) this.current = sketch // this.setToURL('sketch_id', sketch._id) // let params = Object.keys(sketch).map( (key) => { // return {label: key, value: sketch[key]} // }) this.setToURL(sketch) } setRandomSketch() { // if there are sketches, set code from sketch, otherwise generate random console.log("examples length", this.examples, this.exampleIndex) if(this.examples.length > 0) { let index // if(this.exampleIndex === null) { index = Math.floor(Math.random() * this.examples.length) while (index === this.exampleIndex) { index = Math.floor(Math.random() * this.examples.length) } // } else { // index = this.exampleIndex +1 // if(index >= this.examples.length) index = 0 // } this.exampleIndex = index // console.log('example is', this.examples[rand]) this.setSketch(this.examples[index]) } else { var startString = 'osc(' + 2 + Math.floor(Math.pow(10, Math.random() * 2)) + ')' startString += '.color(' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2) + ',' + Math.random().toFixed(2)+ ')' startString += '.rotate(' + Math.random().toFixed(2) + ')' startString += '.out(o0)' this.code = startString } } // shares via twitter shareSketch(code, hydra, name) { this.saveSketch(code, () => { console.log("URL is", this.url, 'sketch is', this.current) hydra.getScreenImage((img) => { request .post('/image') .attach('previewImage', img) .query({ url: this.url, sketch_id: this.current.sketch_id, name: name }) // .send({ // code: base64 // }) // .query(query) .end((err, res) => { if(err) { console.log('error postingimage', err) } else { console.log('image response', res.text) // self.setToURL([ { label: 'sketch_id', value: res.text}, {label: 'code', value: base64} ]) } }) // var oReq = new XMLHttpRequest(); // oReq.open("POST", "https://localhost:8000/image", true); // oReq.onload = function (oEvent) { // // Uploaded. // console.log("uploaded", oEvent) // }; // oReq.send(img); // console.log('got image', img) }) }) } saveSketch(code, callback) { let self = this //console.log('saving in gallery', code) let base64 = this.encodeBase64(code) // console.log('code is', base64) let query = { code: base64, parent: this.current ? this.current.sketch_id : null } console.log('saving in gallery', query) request .post('/sketch') // .send({ // code: base64 // }) .query(query) .end((err, res) => { if(err) { console.log('error posting sketch', err) if(callback) callback(err) } else { console.log('response', res.text) // self.setToURL([ { label: 'sketch_id', value: res.text}, {label: 'code', value: base64} ]) self.setSketch({ sketch_id: res.text, code: base64 }) if(callback) callback(null) } }) } saveLocally(code) { let base64 = this.encodeBase64(code) // keep code in url for backwards compatibility / compatibility between local and public versions var url_params = `code=${base64}` // } else { // url_params = params.map( (param, index) => `${param.label}=${param.value}`).join('&') // } console.log('url params', url_params) let newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?' + url_params window.history.pushState({ path: newurl }, '', newurl) this.url = newurl } getExampleById(id) { console.log('looking for', id, this.examples, this.sketches) var sketches = this.examples.filter((sketch) => sketch.sketch_id === id) if(sketches.length <= 0) sketches = this.sketches.filter((sketch) => sketch.sketch_id === id) return sketches[0] } } module.exports = Gallery },{"./examples.json":6,"superagent":134}],8:[function(require,module,exports){ var logElement module.exports = { init: () => { logElement = document.createElement('div') logElement.className = "console cm-s-tomorrow-night-eighties" document.body.appendChild(logElement) }, log: (msg, className = "") => { if(logElement) logElement.innerHTML =` >> ${msg} ` }, hide: () => { if(logElement) logElement.style.display = 'none' }, show: () => { if(logElement) logElement.style.display = 'block' }, toggle: () => { if(logElement.style.display == 'none') { logElement.style.display = 'block' } else { logElement.style.display = 'none' } } } },{}],9:[function(require,module,exports){ const repl = require('./repl.js') const prettier = require("prettier/standalone") const parserBabel = require("prettier/parser-babel"); class Menu { constructor (obj) { this.sketches = obj.sketches this.editor = obj.editor this.hydra = obj.hydra // variables related to popup window this.closeButton = document.getElementById("close-icon") this.clearButton = document.getElementById("clear-icon") this.shareButton = document.getElementById("share-icon") this.shuffleButton = document.getElementById("shuffle-icon") this.mutatorButton = document.getElementById("mutator-icon") this.runButton = document.getElementById("run-icon") this.editorText = document.getElementsByClassName('CodeMirror-scroll')[0] this.runButton.onclick = this.runAll.bind(this) this.shuffleButton.onclick = this.shuffleSketches.bind(this) this.shareButton.onclick = this.shareSketch.bind(this) this.clearButton.onclick = this.clearAll.bind(this) this.closeButton.onclick = () => { if(!this.isClosed) { this.closeModal() } else { this.openModal() } } this.mutatorButton.onclick = this.mutateSketch.bind(this); this.isClosed = false this.closeModal() } runAll() { repl.eval(this.editor.getValue(), (string, err) => { // console.log('eval', err) this.editor.flashCode() if(!err) this.sketches.saveLocally(this.editor.getValue()) }) } shuffleSketches() { this.clearAll() this.sketches.setRandomSketch() this.editor.setValue(this.sketches.code) repl.eval(this.editor.getValue()) } formatCode() { this.editor.setValue(prettier.format(this.editor.getValue(), { parser: "babel", plugins: [parserBabel], printWidth: 50 })) } shareSketch() { repl.eval(this.editor.getValue(), (code, error) => { console.log('evaluated', code, error) if(!error){ this.showConfirmation( (name) => { this.sketches.shareSketch(code, this.hydra, name) }, () => this.hideConfirmation() ) } }) } showConfirmation(successCallback, terminateCallback) { var c = prompt("Pressing OK will share this sketch to \nhttps://twitter.com/hydra_patterns.\n\nInclude your name or twitter handle (optional):") console.log('confirm value', c) if (c !== null) { successCallback(c) } else { terminateCallback() } } hideConfirmation() { } clearAll() { hush() speed = 1 this.sketches.clear() this.editor.clear() //@todo: add clear/reset function to hydra } closeModal () { document.getElementById("info-container").className = "hidden" this.closeButton.className = "fas fa-question-circle icon" this.shareButton.classList.remove('hidden') this.clearButton.classList.remove('hidden') this.mutatorButton.classList.remove('hidden'); this.runButton.classList.remove('hidden'); this.editorText.style.opacity = 1 this.isClosed = true } openModal () { document.getElementById("info-container").className = "" this.closeButton.className = "fas fa-times icon" this.shareButton.classList.add('hidden') this.clearButton.classList.add('hidden') this.mutatorButton.classList.add('hidden'); this.runButton.classList.add('hidden'); this.editorText.style.opacity = 0.0 this.isClosed = false } mutateSketch(evt) { if (evt.shiftKey) { this.editor.mutator.doUndo(); } else { this.editor.mutator.mutate({reroll: false}); } } } module.exports = Menu },{"./repl.js":12,"prettier/parser-babel":90,"prettier/standalone":91}],10:[function(require,module,exports){ //'use babel' const p5lib = require('p5') require('p5/lib/addons/p5.dom') class P5 extends p5lib{ constructor ({ width = window.innerWidth, height = window.innerHeight, mode = 'P2D' } = {}) { //console.log('createing canvas', width, height, window.innerWidth, window.innerHeight) super(( p ) => { p.setup = () => { p.createCanvas(width, height, p[mode]) } // p.setup = () => { p.createCanvas() } p.draw = () => { } }, 'hydra-ui') this.width = width this.height = height this.mode = mode this.canvas.style.position = "absolute" this.canvas.style.top = "0px" this.canvas.style.left = "0px" this.canvas.style.zIndex = -1 // console.log('p5', this) // return this.p5 } show() { this.canvas.style.zIndex = -1 } hide() { this.canvas.style.zIndex = -10 } // p5 clear function not covering canvas clear() { this.drawingContext.clearRect(0, 0, this.canvas.width, this.canvas.height) } } module.exports = P5 },{"p5":86,"p5/lib/addons/p5.dom":85}],11:[function(require,module,exports){ /* globals sessionStorage */ // Extends rtc-patch-bay to include support for nicknames and persistent session storage var PatchBay = require('./rtc-patch-bay.js') //var PatchBay = require('./../../../../rtc-patch-bay') var inherits = require('inherits') var PBLive = function () { this.session = {} // lookup tables for converting id to nickname this.nickFromId = {} this.idFromNick = {} this.loadFromStorage() } // inherits from PatchBay module inherits(PBLive, PatchBay) PBLive.prototype.init = function (stream, opts) { this.settings = { server: opts.server || 'https://patch-bay.glitch.me/', room: opts.room || 'patch-bay', stream: stream } this.makeGlobal = opts.makeGlobal || true this.setPageTitle = opts.setTitle || true if (this.session.id) this.settings.id = this.session.id PatchBay.call(this, this.settings) if (this.makeGlobal) window.pb = this this.on('ready', () => { if (!this.nick) { if (this.session.nick) { this.setName(this.session.nick) } else { this.session.id = this.id this.setName(this.session.id) } } console.log('connected to server ' + this.settings.server + ' with name ' + this.settings.id) }) // received a broadcast this.on('broadcast', this._processBroadcast.bind(this)) this.on('new peer', this.handleNewPeer.bind(this)) window.onbeforeunload = () => { this.session.id = window.pb.id this.session.nick = this.nick sessionStorage.setItem('pb', JSON.stringify(this.session)) } var self = this this.on('stream', function (id, stream) { console.log('got stream!', id, stream) const video = document.createElement('video') if ('srcObject' in video) { video.srcObject = stream } else { // Avoid using this in new browsers, as it is going away. video.src = window.URL.createObjectURL(stream) } // video.src = window.URL.createObjectURL(stream) video.addEventListener('loadedmetadata', () => { // console.log("loaded meta22") video.play() self.video = video self.emit('got video', self.nickFromId[id], video) }) }) } PBLive.prototype.loadFromStorage = function () { if (sessionStorage.getItem('pb') !== null) { this.session = JSON.parse(sessionStorage.getItem('pb')) } } PBLive.prototype.initSource = function (nick, callback) { this.initConnectionFromId(this.idFromNick[nick], callback) // this.peers[this.idFromNick[nick]].streamCallback = callback } // default nickname is just peer id. // to do: save nickname information between sessions PBLive.prototype.handleNewPeer = function (peer) { // console.log("new peer", peer) this.nickFromId[peer] = peer this.idFromNick[peer] = peer // console.log("THIS IS THE PEER", peer) // to do: only send to new peer, not to all if (this.nick) { this.broadcast({ type: 'update-nick', id: this.id, nick: this.nick }) } } PBLive.prototype.list = function () { var l = Object.keys(this.idFromNick) console.log(l) return Object.keys(this.idFromNick) } // choose an identifying name PBLive.prototype.setName = function (nick) { this.broadcast({ type: 'update-nick', id: this.id, nick: nick, previous: this.nick }) this.nick = nick if (this.setPageTitle) document.title = nick } PBLive.prototype._processBroadcast = function (data) { if (data.type === 'update-nick') { if (data.previous !== data.nick) { delete this.idFromNick[this.nickFromId[data.id]] this.nickFromId[data.id] = data.nick this.idFromNick[data.nick] = data.id if (data.previous) { console.log(data.previous + ' changed to ' + data.nick) } else { console.log('connected to ' + data.nick) } } } } // PBExtended.prototype. module.exports = PBLive },{"./rtc-patch-bay.js":13,"inherits":79}],12:[function(require,module,exports){ const log = require('./log.js').log module.exports = { eval: (arg, callback) => { var self = this var jsString = arg var isError = false try { eval(jsString) // log(jsString) log('') } catch (e) { isError = true console.log("logging", e) // var err = e.constructor('Error in Evaled Script: ' + e.message); // console.log(err.lineNumber) log(e.message, "log-error") //console.log('ERROR', JSON.stringify(e)) } // console.log('callback is', callback) if(callback) callback(jsString, isError) } } },{"./log.js":8}],13:[function(require,module,exports){ // Module for handling connections to multiple peers. var io = require('socket.io-client') var SimplePeer = require('simple-peer') var extend = Object.assign var events = require('events').EventEmitter var inherits = require('inherits') const shortid = require('shortid') var PatchBay = function (options) { // connect to websocket signalling server. To DO: error validation this.signaller = io(options.server) //assign unique id to this peer, or use id passed in this.id = options.id || shortid.generate() this.stream = options.stream || null //options to be sent to simple peer this._peerOptions = options.peerOptions || {} this._room = options.room this.settings['shareMediaWhenRequested'] = true this.settings['shareMediaWhenInitiating'] = false this.settings['requestMediaWhenInitiating'] = true this.settings['autoconnect'] = false //object containing ALL peers in room this.peers = {} //object containing peers connected via webrtc this.rtcPeers = {} // Handle events from signalling server this.signaller.on('ready', this._readyForSignalling.bind(this)) // this.signaller.on('peers', ) // this.signaller.on('signal', this._handleSignal.bind(this)) this.signaller.on('message', this._handleMessage.bind(this)) // Received message via websockets to all peers in room this.signaller.on('broadcast', this._receivedBroadcast.bind(this)) // emit 'join' event to signalling server this.signaller.emit('join', this._room, {uuid: this.id}) this.signaller.on('new peer', this._newPeer.bind(this)) } // inherits from events module in order to trigger events inherits(PatchBay, events) // send data to all connected peers via data channels PatchBay.prototype.sendToAll = function (data) { Object.keys(this.rtcPeers).forEach(function (id) { this.rtcPeers[id].send(data) }, this) } // sends to peer specified b PatchBay.prototype.sendToPeer = function (peerId, data) { if (peerId in this.rtcPeers) { this.rtcPeers[peerId].send(data) } } PatchBay.prototype.reinitAll = function(){ Object.keys(this.rtcPeers).forEach(function (id) { this.reinitPeer(id) }.bind(this)) // this._connectToPeers.bind(this) } PatchBay.prototype.initRtcPeer = function(id, opts) { this.emit('new peer', {id: id}) var newOptions = opts console.log() if(this.iceServers) { opts['config'] = { iceServers: this.iceServers } } if(opts.initiator === true) { if (this.stream != null) { if(this.settings.shareMediaWhenInitiating === true){ newOptions.stream = this.stream } } if(this.settings.requestMediaWhenInitiating === true){ newOptions.offerConstraints = { offerToReceiveVideo: true, offerToReceiveAudio: true } } } else { if(this.settings.shareMediaWhenRequested === true){ if (this.stream != null) { newOptions.stream = this.stream } } } var options = extend(this._peerOptions, newOptions) console.log("OPTIONS", options) this.rtcPeers[id] = new SimplePeer(options) this._attachPeerEvents(this.rtcPeers[id], id) } PatchBay.prototype.reinitRtcConnection = function(id, opts){ // Because renegotiation is not implemeneted in SimplePeer, reinitiate connection when configuration has changed this.rtcPeers[id]._destroy(null, function(e){ this.initRtcPeer(id, { stream: this.stream, initiator: true }) }.bind(this)) } // //new peer connected to signalling server PatchBay.prototype._newPeer = function (peer){ // this.connectedIds.push(peer) // Configuration for specified peer. // Individual configuration controls whether will receive media from // and/or send media to a specific peer. this.peers[peer] = { rtcPeer: null } this.emit('new peer', peer) // this.emit('updated peer list', this.connectedIds) } // // Once the new peer receives a list of connected peers from the server, // // creates new simple peer object for each connected peer. PatchBay.prototype._readyForSignalling = function ({ peers, servers }) { // console.log("received peer list", _t, this.peers) peers.forEach((peer) => { this._newPeer(peer) }) // if received ice and turn server information from signalling server, use in establishing if(servers) { this.iceServers = servers } // this.peers = peers this.emit('ready') } // Init connection to RECEIVE video PatchBay.prototype.initConnectionFromId = function(id, callback){ // console.log("initianing connection") if(id in this.rtcPeers){ console.log("Already connected to..", id, this.rtcPeers) //if this peer was originally only sending a stream (not receiving), recreate connecting but this time two-way if(this.rtcPeers[id].initiator===false){ this.reinitRtcConnection(id) } else { //already connected, do nothing } } else { this.initRtcPeer(id, { initiator: true }) } } // receive signal from signalling server, forward to simple-peer PatchBay.prototype._handleMessage = function (data) { // if there is currently no peer object for a peer id, that peer is initiating a new connection. if (data.type === 'signal'){ this._handleSignal(data) } else { this.emit('message', data) } } // receive signal from signalling server, forward to simple-peer PatchBay.prototype._handleSignal = function (data) { // if there is currently no peer object for a peer id, that peer is initiating a new connection. if (!this.rtcPeers[data.id]) { // this.emit('new peer', data) // var options = extend({stream: this.stream}, this._peerOptions) // this.rtcPeers[data.id] = new SimplePeer(options) // this._attachPeerEvents(this.rtcPeers[data.id], data.id) this.initRtcPeer(data.id, {initiator: false}) } this.rtcPeers[data.id].signal(data.message) } // sendToAll send through rtc connections, whereas broadcast // send through the signalling server. Useful in cases where // not all peers are connected via webrtc with other peers PatchBay.prototype._receivedBroadcast = function(data) { //console.log("RECEIVED BROADCAST", data) this.emit('broadcast', data) } //sends via signalling server PatchBay.prototype.broadcast = function (data) { this.signaller.emit('broadcast', data) } // handle events for each connected peer PatchBay.prototype._attachPeerEvents = function (p, _id) { p.on('signal', function (id, signal) { // console.log('signal', id, signal) // console.log("peer signal sending over sockets", id, signal) // this.signaller.emit('signal', {id: id, signal: signal}) this.signaller.emit('message', {id: id, message: signal, type: 'signal'}) }.bind(this, _id)) p.on('stream', function (id, stream) { this.rtcPeers[id].stream = stream // console.log('E: stream', id, stream) // console.log("received a stream", stream) this.emit('stream', id, stream) }.bind(this, _id)) p.on('connect', function (id) { // console.log("connected to ", id) this.emit('connect', id) }.bind(this, _id)) p.on('data', function (id, data) { // console.log('data', id) this.emit('data', {id: id, data: JSON.parse(data)}) }.bind(this, _id)) p.on('close', function (id) { //console.log('CLOSED') delete (this.rtcPeers[id]) this.emit('close', id) }.bind(this, _id)) p.on('error', function(e){ console.log("simple peer error", e) }) } PatchBay.prototype._destroy = function () { Object.values(this.rtcPeers).forEach( function (peer) { peer.destroy() }) this.signaller.close() } module.exports = PatchBay },{"events":26,"inherits":79,"shortid":109,"simple-peer":119,"socket.io-client":123}],14:[function(require,module,exports){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.acorn = {}))); }(this, (function (exports) { 'use strict'; // Reserved word lists for various dialects of the language var reservedWords = { 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5: "class enum extends super const export import", 6: "enum", strict: "implements interface let package private protected public static yield", strictBind: "eval arguments" }; // And the keywords var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; var keywords = { 5: ecma5AndLessKeywords, 6: ecma5AndLessKeywords + " const class extends export import super" }; var keywordRelationalOperator = /^in(stanceof)?$/; // ## Character categories // Big ugly regular expressions that match characters in the // whitespace, identifier, and identifier-start categories. These // are only applied when a character is found to actually have a // code point above 128. // Generated by `bin/generate-identifier-regex.js`. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08bd\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fef\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7b9\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab65\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; // These are a run-length and offset encoded representation of the // >0xffff code points that are a valid part of identifiers. The // offset starts at 0x10000, and each pair of numbers represents an // offset to the next range, and then a size of the range. They were // generated by bin/generate-identifier-regex.js // eslint-disable-next-line comma-spacing var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,190,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,54,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,86,26,230,43,117,63,32,0,257,0,11,39,8,0,22,0,12,39,3,3,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,68,12,0,67,12,65,1,31,6129,15,754,9486,286,82,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,4149,196,60,67,1213,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541]; // eslint-disable-next-line comma-spacing var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,280,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1016,45,17,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,2214,6,110,6,6,9,792487,239]; // This has a complexity linear to the value of the code. The // assumption is that looking up astral identifier characters is // rare. function isInAstralSet(code, set) { var pos = 0x10000; for (var i = 0; i < set.length; i += 2) { pos += set[i]; if (pos > code) { return false } pos += set[i + 1]; if (pos >= code) { return true } } } // Test whether a given character code starts an identifier. function isIdentifierStart(code, astral) { if (code < 65) { return code === 36 } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) } // Test whether a given character is part of an identifier. function isIdentifierChar(code, astral) { if (code < 48) { return code === 36 } if (code < 58) { return true } if (code < 65) { return false } if (code < 91) { return true } if (code < 97) { return code === 95 } if (code < 123) { return true } if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } if (astral === false) { return false } return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) } // ## Token types // The assignment of fine-grained, information-carrying type objects // allows the tokenizer to store the information it has about a // token in a way that is very cheap for the parser to look up. // All token type variables start with an underscore, to make them // easy to recognize. // The `beforeExpr` property is used to disambiguate between regular // expressions and divisions. It is set on all token types that can // be followed by an expression (thus, a slash after them would be a // regular expression). // // The `startsExpr` property is used to check if the token ends a // `yield` expression. It is set on all token types that either can // directly start an expression (like a quotation mark) or can // continue an expression (like the body of a string). // // `isLoop` marks a keyword as starting a loop, which is important // to know when parsing a label, in order to allow or disallow // continue jumps to that label. var TokenType = function TokenType(label, conf) { if ( conf === void 0 ) conf = {}; this.label = label; this.keyword = conf.keyword; this.beforeExpr = !!conf.beforeExpr; this.startsExpr = !!conf.startsExpr; this.isLoop = !!conf.isLoop; this.isAssign = !!conf.isAssign; this.prefix = !!conf.prefix; this.postfix = !!conf.postfix; this.binop = conf.binop || null; this.updateContext = null; }; function binop(name, prec) { return new TokenType(name, {beforeExpr: true, binop: prec}) } var beforeExpr = {beforeExpr: true}; var startsExpr = {startsExpr: true}; // Map keyword names to token types. var keywords$1 = {}; // Succinct definitions of keyword token types function kw(name, options) { if ( options === void 0 ) options = {}; options.keyword = name; return keywords$1[name] = new TokenType(name, options) } var types = { num: new TokenType("num", startsExpr), regexp: new TokenType("regexp", startsExpr), string: new TokenType("string", startsExpr), name: new TokenType("name", startsExpr), eof: new TokenType("eof"), // Punctuation token types. bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), bracketR: new TokenType("]"), braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), braceR: new TokenType("}"), parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), parenR: new TokenType(")"), comma: new TokenType(",", beforeExpr), semi: new TokenType(";", beforeExpr), colon: new TokenType(":", beforeExpr), dot: new TokenType("."), question: new TokenType("?", beforeExpr), arrow: new TokenType("=>", beforeExpr), template: new TokenType("template"), invalidTemplate: new TokenType("invalidTemplate"), ellipsis: new TokenType("...", beforeExpr), backQuote: new TokenType("`", startsExpr), dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), // Operators. These carry several kinds of properties to help the // parser use them properly (the presence of these properties is // what categorizes them as operators). // // `binop`, when present, specifies that this operator is a binary // operator, and will refer to its precedence. // // `prefix` and `postfix` mark the operator as a prefix or postfix // unary operator. // // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as // binary operators with a very low precedence, that should result // in AssignmentExpression nodes. eq: new TokenType("=", {beforeExpr: true, isAssign: true}), assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), logicalOR: binop("||", 1), logicalAND: binop("&&", 2), bitwiseOR: binop("|", 3), bitwiseXOR: binop("^", 4), bitwiseAND: binop("&", 5), equality: binop("==/!=/===/!==", 6), relational: binop("/<=/>=", 7), bitShift: binop("<>/>>>", 8), plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), modulo: binop("%", 10), star: binop("*", 10), slash: binop("/", 10), starstar: new TokenType("**", {beforeExpr: true}), // Keyword token types. _break: kw("break"), _case: kw("case", beforeExpr), _catch: kw("catch"), _continue: kw("continue"), _debugger: kw("debugger"), _default: kw("default", beforeExpr), _do: kw("do", {isLoop: true, beforeExpr: true}), _else: kw("else", beforeExpr), _finally: kw("finally"), _for: kw("for", {isLoop: true}), _function: kw("function", startsExpr), _if: kw("if"), _return: kw("return", beforeExpr), _switch: kw("switch"), _throw: kw("throw", beforeExpr), _try: kw("try"), _var: kw("var"), _const: kw("const"), _while: kw("while", {isLoop: true}), _with: kw("with"), _new: kw("new", {beforeExpr: true, startsExpr: true}), _this: kw("this", startsExpr), _super: kw("super", startsExpr), _class: kw("class", startsExpr), _extends: kw("extends", beforeExpr), _export: kw("export"), _import: kw("import"), _null: kw("null", startsExpr), _true: kw("true", startsExpr), _false: kw("false", startsExpr), _in: kw("in", {beforeExpr: true, binop: 7}), _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) }; // Matches a whole line break (where CRLF is considered a single // line break). Used to count lines. var lineBreak = /\r\n?|\n|\u2028|\u2029/; var lineBreakG = new RegExp(lineBreak.source, "g"); function isNewLine(code, ecma2019String) { return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) } var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; var ref = Object.prototype; var hasOwnProperty = ref.hasOwnProperty; var toString = ref.toString; // Checks if an object has a property. function has(obj, propName) { return hasOwnProperty.call(obj, propName) } var isArray = Array.isArray || (function (obj) { return ( toString.call(obj) === "[object Array]" ); }); function wordsRegexp(words) { return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") } // These are used when `options.locations` is on, for the // `startLoc` and `endLoc` properties. var Position = function Position(line, col) { this.line = line; this.column = col; }; Position.prototype.offset = function offset (n) { return new Position(this.line, this.column + n) }; var SourceLocation = function SourceLocation(p, start, end) { this.start = start; this.end = end; if (p.sourceFile !== null) { this.source = p.sourceFile; } }; // The `getLineInfo` function is mostly useful when the // `locations` option is off (for performance reasons) and you // want to find the line/column position for a given character // offset. `input` should be the code string that the offset refers // into. function getLineInfo(input, offset) { for (var line = 1, cur = 0;;) { lineBreakG.lastIndex = cur; var match = lineBreakG.exec(input); if (match && match.index < offset) { ++line; cur = match.index + match[0].length; } else { return new Position(line, offset - cur) } } } // A second optional argument can be given to further configure // the parser process. These options are recognized: var defaultOptions = { // `ecmaVersion` indicates the ECMAScript version to parse. Must be // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 // (2019). This influences support for strict mode, the set of // reserved words, and support for new syntax features. The default // is 9. ecmaVersion: 9, // `sourceType` indicates the mode the code should be parsed in. // Can be either `"script"` or `"module"`. This influences global // strict mode and parsing of `import` and `export` declarations. sourceType: "script", // `onInsertedSemicolon` can be a callback that will be called // when a semicolon is automatically inserted. It will be passed // the position of the comma as an offset, and if `locations` is // enabled, it is given the location as a `{line, column}` object // as second argument. onInsertedSemicolon: null, // `onTrailingComma` is similar to `onInsertedSemicolon`, but for // trailing commas. onTrailingComma: null, // By default, reserved words are only enforced if ecmaVersion >= 5. // Set `allowReserved` to a boolean value to explicitly turn this on // an off. When this option has the value "never", reserved words // and keywords can also not be used as property names. allowReserved: null, // When enabled, a return at the top level is not considered an // error. allowReturnOutsideFunction: false, // When enabled, import/export statements are not constrained to // appearing at the top of the program. allowImportExportEverywhere: false, // When enabled, await identifiers are allowed to appear at the top-level scope, // but they are still not allowed in non-async functions. allowAwaitOutsideFunction: false, // When enabled, hashbang directive in the beginning of file // is allowed and treated as a line comment. allowHashBang: false, // When `locations` is on, `loc` properties holding objects with // `start` and `end` properties in `{line, column}` form (with // line being 1-based and column 0-based) will be attached to the // nodes. locations: false, // A function can be passed as `onToken` option, which will // cause Acorn to call that function with object in the same // format as tokens returned from `tokenizer().getToken()`. Note // that you are not allowed to call the parser from the // callback—that will corrupt its internal state. onToken: null, // A function can be passed as `onComment` option, which will // cause Acorn to call that function with `(block, text, start, // end)` parameters whenever a comment is skipped. `block` is a // boolean indicating whether this is a block (`/* */`) comment, // `text` is the content of the comment, and `start` and `end` are // character offsets that denote the start and end of the comment. // When the `locations` option is on, two more parameters are // passed, the full `{line, column}` locations of the start and // end of the comments. Note that you are not allowed to call the // parser from the callback—that will corrupt its internal state. onComment: null, // Nodes have their start and end characters offsets recorded in // `start` and `end` properties (directly on the node, rather than // the `loc` object, which holds line/column data. To also add a // [semi-standardized][range] `range` property holding a `[start, // end]` array with the same numbers, set the `ranges` option to // `true`. // // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 ranges: false, // It is possible to parse multiple files into a single AST by // passing the tree produced by parsing the first file as // `program` option in subsequent parses. This will add the // toplevel forms of the parsed file to the `Program` (top) node // of an existing parse tree. program: null, // When `locations` is on, you can pass this to record the source // file in every node's `loc` object. sourceFile: null, // This value, if given, is stored in every node, whether // `locations` is on or off. directSourceFile: null, // When enabled, parenthesized expressions are represented by // (non-standard) ParenthesizedExpression nodes preserveParens: false }; // Interpret and default an options object function getOptions(opts) { var options = {}; for (var opt in defaultOptions) { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } if (options.ecmaVersion >= 2015) { options.ecmaVersion -= 2009; } if (options.allowReserved == null) { options.allowReserved = options.ecmaVersion < 5; } if (isArray(options.onToken)) { var tokens = options.onToken; options.onToken = function (token) { return tokens.push(token); }; } if (isArray(options.onComment)) { options.onComment = pushComment(options, options.onComment); } return options } function pushComment(options, array) { return function(block, text, start, end, startLoc, endLoc) { var comment = { type: block ? "Block" : "Line", value: text, start: start, end: end }; if (options.locations) { comment.loc = new SourceLocation(this, startLoc, endLoc); } if (options.ranges) { comment.range = [start, end]; } array.push(comment); } } // Each scope gets a bitset that may contain these flags var SCOPE_TOP = 1; var SCOPE_FUNCTION = 2; var SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION; var SCOPE_ASYNC = 4; var SCOPE_GENERATOR = 8; var SCOPE_ARROW = 16; var SCOPE_SIMPLE_CATCH = 32; var SCOPE_SUPER = 64; var SCOPE_DIRECT_SUPER = 128; function functionFlags(async, generator) { return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) } // Used in checkLVal and declareName to determine the type of a binding var BIND_NONE = 0; var BIND_VAR = 1; var BIND_LEXICAL = 2; var BIND_FUNCTION = 3; var BIND_SIMPLE_CATCH = 4; var BIND_OUTSIDE = 5; // Special case for function names as bound inside the function var Parser = function Parser(options, input, startPos) { this.options = options = getOptions(options); this.sourceFile = options.sourceFile; this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]); var reserved = ""; if (!options.allowReserved) { for (var v = options.ecmaVersion;; v--) { if (reserved = reservedWords[v]) { break } } if (options.sourceType === "module") { reserved += " await"; } } this.reservedWords = wordsRegexp(reserved); var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; this.reservedWordsStrict = wordsRegexp(reservedStrict); this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); this.input = String(input); // Used to signal to callers of `readWord1` whether the word // contained any escape sequences. This is needed because words with // escape sequences must not be interpreted as keywords. this.containsEsc = false; // Set up token state // The current position of the tokenizer in the input. if (startPos) { this.pos = startPos; this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; } else { this.pos = this.lineStart = 0; this.curLine = 1; } // Properties of the current token: // Its type this.type = types.eof; // For tokens that include more information than their type, the value this.value = null; // Its start and end offset this.start = this.end = this.pos; // And, if locations are used, the {line, column} object // corresponding to those offsets this.startLoc = this.endLoc = this.curPosition(); // Position information for the previous token this.lastTokEndLoc = this.lastTokStartLoc = null; this.lastTokStart = this.lastTokEnd = this.pos; // The context stack is used to superficially track syntactic // context to predict whether a regular expression is allowed in a // given position. this.context = this.initialContext(); this.exprAllowed = true; // Figure out if it's a module code. this.inModule = options.sourceType === "module"; this.strict = this.inModule || this.strictDirective(this.pos); // Used to signify the start of a potential arrow function this.potentialArrowAt = -1; // Positions to delayed-check that yield/await does not exist in default parameters. this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; // Labels in scope. this.labels = []; // Thus-far undefined exports. this.undefinedExports = {}; // If enabled, skip leading hashbang line. if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") { this.skipLineComment(2); } // Scope tracking for duplicate variable names (see scope.js) this.scopeStack = []; this.enterScope(SCOPE_TOP); // For RegExp validation this.regexpState = null; }; var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } }; Parser.prototype.parse = function parse () { var node = this.options.program || this.startNode(); this.nextToken(); return this.parseTopLevel(node) }; prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; // Switch to a getter for 7.0.0. Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; Parser.extend = function extend () { var plugins = [], len = arguments.length; while ( len-- ) plugins[ len ] = arguments[ len ]; var cls = this; for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } return cls }; Parser.parse = function parse (input, options) { return new this(options, input).parse() }; Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { var parser = new this(options, input, pos); parser.nextToken(); return parser.parseExpression() }; Parser.tokenizer = function tokenizer (input, options) { return new this(options, input) }; Object.defineProperties( Parser.prototype, prototypeAccessors ); var pp = Parser.prototype; // ## Parser utilities var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/; pp.strictDirective = function(start) { var this$1 = this; for (;;) { // Try to find string literal. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this$1.input)[0].length; var match = literal.exec(this$1.input.slice(start)); if (!match) { return false } if ((match[1] || match[2]) === "use strict") { return true } start += match[0].length; // Skip semicolon, if any. skipWhiteSpace.lastIndex = start; start += skipWhiteSpace.exec(this$1.input)[0].length; if (this$1.input[start] === ";") { start++; } } }; // Predicate that tests whether the next token is of the given // type, and if yes, consumes it as a side effect. pp.eat = function(type) { if (this.type === type) { this.next(); return true } else { return false } }; // Tests whether parsed token is a contextual keyword. pp.isContextual = function(name) { return this.type === types.name && this.value === name && !this.containsEsc }; // Consumes contextual keyword if possible. pp.eatContextual = function(name) { if (!this.isContextual(name)) { return false } this.next(); return true }; // Asserts that following token is given contextual keyword. pp.expectContextual = function(name) { if (!this.eatContextual(name)) { this.unexpected(); } }; // Test whether a semicolon can be inserted at the current position. pp.canInsertSemicolon = function() { return this.type === types.eof || this.type === types.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; pp.insertSemicolon = function() { if (this.canInsertSemicolon()) { if (this.options.onInsertedSemicolon) { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } return true } }; // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. pp.semicolon = function() { if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } }; pp.afterTrailingComma = function(tokType, notNext) { if (this.type === tokType) { if (this.options.onTrailingComma) { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } if (!notNext) { this.next(); } return true } }; // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error. pp.expect = function(type) { this.eat(type) || this.unexpected(); }; // Raise an unexpected token error. pp.unexpected = function(pos) { this.raise(pos != null ? pos : this.start, "Unexpected token"); }; function DestructuringErrors() { this.shorthandAssign = this.trailingComma = this.parenthesizedAssign = this.parenthesizedBind = this.doubleProto = -1; } pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { if (!refDestructuringErrors) { return } if (refDestructuringErrors.trailingComma > -1) { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } }; pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { if (!refDestructuringErrors) { return false } var shorthandAssign = refDestructuringErrors.shorthandAssign; var doubleProto = refDestructuringErrors.doubleProto; if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } if (shorthandAssign >= 0) { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } if (doubleProto >= 0) { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } }; pp.checkYieldAwaitInDefaultParams = function() { if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } if (this.awaitPos) { this.raise(this.awaitPos, "Await expression cannot be a default value"); } }; pp.isSimpleAssignTarget = function(expr) { if (expr.type === "ParenthesizedExpression") { return this.isSimpleAssignTarget(expr.expression) } return expr.type === "Identifier" || expr.type === "MemberExpression" }; var pp$1 = Parser.prototype; // ### Statement parsing // Parse a program. Initializes the parser, reads any number of // statements, and wraps them in a Program node. Optionally takes a // `program` argument. If present, the statements will be appended // to its body instead of creating a new node. pp$1.parseTopLevel = function(node) { var this$1 = this; var exports = {}; if (!node.body) { node.body = []; } while (this.type !== types.eof) { var stmt = this$1.parseStatement(null, true, exports); node.body.push(stmt); } if (this.inModule) { for (var i = 0, list = Object.keys(this$1.undefinedExports); i < list.length; i += 1) { var name = list[i]; this$1.raiseRecoverable(this$1.undefinedExports[name].start, ("Export '" + name + "' is not defined")); } } this.adaptDirectivePrologue(node.body); this.next(); if (this.options.ecmaVersion >= 6) { node.sourceType = this.options.sourceType; } return this.finishNode(node, "Program") }; var loopLabel = {kind: "loop"}; var switchLabel = {kind: "switch"}; pp$1.isLet = function(context) { if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); // For ambiguous cases, determine if a LexicalDeclaration (or only a // Statement) is allowed here. If context is not empty then only a Statement // is allowed. However, `let [` is an explicit negative lookahead for // ExpressionStatement, so special-case it first. if (nextCh === 91) { return true } // '[' if (context) { return false } if (nextCh === 123) { return true } // '{' if (isIdentifierStart(nextCh, true)) { var pos = next + 1; while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } var ident = this.input.slice(next, pos); if (!keywordRelationalOperator.test(ident)) { return true } } return false }; // check 'async [no LineTerminator here] function' // - 'async /*foo*/ function' is OK. // - 'async /*\n*/ function' is invalid. pp$1.isAsyncFunction = function() { if (this.options.ecmaVersion < 8 || !this.isContextual("async")) { return false } skipWhiteSpace.lastIndex = this.pos; var skip = skipWhiteSpace.exec(this.input); var next = this.pos + skip[0].length; return !lineBreak.test(this.input.slice(this.pos, next)) && this.input.slice(next, next + 8) === "function" && (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) }; // Parse a single statement. // // If expecting a statement and finding a slash operator, parse a // regular expression literal. This is to handle cases like // `if (foo) /blah/.exec(foo)`, where looking at the previous token // does not help. pp$1.parseStatement = function(context, topLevel, exports) { var starttype = this.type, node = this.startNode(), kind; if (this.isLet(context)) { starttype = types._var; kind = "let"; } // Most types of statements are recognized by the keyword they // start with. Many are trivial to parse, some require a bit of // complexity. switch (starttype) { case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) case types._debugger: return this.parseDebuggerStatement(node) case types._do: return this.parseDoStatement(node) case types._for: return this.parseForStatement(node) case types._function: // Function as sole body of either an if statement or a labeled statement // works, but not when it is part of a labeled statement that is the sole // body of an if statement. if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } return this.parseFunctionStatement(node, false, !context) case types._class: if (context) { this.unexpected(); } return this.parseClass(node, true) case types._if: return this.parseIfStatement(node) case types._return: return this.parseReturnStatement(node) case types._switch: return this.parseSwitchStatement(node) case types._throw: return this.parseThrowStatement(node) case types._try: return this.parseTryStatement(node) case types._const: case types._var: kind = kind || this.value; if (context && kind !== "var") { this.unexpected(); } return this.parseVarStatement(node, kind) case types._while: return this.parseWhileStatement(node) case types._with: return this.parseWithStatement(node) case types.braceL: return this.parseBlock(true, node) case types.semi: return this.parseEmptyStatement(node) case types._export: case types._import: if (!this.options.allowImportExportEverywhere) { if (!topLevel) { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } if (!this.inModule) { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } } return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) // If the statement does not start with a statement keyword or a // brace, it's an ExpressionStatement or LabeledStatement. We // simply start parsing an expression, and afterwards, if the // next token is a colon and the expression was a simple // Identifier node, we switch to interpreting it as a label. default: if (this.isAsyncFunction()) { if (context) { this.unexpected(); } this.next(); return this.parseFunctionStatement(node, true, !context) } var maybeName = this.value, expr = this.parseExpression(); if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) { return this.parseLabeledStatement(node, maybeName, expr, context) } else { return this.parseExpressionStatement(node, expr) } } }; pp$1.parseBreakContinueStatement = function(node, keyword) { var this$1 = this; var isBreak = keyword === "break"; this.next(); if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } else if (this.type !== types.name) { this.unexpected(); } else { node.label = this.parseIdent(); this.semicolon(); } // Verify that there is an actual destination to break or // continue to. var i = 0; for (; i < this.labels.length; ++i) { var lab = this$1.labels[i]; if (node.label == null || lab.name === node.label.name) { if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } if (node.label && isBreak) { break } } } if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") }; pp$1.parseDebuggerStatement = function(node) { this.next(); this.semicolon(); return this.finishNode(node, "DebuggerStatement") }; pp$1.parseDoStatement = function(node) { this.next(); this.labels.push(loopLabel); node.body = this.parseStatement("do"); this.labels.pop(); this.expect(types._while); node.test = this.parseParenExpression(); if (this.options.ecmaVersion >= 6) { this.eat(types.semi); } else { this.semicolon(); } return this.finishNode(node, "DoWhileStatement") }; // Disambiguating between a `for` and a `for`/`in` or `for`/`of` // loop is non-trivial. Basically, we have to parse the init `var` // statement or expression, disallowing the `in` operator (see // the second parameter to `parseExpression`), and then check // whether the next token is `in` or `of`. When there is no init // part (semicolon immediately after the opening parenthesis), it // is a regular `for` loop. pp$1.parseForStatement = function(node) { this.next(); var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; this.labels.push(loopLabel); this.enterScope(0); this.expect(types.parenL); if (this.type === types.semi) { if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, null) } var isLet = this.isLet(); if (this.type === types._var || this.type === types._const || isLet) { var init$1 = this.startNode(), kind = isLet ? "let" : this.value; this.next(); this.parseVar(init$1, true, kind); this.finishNode(init$1, "VariableDeclaration"); if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1 && !(kind !== "var" && init$1.declarations[0].init)) { if (this.options.ecmaVersion >= 9) { if (this.type === types._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } return this.parseForIn(node, init$1) } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init$1) } var refDestructuringErrors = new DestructuringErrors; var init = this.parseExpression(true, refDestructuringErrors); if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { if (this.options.ecmaVersion >= 9) { if (this.type === types._in) { if (awaitAt > -1) { this.unexpected(awaitAt); } } else { node.await = awaitAt > -1; } } this.toAssignable(init, false, refDestructuringErrors); this.checkLVal(init); return this.parseForIn(node, init) } else { this.checkExpressionErrors(refDestructuringErrors, true); } if (awaitAt > -1) { this.unexpected(awaitAt); } return this.parseFor(node, init) }; pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { this.next(); return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) }; pp$1.parseIfStatement = function(node) { this.next(); node.test = this.parseParenExpression(); // allow function declarations in branches, but only in non-strict mode node.consequent = this.parseStatement("if"); node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; return this.finishNode(node, "IfStatement") }; pp$1.parseReturnStatement = function(node) { if (!this.inFunction && !this.options.allowReturnOutsideFunction) { this.raise(this.start, "'return' outside of function"); } this.next(); // In `return` (and `break`/`continue`), the keywords with // optional arguments, we eagerly look for a semicolon or the // possibility to insert one. if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } else { node.argument = this.parseExpression(); this.semicolon(); } return this.finishNode(node, "ReturnStatement") }; pp$1.parseSwitchStatement = function(node) { var this$1 = this; this.next(); node.discriminant = this.parseParenExpression(); node.cases = []; this.expect(types.braceL); this.labels.push(switchLabel); this.enterScope(0); // Statements under must be grouped (by label) in SwitchCase // nodes. `cur` is used to keep the node that we are currently // adding statements to. var cur; for (var sawDefault = false; this.type !== types.braceR;) { if (this$1.type === types._case || this$1.type === types._default) { var isCase = this$1.type === types._case; if (cur) { this$1.finishNode(cur, "SwitchCase"); } node.cases.push(cur = this$1.startNode()); cur.consequent = []; this$1.next(); if (isCase) { cur.test = this$1.parseExpression(); } else { if (sawDefault) { this$1.raiseRecoverable(this$1.lastTokStart, "Multiple default clauses"); } sawDefault = true; cur.test = null; } this$1.expect(types.colon); } else { if (!cur) { this$1.unexpected(); } cur.consequent.push(this$1.parseStatement(null)); } } this.exitScope(); if (cur) { this.finishNode(cur, "SwitchCase"); } this.next(); // Closing brace this.labels.pop(); return this.finishNode(node, "SwitchStatement") }; pp$1.parseThrowStatement = function(node) { this.next(); if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) { this.raise(this.lastTokEnd, "Illegal newline after throw"); } node.argument = this.parseExpression(); this.semicolon(); return this.finishNode(node, "ThrowStatement") }; // Reused empty array added for node fields that are always empty. var empty = []; pp$1.parseTryStatement = function(node) { this.next(); node.block = this.parseBlock(); node.handler = null; if (this.type === types._catch) { var clause = this.startNode(); this.next(); if (this.eat(types.parenL)) { clause.param = this.parseBindingAtom(); var simple = clause.param.type === "Identifier"; this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); this.expect(types.parenR); } else { if (this.options.ecmaVersion < 10) { this.unexpected(); } clause.param = null; this.enterScope(0); } clause.body = this.parseBlock(false); this.exitScope(); node.handler = this.finishNode(clause, "CatchClause"); } node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; if (!node.handler && !node.finalizer) { this.raise(node.start, "Missing catch or finally clause"); } return this.finishNode(node, "TryStatement") }; pp$1.parseVarStatement = function(node, kind) { this.next(); this.parseVar(node, false, kind); this.semicolon(); return this.finishNode(node, "VariableDeclaration") }; pp$1.parseWhileStatement = function(node) { this.next(); node.test = this.parseParenExpression(); this.labels.push(loopLabel); node.body = this.parseStatement("while"); this.labels.pop(); return this.finishNode(node, "WhileStatement") }; pp$1.parseWithStatement = function(node) { if (this.strict) { this.raise(this.start, "'with' in strict mode"); } this.next(); node.object = this.parseParenExpression(); node.body = this.parseStatement("with"); return this.finishNode(node, "WithStatement") }; pp$1.parseEmptyStatement = function(node) { this.next(); return this.finishNode(node, "EmptyStatement") }; pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { var this$1 = this; for (var i$1 = 0, list = this$1.labels; i$1 < list.length; i$1 += 1) { var label = list[i$1]; if (label.name === maybeName) { this$1.raise(expr.start, "Label '" + maybeName + "' is already declared"); } } var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; for (var i = this.labels.length - 1; i >= 0; i--) { var label$1 = this$1.labels[i]; if (label$1.statementStart === node.start) { // Update information about previous labels on this node label$1.statementStart = this$1.start; label$1.kind = kind; } else { break } } this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); this.labels.pop(); node.label = expr; return this.finishNode(node, "LabeledStatement") }; pp$1.parseExpressionStatement = function(node, expr) { node.expression = expr; this.semicolon(); return this.finishNode(node, "ExpressionStatement") }; // Parse a semicolon-enclosed block of statements, handling `"use // strict"` declarations when `allowStrict` is true (used for // function bodies). pp$1.parseBlock = function(createNewLexicalScope, node) { var this$1 = this; if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; if ( node === void 0 ) node = this.startNode(); node.body = []; this.expect(types.braceL); if (createNewLexicalScope) { this.enterScope(0); } while (!this.eat(types.braceR)) { var stmt = this$1.parseStatement(null); node.body.push(stmt); } if (createNewLexicalScope) { this.exitScope(); } return this.finishNode(node, "BlockStatement") }; // Parse a regular `for` loop. The disambiguation code in // `parseStatement` will already have parsed the init statement or // expression. pp$1.parseFor = function(node, init) { node.init = init; this.expect(types.semi); node.test = this.type === types.semi ? null : this.parseExpression(); this.expect(types.semi); node.update = this.type === types.parenR ? null : this.parseExpression(); this.expect(types.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, "ForStatement") }; // Parse a `for`/`in` and `for`/`of` loop, which are almost // same from parser's perspective. pp$1.parseForIn = function(node, init) { var type = this.type === types._in ? "ForInStatement" : "ForOfStatement"; this.next(); if (type === "ForInStatement") { if (init.type === "AssignmentPattern" || (init.type === "VariableDeclaration" && init.declarations[0].init != null && (this.strict || init.declarations[0].id.type !== "Identifier"))) { this.raise(init.start, "Invalid assignment in for-in loop head"); } } node.left = init; node.right = type === "ForInStatement" ? this.parseExpression() : this.parseMaybeAssign(); this.expect(types.parenR); node.body = this.parseStatement("for"); this.exitScope(); this.labels.pop(); return this.finishNode(node, type) }; // Parse a list of variable declarations. pp$1.parseVar = function(node, isFor, kind) { var this$1 = this; node.declarations = []; node.kind = kind; for (;;) { var decl = this$1.startNode(); this$1.parseVarId(decl, kind); if (this$1.eat(types.eq)) { decl.init = this$1.parseMaybeAssign(isFor); } else if (kind === "const" && !(this$1.type === types._in || (this$1.options.ecmaVersion >= 6 && this$1.isContextual("of")))) { this$1.unexpected(); } else if (decl.id.type !== "Identifier" && !(isFor && (this$1.type === types._in || this$1.isContextual("of")))) { this$1.raise(this$1.lastTokEnd, "Complex binding patterns require an initialization value"); } else { decl.init = null; } node.declarations.push(this$1.finishNode(decl, "VariableDeclarator")); if (!this$1.eat(types.comma)) { break } } return node }; pp$1.parseVarId = function(decl, kind) { if ((kind === "const" || kind === "let") && this.isContextual("let")) { this.raiseRecoverable(this.start, "let is disallowed as a lexically bound name"); } decl.id = this.parseBindingAtom(); this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); }; var FUNC_STATEMENT = 1; var FUNC_HANGING_STATEMENT = 2; var FUNC_NULLABLE_ID = 4; // Parse a function declaration or literal (depending on the // `statement & FUNC_STATEMENT`). // Remove `allowExpressionBody` for 7.0.0, as it is only called with false pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { this.initFunction(node); if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) { this.unexpected(); } node.generator = this.eat(types.star); } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } if (statement & FUNC_STATEMENT) { node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); if (node.id && !(statement & FUNC_HANGING_STATEMENT)) // If it is a regular function declaration in sloppy mode, then it is // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding // mode depends on properties of the current scope (see // treatFunctionsAsVar). { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } } var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(node.async, node.generator)); if (!(statement & FUNC_STATEMENT)) { node.id = this.type === types.name ? this.parseIdent() : null; } this.parseFunctionParams(node); this.parseFunctionBody(node, allowExpressionBody, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") }; pp$1.parseFunctionParams = function(node) { this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); }; // Parse a class declaration or literal (depending on the // `isStatement` parameter). pp$1.parseClass = function(node, isStatement) { var this$1 = this; this.next(); // ecma-262 14.6 Class Definitions // A class definition is always strict mode code. var oldStrict = this.strict; this.strict = true; this.parseClassId(node, isStatement); this.parseClassSuper(node); var classBody = this.startNode(); var hadConstructor = false; classBody.body = []; this.expect(types.braceL); while (!this.eat(types.braceR)) { var element = this$1.parseClassElement(node.superClass !== null); if (element) { classBody.body.push(element); if (element.type === "MethodDefinition" && element.kind === "constructor") { if (hadConstructor) { this$1.raise(element.start, "Duplicate constructor in the same class"); } hadConstructor = true; } } } node.body = this.finishNode(classBody, "ClassBody"); this.strict = oldStrict; return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") }; pp$1.parseClassElement = function(constructorAllowsSuper) { var this$1 = this; if (this.eat(types.semi)) { return null } var method = this.startNode(); var tryContextual = function (k, noLineBreak) { if ( noLineBreak === void 0 ) noLineBreak = false; var start = this$1.start, startLoc = this$1.startLoc; if (!this$1.eatContextual(k)) { return false } if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true } if (method.key) { this$1.unexpected(); } method.computed = false; method.key = this$1.startNodeAt(start, startLoc); method.key.name = k; this$1.finishNode(method.key, "Identifier"); return false }; method.kind = "method"; method.static = tryContextual("static"); var isGenerator = this.eat(types.star); var isAsync = false; if (!isGenerator) { if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); } else if (tryContextual("get")) { method.kind = "get"; } else if (tryContextual("set")) { method.kind = "set"; } } if (!method.key) { this.parsePropertyName(method); } var key = method.key; var allowsDirectSuper = false; if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) { if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } method.kind = "constructor"; allowsDirectSuper = constructorAllowsSuper; } else if (method.static && key.type === "Identifier" && key.name === "prototype") { this.raise(key.start, "Classes may not have a static property named prototype"); } this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); if (method.kind === "get" && method.value.params.length !== 0) { this.raiseRecoverable(method.value.start, "getter should have no params"); } if (method.kind === "set" && method.value.params.length !== 1) { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } if (method.kind === "set" && method.value.params[0].type === "RestElement") { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } return method }; pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); return this.finishNode(method, "MethodDefinition") }; pp$1.parseClassId = function(node, isStatement) { if (this.type === types.name) { node.id = this.parseIdent(); if (isStatement) { this.checkLVal(node.id, BIND_LEXICAL, false); } } else { if (isStatement === true) { this.unexpected(); } node.id = null; } }; pp$1.parseClassSuper = function(node) { node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; }; // Parses module export declaration. pp$1.parseExport = function(node, exports) { var this$1 = this; this.next(); // export * from '...' if (this.eat(types.star)) { this.expectContextual("from"); if (this.type !== types.string) { this.unexpected(); } node.source = this.parseExprAtom(); this.semicolon(); return this.finishNode(node, "ExportAllDeclaration") } if (this.eat(types._default)) { // export default ... this.checkExport(exports, "default", this.lastTokStart); var isAsync; if (this.type === types._function || (isAsync = this.isAsyncFunction())) { var fNode = this.startNode(); this.next(); if (isAsync) { this.next(); } node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); } else if (this.type === types._class) { var cNode = this.startNode(); node.declaration = this.parseClass(cNode, "nullableID"); } else { node.declaration = this.parseMaybeAssign(); this.semicolon(); } return this.finishNode(node, "ExportDefaultDeclaration") } // export var|const|let|function|class ... if (this.shouldParseExportStatement()) { node.declaration = this.parseStatement(null); if (node.declaration.type === "VariableDeclaration") { this.checkVariableExport(exports, node.declaration.declarations); } else { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } node.specifiers = []; node.source = null; } else { // export { x, y as z } [from '...'] node.declaration = null; node.specifiers = this.parseExportSpecifiers(exports); if (this.eatContextual("from")) { if (this.type !== types.string) { this.unexpected(); } node.source = this.parseExprAtom(); } else { for (var i = 0, list = node.specifiers; i < list.length; i += 1) { // check for keywords used as local names var spec = list[i]; this$1.checkUnreserved(spec.local); // check if export is defined this$1.checkLocalExport(spec.local); } node.source = null; } this.semicolon(); } return this.finishNode(node, "ExportNamedDeclaration") }; pp$1.checkExport = function(exports, name, pos) { if (!exports) { return } if (has(exports, name)) { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } exports[name] = true; }; pp$1.checkPatternExport = function(exports, pat) { var this$1 = this; var type = pat.type; if (type === "Identifier") { this.checkExport(exports, pat.name, pat.start); } else if (type === "ObjectPattern") { for (var i = 0, list = pat.properties; i < list.length; i += 1) { var prop = list[i]; this$1.checkPatternExport(exports, prop); } } else if (type === "ArrayPattern") { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { var elt = list$1[i$1]; if (elt) { this$1.checkPatternExport(exports, elt); } } } else if (type === "Property") { this.checkPatternExport(exports, pat.value); } else if (type === "AssignmentPattern") { this.checkPatternExport(exports, pat.left); } else if (type === "RestElement") { this.checkPatternExport(exports, pat.argument); } else if (type === "ParenthesizedExpression") { this.checkPatternExport(exports, pat.expression); } }; pp$1.checkVariableExport = function(exports, decls) { var this$1 = this; if (!exports) { return } for (var i = 0, list = decls; i < list.length; i += 1) { var decl = list[i]; this$1.checkPatternExport(exports, decl.id); } }; pp$1.shouldParseExportStatement = function() { return this.type.keyword === "var" || this.type.keyword === "const" || this.type.keyword === "class" || this.type.keyword === "function" || this.isLet() || this.isAsyncFunction() }; // Parses a comma-separated list of module exports. pp$1.parseExportSpecifiers = function(exports) { var this$1 = this; var nodes = [], first = true; // export { x, y as z } [from '...'] this.expect(types.braceL); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false; } var node = this$1.startNode(); node.local = this$1.parseIdent(true); node.exported = this$1.eatContextual("as") ? this$1.parseIdent(true) : node.local; this$1.checkExport(exports, node.exported.name, node.exported.start); nodes.push(this$1.finishNode(node, "ExportSpecifier")); } return nodes }; // Parses import declaration. pp$1.parseImport = function(node) { this.next(); // import '...' if (this.type === types.string) { node.specifiers = empty; node.source = this.parseExprAtom(); } else { node.specifiers = this.parseImportSpecifiers(); this.expectContextual("from"); node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); } this.semicolon(); return this.finishNode(node, "ImportDeclaration") }; // Parses a comma-separated list of module imports. pp$1.parseImportSpecifiers = function() { var this$1 = this; var nodes = [], first = true; if (this.type === types.name) { // import defaultObj, { x, y as z } from '...' var node = this.startNode(); node.local = this.parseIdent(); this.checkLVal(node.local, BIND_LEXICAL); nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); if (!this.eat(types.comma)) { return nodes } } if (this.type === types.star) { var node$1 = this.startNode(); this.next(); this.expectContextual("as"); node$1.local = this.parseIdent(); this.checkLVal(node$1.local, BIND_LEXICAL); nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); return nodes } this.expect(types.braceL); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false; } var node$2 = this$1.startNode(); node$2.imported = this$1.parseIdent(true); if (this$1.eatContextual("as")) { node$2.local = this$1.parseIdent(); } else { this$1.checkUnreserved(node$2.imported); node$2.local = node$2.imported; } this$1.checkLVal(node$2.local, BIND_LEXICAL); nodes.push(this$1.finishNode(node$2, "ImportSpecifier")); } return nodes }; // Set `ExpressionStatement#directive` property for directive prologues. pp$1.adaptDirectivePrologue = function(statements) { for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { statements[i].directive = statements[i].expression.raw.slice(1, -1); } }; pp$1.isDirectiveCandidate = function(statement) { return ( statement.type === "ExpressionStatement" && statement.expression.type === "Literal" && typeof statement.expression.value === "string" && // Reject parenthesized strings. (this.input[statement.start] === "\"" || this.input[statement.start] === "'") ) }; var pp$2 = Parser.prototype; // Convert existing expression atom to assignable pattern // if possible. pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { var this$1 = this; if (this.options.ecmaVersion >= 6 && node) { switch (node.type) { case "Identifier": if (this.inAsync && node.name === "await") { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } break case "ObjectPattern": case "ArrayPattern": case "RestElement": break case "ObjectExpression": node.type = "ObjectPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } for (var i = 0, list = node.properties; i < list.length; i += 1) { var prop = list[i]; this$1.toAssignable(prop, isBinding); // Early error: // AssignmentRestProperty[Yield, Await] : // `...` DestructuringAssignmentTarget[Yield, Await] // // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. if ( prop.type === "RestElement" && (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") ) { this$1.raise(prop.argument.start, "Unexpected token"); } } break case "Property": // AssignmentProperty has type === "Property" if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } this.toAssignable(node.value, isBinding); break case "ArrayExpression": node.type = "ArrayPattern"; if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } this.toAssignableList(node.elements, isBinding); break case "SpreadElement": node.type = "RestElement"; this.toAssignable(node.argument, isBinding); if (node.argument.type === "AssignmentPattern") { this.raise(node.argument.start, "Rest elements cannot have a default value"); } break case "AssignmentExpression": if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } node.type = "AssignmentPattern"; delete node.operator; this.toAssignable(node.left, isBinding); // falls through to AssignmentPattern case "AssignmentPattern": break case "ParenthesizedExpression": this.toAssignable(node.expression, isBinding, refDestructuringErrors); break case "MemberExpression": if (!isBinding) { break } default: this.raise(node.start, "Assigning to rvalue"); } } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } return node }; // Convert list of expression atoms to binding list. pp$2.toAssignableList = function(exprList, isBinding) { var this$1 = this; var end = exprList.length; for (var i = 0; i < end; i++) { var elt = exprList[i]; if (elt) { this$1.toAssignable(elt, isBinding); } } if (end) { var last = exprList[end - 1]; if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") { this.unexpected(last.argument.start); } } return exprList }; // Parses spread element. pp$2.parseSpread = function(refDestructuringErrors) { var node = this.startNode(); this.next(); node.argument = this.parseMaybeAssign(false, refDestructuringErrors); return this.finishNode(node, "SpreadElement") }; pp$2.parseRestBinding = function() { var node = this.startNode(); this.next(); // RestElement inside of a function parameter must be an identifier if (this.options.ecmaVersion === 6 && this.type !== types.name) { this.unexpected(); } node.argument = this.parseBindingAtom(); return this.finishNode(node, "RestElement") }; // Parses lvalue (assignable) atom. pp$2.parseBindingAtom = function() { if (this.options.ecmaVersion >= 6) { switch (this.type) { case types.bracketL: var node = this.startNode(); this.next(); node.elements = this.parseBindingList(types.bracketR, true, true); return this.finishNode(node, "ArrayPattern") case types.braceL: return this.parseObj(true) } } return this.parseIdent() }; pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { var this$1 = this; var elts = [], first = true; while (!this.eat(close)) { if (first) { first = false; } else { this$1.expect(types.comma); } if (allowEmpty && this$1.type === types.comma) { elts.push(null); } else if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } else if (this$1.type === types.ellipsis) { var rest = this$1.parseRestBinding(); this$1.parseBindingListItem(rest); elts.push(rest); if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } this$1.expect(close); break } else { var elem = this$1.parseMaybeDefault(this$1.start, this$1.startLoc); this$1.parseBindingListItem(elem); elts.push(elem); } } return elts }; pp$2.parseBindingListItem = function(param) { return param }; // Parses assignment pattern around given atom if possible. pp$2.parseMaybeDefault = function(startPos, startLoc, left) { left = left || this.parseBindingAtom(); if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } var node = this.startNodeAt(startPos, startLoc); node.left = left; node.right = this.parseMaybeAssign(); return this.finishNode(node, "AssignmentPattern") }; // Verify that a node is an lval — something that can be assigned // to. // bindingType can be either: // 'var' indicating that the lval creates a 'var' binding // 'let' indicating that the lval creates a lexical ('let' or 'const') binding // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references pp$2.checkLVal = function(expr, bindingType, checkClashes) { var this$1 = this; if ( bindingType === void 0 ) bindingType = BIND_NONE; switch (expr.type) { case "Identifier": if (this.strict && this.reservedWordsStrictBind.test(expr.name)) { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } if (checkClashes) { if (has(checkClashes, expr.name)) { this.raiseRecoverable(expr.start, "Argument name clash"); } checkClashes[expr.name] = true; } if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } break case "MemberExpression": if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } break case "ObjectPattern": for (var i = 0, list = expr.properties; i < list.length; i += 1) { var prop = list[i]; this$1.checkLVal(prop, bindingType, checkClashes); } break case "Property": // AssignmentProperty has type === "Property" this.checkLVal(expr.value, bindingType, checkClashes); break case "ArrayPattern": for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { var elem = list$1[i$1]; if (elem) { this$1.checkLVal(elem, bindingType, checkClashes); } } break case "AssignmentPattern": this.checkLVal(expr.left, bindingType, checkClashes); break case "RestElement": this.checkLVal(expr.argument, bindingType, checkClashes); break case "ParenthesizedExpression": this.checkLVal(expr.expression, bindingType, checkClashes); break default: this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); } }; // A recursive descent parser operates by defining functions for all // syntactic elements, and recursively calling those, each function // advancing the input stream and returning an AST node. Precedence // of constructs (for example, the fact that `!x[1]` means `!(x[1])` // instead of `(!x)[1]` is handled by the fact that the parser // function that parses unary prefix operators is called first, and // in turn calls the function that parses `[]` subscripts — that // way, it'll receive the node for `x[1]` already parsed, and wraps // *that* in the unary operator node. // // Acorn uses an [operator precedence parser][opp] to handle binary // operator precedence, because it is much more compact than using // the technique outlined above, which uses different, nesting // functions to specify precedence, for all of the ten binary // precedence levels that JavaScript defines. // // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser var pp$3 = Parser.prototype; // Check if property name clashes with already added. // Object/class getters and setters are not allowed to clash — // either with each other or with an init property — and in // strict mode, init properties are also not allowed to be repeated. pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") { return } if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) { return } var key = prop.key; var name; switch (key.type) { case "Identifier": name = key.name; break case "Literal": name = String(key.value); break default: return } var kind = prop.kind; if (this.options.ecmaVersion >= 6) { if (name === "__proto__" && kind === "init") { if (propHash.proto) { if (refDestructuringErrors && refDestructuringErrors.doubleProto < 0) { refDestructuringErrors.doubleProto = key.start; } // Backwards-compat kludge. Can be removed in version 6.0 else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } } propHash.proto = true; } return } name = "$" + name; var other = propHash[name]; if (other) { var redefinition; if (kind === "init") { redefinition = this.strict && other.init || other.get || other.set; } else { redefinition = other.init || other[kind]; } if (redefinition) { this.raiseRecoverable(key.start, "Redefinition of property"); } } else { other = propHash[name] = { init: false, get: false, set: false }; } other[kind] = true; }; // ### Expression parsing // These nest, from the most general expression type at the top to // 'atomic', nondivisible expression types at the bottom. Most of // the functions will simply let the function(s) below them parse, // and, *if* the syntactic construct they handle is present, wrap // the AST node that the inner parser gave them in another node. // Parse a full expression. The optional arguments are used to // forbid the `in` operator (in for loops initalization expressions) // and provide reference for storing '=' operator inside shorthand // property assignment in contexts where both object expression // and object pattern might appear (so it's possible to raise // delayed syntax error at correct position). pp$3.parseExpression = function(noIn, refDestructuringErrors) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); if (this.type === types.comma) { var node = this.startNodeAt(startPos, startLoc); node.expressions = [expr]; while (this.eat(types.comma)) { node.expressions.push(this$1.parseMaybeAssign(noIn, refDestructuringErrors)); } return this.finishNode(node, "SequenceExpression") } return expr }; // Parse an assignment expression. This includes applications of // operators like `+=`. pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { if (this.isContextual("yield")) { if (this.inGenerator) { return this.parseYield(noIn) } // The tokenizer will assume an expression is allowed after // `yield`, but this isn't that kind of yield else { this.exprAllowed = false; } } var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldShorthandAssign = -1; if (refDestructuringErrors) { oldParenAssign = refDestructuringErrors.parenthesizedAssign; oldTrailingComma = refDestructuringErrors.trailingComma; oldShorthandAssign = refDestructuringErrors.shorthandAssign; refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.shorthandAssign = -1; } else { refDestructuringErrors = new DestructuringErrors; ownDestructuringErrors = true; } var startPos = this.start, startLoc = this.startLoc; if (this.type === types.parenL || this.type === types.name) { this.potentialArrowAt = this.start; } var left = this.parseMaybeConditional(noIn, refDestructuringErrors); if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } if (this.type.isAssign) { var node = this.startNodeAt(startPos, startLoc); node.operator = this.value; node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; if (!ownDestructuringErrors) { DestructuringErrors.call(refDestructuringErrors); } refDestructuringErrors.shorthandAssign = -1; // reset because shorthand default was used correctly this.checkLVal(left); this.next(); node.right = this.parseMaybeAssign(noIn); return this.finishNode(node, "AssignmentExpression") } else { if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } } if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } if (oldShorthandAssign > -1) { refDestructuringErrors.shorthandAssign = oldShorthandAssign; } return left }; // Parse a ternary conditional (`?:`) operator. pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprOps(noIn, refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } if (this.eat(types.question)) { var node = this.startNodeAt(startPos, startLoc); node.test = expr; node.consequent = this.parseMaybeAssign(); this.expect(types.colon); node.alternate = this.parseMaybeAssign(noIn); return this.finishNode(node, "ConditionalExpression") } return expr }; // Start the precedence parser. pp$3.parseExprOps = function(noIn, refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseMaybeUnary(refDestructuringErrors, false); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) }; // Parse binary operators with the operator precedence parsing // algorithm. `left` is the left-hand side of the operator. // `minPrec` provides context that allows the function to stop and // defer further parser to one of its callers when it encounters an // operator that has a lower precedence than the set it is parsing. pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { var prec = this.type.binop; if (prec != null && (!noIn || this.type !== types._in)) { if (prec > minPrec) { var logical = this.type === types.logicalOR || this.type === types.logicalAND; var op = this.value; this.next(); var startPos = this.start, startLoc = this.startLoc; var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical); return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) } } return left }; pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { var node = this.startNodeAt(startPos, startLoc); node.left = left; node.operator = op; node.right = right; return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") }; // Parse unary operators, both prefix and postfix. pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc, expr; if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { expr = this.parseAwait(); sawUnary = true; } else if (this.type.prefix) { var node = this.startNode(), update = this.type === types.incDec; node.operator = this.value; node.prefix = true; this.next(); node.argument = this.parseMaybeUnary(null, true); this.checkExpressionErrors(refDestructuringErrors, true); if (update) { this.checkLVal(node.argument); } else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } else { sawUnary = true; } expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); } else { expr = this.parseExprSubscripts(refDestructuringErrors); if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } while (this.type.postfix && !this.canInsertSemicolon()) { var node$1 = this$1.startNodeAt(startPos, startLoc); node$1.operator = this$1.value; node$1.prefix = false; node$1.argument = expr; this$1.checkLVal(expr); this$1.next(); expr = this$1.finishNode(node$1, "UpdateExpression"); } } if (!sawUnary && this.eat(types.starstar)) { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } else { return expr } }; // Parse call, dot, and `[]`-subscript expressions. pp$3.parseExprSubscripts = function(refDestructuringErrors) { var startPos = this.start, startLoc = this.startLoc; var expr = this.parseExprAtom(refDestructuringErrors); var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")"; if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) { return expr } var result = this.parseSubscripts(expr, startPos, startLoc); if (refDestructuringErrors && result.type === "MemberExpression") { if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } } return result }; pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { var this$1 = this; var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && this.lastTokEnd === base.end && !this.canInsertSemicolon() && this.input.slice(base.start, base.end) === "async"; while (true) { var element = this$1.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow); if (element === base || element.type === "ArrowFunctionExpression") { return element } base = element; } }; pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow) { var computed = this.eat(types.bracketL); if (computed || this.eat(types.dot)) { var node = this.startNodeAt(startPos, startLoc); node.object = base; node.property = computed ? this.parseExpression() : this.parseIdent(true); node.computed = !!computed; if (computed) { this.expect(types.bracketR); } base = this.finishNode(node, "MemberExpression"); } else if (!noCalls && this.eat(types.parenL)) { var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); if (maybeAsyncArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); if (this.awaitIdentPos > 0) { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; var node$1 = this.startNodeAt(startPos, startLoc); node$1.callee = base; node$1.arguments = exprList; base = this.finishNode(node$1, "CallExpression"); } else if (this.type === types.backQuote) { var node$2 = this.startNodeAt(startPos, startLoc); node$2.tag = base; node$2.quasi = this.parseTemplate({isTagged: true}); base = this.finishNode(node$2, "TaggedTemplateExpression"); } return base }; // Parse an atomic expression — either a single token that is an // expression, an expression started by a keyword like `function` or // `new`, or an expression wrapped in punctuation like `()`, `[]`, // or `{}`. pp$3.parseExprAtom = function(refDestructuringErrors) { // If a division operator appears in an expression position, the // tokenizer got confused, and we force it to read a regexp instead. if (this.type === types.slash) { this.readRegexp(); } var node, canBeArrow = this.potentialArrowAt === this.start; switch (this.type) { case types._super: if (!this.allowSuper) { this.raise(this.start, "'super' keyword outside a method"); } node = this.startNode(); this.next(); if (this.type === types.parenL && !this.allowDirectSuper) { this.raise(node.start, "super() call outside constructor of a subclass"); } // The `super` keyword can appear at below: // SuperProperty: // super [ Expression ] // super . IdentifierName // SuperCall: // super Arguments if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) { this.unexpected(); } return this.finishNode(node, "Super") case types._this: node = this.startNode(); this.next(); return this.finishNode(node, "ThisExpression") case types.name: var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; var id = this.parseIdent(false); if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } if (canBeArrow && !this.canInsertSemicolon()) { if (this.eat(types.arrow)) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { id = this.parseIdent(false); if (this.canInsertSemicolon() || !this.eat(types.arrow)) { this.unexpected(); } return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) } } return id case types.regexp: var value = this.value; node = this.parseLiteral(value.value); node.regex = {pattern: value.pattern, flags: value.flags}; return node case types.num: case types.string: return this.parseLiteral(this.value) case types._null: case types._true: case types._false: node = this.startNode(); node.value = this.type === types._null ? null : this.type === types._true; node.raw = this.type.keyword; this.next(); return this.finishNode(node, "Literal") case types.parenL: var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); if (refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) { refDestructuringErrors.parenthesizedAssign = start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = start; } } return expr case types.bracketL: node = this.startNode(); this.next(); node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); return this.finishNode(node, "ArrayExpression") case types.braceL: return this.parseObj(false, refDestructuringErrors) case types._function: node = this.startNode(); this.next(); return this.parseFunction(node, 0) case types._class: return this.parseClass(this.startNode(), false) case types._new: return this.parseNew() case types.backQuote: return this.parseTemplate() default: this.unexpected(); } }; pp$3.parseLiteral = function(value) { var node = this.startNode(); node.value = value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "Literal") }; pp$3.parseParenExpression = function() { this.expect(types.parenL); var val = this.parseExpression(); this.expect(types.parenR); return val }; pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { var this$1 = this; var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; if (this.options.ecmaVersion >= 6) { this.next(); var innerStartPos = this.start, innerStartLoc = this.startLoc; var exprList = [], first = true, lastIsComma = false; var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; this.yieldPos = 0; this.awaitPos = 0; // Do not save awaitIdentPos to allow checking awaits nested in parameters while (this.type !== types.parenR) { first ? first = false : this$1.expect(types.comma); if (allowTrailingComma && this$1.afterTrailingComma(types.parenR, true)) { lastIsComma = true; break } else if (this$1.type === types.ellipsis) { spreadStart = this$1.start; exprList.push(this$1.parseParenItem(this$1.parseRestBinding())); if (this$1.type === types.comma) { this$1.raise(this$1.start, "Comma is not permitted after the rest element"); } break } else { exprList.push(this$1.parseMaybeAssign(false, refDestructuringErrors, this$1.parseParenItem)); } } var innerEndPos = this.start, innerEndLoc = this.startLoc; this.expect(types.parenR); if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { this.checkPatternErrors(refDestructuringErrors, false); this.checkYieldAwaitInDefaultParams(); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; return this.parseParenArrowList(startPos, startLoc, exprList) } if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } if (spreadStart) { this.unexpected(spreadStart); } this.checkExpressionErrors(refDestructuringErrors, true); this.yieldPos = oldYieldPos || this.yieldPos; this.awaitPos = oldAwaitPos || this.awaitPos; if (exprList.length > 1) { val = this.startNodeAt(innerStartPos, innerStartLoc); val.expressions = exprList; this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); } else { val = exprList[0]; } } else { val = this.parseParenExpression(); } if (this.options.preserveParens) { var par = this.startNodeAt(startPos, startLoc); par.expression = val; return this.finishNode(par, "ParenthesizedExpression") } else { return val } }; pp$3.parseParenItem = function(item) { return item }; pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) }; // New's precedence is slightly tricky. It must allow its argument to // be a `[]` or dot subscript expression, but not a call — at least, // not without wrapping it in parentheses. Thus, it uses the noCalls // argument to parseSubscripts to prevent it from consuming the // argument list. var empty$1 = []; pp$3.parseNew = function() { var node = this.startNode(); var meta = this.parseIdent(true); if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { node.meta = meta; var containsEsc = this.containsEsc; node.property = this.parseIdent(true); if (node.property.name !== "target" || containsEsc) { this.raiseRecoverable(node.property.start, "The only valid meta property for new is new.target"); } if (!this.inNonArrowFunction()) { this.raiseRecoverable(node.start, "new.target can only be used in functions"); } return this.finishNode(node, "MetaProperty") } var startPos = this.start, startLoc = this.startLoc; node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } else { node.arguments = empty$1; } return this.finishNode(node, "NewExpression") }; // Parse template expression. pp$3.parseTemplateElement = function(ref) { var isTagged = ref.isTagged; var elem = this.startNode(); if (this.type === types.invalidTemplate) { if (!isTagged) { this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); } elem.value = { raw: this.value, cooked: null }; } else { elem.value = { raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), cooked: this.value }; } this.next(); elem.tail = this.type === types.backQuote; return this.finishNode(elem, "TemplateElement") }; pp$3.parseTemplate = function(ref) { var this$1 = this; if ( ref === void 0 ) ref = {}; var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; var node = this.startNode(); this.next(); node.expressions = []; var curElt = this.parseTemplateElement({isTagged: isTagged}); node.quasis = [curElt]; while (!curElt.tail) { if (this$1.type === types.eof) { this$1.raise(this$1.pos, "Unterminated template literal"); } this$1.expect(types.dollarBraceL); node.expressions.push(this$1.parseExpression()); this$1.expect(types.braceR); node.quasis.push(curElt = this$1.parseTemplateElement({isTagged: isTagged})); } this.next(); return this.finishNode(node, "TemplateLiteral") }; pp$3.isAsyncProp = function(prop) { return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }; // Parse an object literal or binding pattern. pp$3.parseObj = function(isPattern, refDestructuringErrors) { var this$1 = this; var node = this.startNode(), first = true, propHash = {}; node.properties = []; this.next(); while (!this.eat(types.braceR)) { if (!first) { this$1.expect(types.comma); if (this$1.afterTrailingComma(types.braceR)) { break } } else { first = false; } var prop = this$1.parseProperty(isPattern, refDestructuringErrors); if (!isPattern) { this$1.checkPropClash(prop, propHash, refDestructuringErrors); } node.properties.push(prop); } return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") }; pp$3.parseProperty = function(isPattern, refDestructuringErrors) { var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { if (isPattern) { prop.argument = this.parseIdent(false); if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } return this.finishNode(prop, "RestElement") } // To disallow parenthesized identifier via `this.toAssignable()`. if (this.type === types.parenL && refDestructuringErrors) { if (refDestructuringErrors.parenthesizedAssign < 0) { refDestructuringErrors.parenthesizedAssign = this.start; } if (refDestructuringErrors.parenthesizedBind < 0) { refDestructuringErrors.parenthesizedBind = this.start; } } // Parse argument. prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); // To disallow trailing comma via `this.toAssignable()`. if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this.start; } // Finish return this.finishNode(prop, "SpreadElement") } if (this.options.ecmaVersion >= 6) { prop.method = false; prop.shorthand = false; if (isPattern || refDestructuringErrors) { startPos = this.start; startLoc = this.startLoc; } if (!isPattern) { isGenerator = this.eat(types.star); } } var containsEsc = this.containsEsc; this.parsePropertyName(prop); if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { isAsync = true; isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); this.parsePropertyName(prop, refDestructuringErrors); } else { isAsync = false; } this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); return this.finishNode(prop, "Property") }; pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { if ((isGenerator || isAsync) && this.type === types.colon) { this.unexpected(); } if (this.eat(types.colon)) { prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); prop.kind = "init"; } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { if (isPattern) { this.unexpected(); } prop.kind = "init"; prop.method = true; prop.value = this.parseMethod(isGenerator, isAsync); } else if (!isPattern && !containsEsc && this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && (this.type !== types.comma && this.type !== types.braceR)) { if (isGenerator || isAsync) { this.unexpected(); } prop.kind = prop.key.name; this.parsePropertyName(prop); prop.value = this.parseMethod(false); var paramCount = prop.kind === "get" ? 0 : 1; if (prop.value.params.length !== paramCount) { var start = prop.value.start; if (prop.kind === "get") { this.raiseRecoverable(start, "getter should have no params"); } else { this.raiseRecoverable(start, "setter should have exactly one param"); } } else { if (prop.kind === "set" && prop.value.params[0].type === "RestElement") { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } } } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { if (isGenerator || isAsync) { this.unexpected(); } this.checkUnreserved(prop.key); if (prop.key.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = startPos; } prop.kind = "init"; if (isPattern) { prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); } else if (this.type === types.eq && refDestructuringErrors) { if (refDestructuringErrors.shorthandAssign < 0) { refDestructuringErrors.shorthandAssign = this.start; } prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); } else { prop.value = prop.key; } prop.shorthand = true; } else { this.unexpected(); } }; pp$3.parsePropertyName = function(prop) { if (this.options.ecmaVersion >= 6) { if (this.eat(types.bracketL)) { prop.computed = true; prop.key = this.parseMaybeAssign(); this.expect(types.bracketR); return prop.key } else { prop.computed = false; } } return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(true) }; // Initialize empty function node. pp$3.initFunction = function(node) { node.id = null; if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } if (this.options.ecmaVersion >= 8) { node.async = false; } }; // Parse object or class method. pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.initFunction(node); if (this.options.ecmaVersion >= 6) { node.generator = isGenerator; } if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); this.expect(types.parenL); node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); this.checkYieldAwaitInDefaultParams(); this.parseFunctionBody(node, false, true); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "FunctionExpression") }; // Parse arrow function expression with given parameters. pp$3.parseArrowExpression = function(node, params, isAsync) { var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); this.initFunction(node); if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } this.yieldPos = 0; this.awaitPos = 0; this.awaitIdentPos = 0; node.params = this.toAssignableList(params, true); this.parseFunctionBody(node, true, false); this.yieldPos = oldYieldPos; this.awaitPos = oldAwaitPos; this.awaitIdentPos = oldAwaitIdentPos; return this.finishNode(node, "ArrowFunctionExpression") }; // Parse function body and check parameters. pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { var isExpression = isArrowFunction && this.type !== types.braceL; var oldStrict = this.strict, useStrict = false; if (isExpression) { node.body = this.parseMaybeAssign(); node.expression = true; this.checkParams(node, false); } else { var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); if (!oldStrict || nonSimple) { useStrict = this.strictDirective(this.end); // If this is a strict mode function, verify that argument names // are not repeated, and it does not try to bind the words `eval` // or `arguments`. if (useStrict && nonSimple) { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } } // Start a new scope with regard to labels and the `inFunction` // flag (restore them to their old value afterwards). var oldLabels = this.labels; this.labels = []; if (useStrict) { this.strict = true; } // Add the params to varDeclaredNames to ensure that an error is thrown // if a let/const declaration in the function clashes with one of the params. this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); node.body = this.parseBlock(false); node.expression = false; this.adaptDirectivePrologue(node.body.body); this.labels = oldLabels; } this.exitScope(); // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } this.strict = oldStrict; }; pp$3.isSimpleParamList = function(params) { for (var i = 0, list = params; i < list.length; i += 1) { var param = list[i]; if (param.type !== "Identifier") { return false } } return true }; // Checks function params for various disallowed patterns such as using "eval" // or "arguments" and duplicate parameters. pp$3.checkParams = function(node, allowDuplicates) { var this$1 = this; var nameHash = {}; for (var i = 0, list = node.params; i < list.length; i += 1) { var param = list[i]; this$1.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); } }; // Parses a comma-separated list of expressions, and returns them as // an array. `close` is the token type that ends the list, and // `allowEmpty` can be turned on to allow subsequent commas with // nothing in between them to be parsed as `null` (which is needed // for array literals). pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { var this$1 = this; var elts = [], first = true; while (!this.eat(close)) { if (!first) { this$1.expect(types.comma); if (allowTrailingComma && this$1.afterTrailingComma(close)) { break } } else { first = false; } var elt = (void 0); if (allowEmpty && this$1.type === types.comma) { elt = null; } else if (this$1.type === types.ellipsis) { elt = this$1.parseSpread(refDestructuringErrors); if (refDestructuringErrors && this$1.type === types.comma && refDestructuringErrors.trailingComma < 0) { refDestructuringErrors.trailingComma = this$1.start; } } else { elt = this$1.parseMaybeAssign(false, refDestructuringErrors); } elts.push(elt); } return elts }; pp$3.checkUnreserved = function(ref) { var start = ref.start; var end = ref.end; var name = ref.name; if (this.inGenerator && name === "yield") { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } if (this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } if (this.keywords.test(name)) { this.raise(start, ("Unexpected keyword '" + name + "'")); } if (this.options.ecmaVersion < 6 && this.input.slice(start, end).indexOf("\\") !== -1) { return } var re = this.strict ? this.reservedWordsStrict : this.reservedWords; if (re.test(name)) { if (!this.inAsync && name === "await") { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); } }; // Parse the next token as an identifier. If `liberal` is true (used // when parsing properties), it will also convert keywords into // identifiers. pp$3.parseIdent = function(liberal, isBinding) { var node = this.startNode(); if (liberal && this.options.allowReserved === "never") { liberal = false; } if (this.type === types.name) { node.name = this.value; } else if (this.type.keyword) { node.name = this.type.keyword; // To fix https://github.com/acornjs/acorn/issues/575 // `class` and `function` keywords push new context into this.context. // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword if ((node.name === "class" || node.name === "function") && (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { this.context.pop(); } } else { this.unexpected(); } this.next(); this.finishNode(node, "Identifier"); if (!liberal) { this.checkUnreserved(node); if (node.name === "await" && !this.awaitIdentPos) { this.awaitIdentPos = node.start; } } return node }; // Parses yield expression inside generator. pp$3.parseYield = function(noIn) { if (!this.yieldPos) { this.yieldPos = this.start; } var node = this.startNode(); this.next(); if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { node.delegate = false; node.argument = null; } else { node.delegate = this.eat(types.star); node.argument = this.parseMaybeAssign(noIn); } return this.finishNode(node, "YieldExpression") }; pp$3.parseAwait = function() { if (!this.awaitPos) { this.awaitPos = this.start; } var node = this.startNode(); this.next(); node.argument = this.parseMaybeUnary(null, true); return this.finishNode(node, "AwaitExpression") }; var pp$4 = Parser.prototype; // This function is used to raise exceptions on parse errors. It // takes an offset integer (into the current `input`) to indicate // the location of the error, attaches the position to the end // of the error message, and then raises a `SyntaxError` with that // message. pp$4.raise = function(pos, message) { var loc = getLineInfo(this.input, pos); message += " (" + loc.line + ":" + loc.column + ")"; var err = new SyntaxError(message); err.pos = pos; err.loc = loc; err.raisedAt = this.pos; throw err }; pp$4.raiseRecoverable = pp$4.raise; pp$4.curPosition = function() { if (this.options.locations) { return new Position(this.curLine, this.pos - this.lineStart) } }; var pp$5 = Parser.prototype; var Scope = function Scope(flags) { this.flags = flags; // A list of var-declared names in the current lexical scope this.var = []; // A list of lexically-declared names in the current lexical scope this.lexical = []; // A list of lexically-declared FunctionDeclaration names in the current lexical scope this.functions = []; }; // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. pp$5.enterScope = function(flags) { this.scopeStack.push(new Scope(flags)); }; pp$5.exitScope = function() { this.scopeStack.pop(); }; // The spec says: // > At the top level of a function, or script, function declarations are // > treated like var declarations rather than like lexical declarations. pp$5.treatFunctionsAsVarInScope = function(scope) { return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) }; pp$5.declareName = function(name, bindingType, pos) { var this$1 = this; var redeclared = false; if (bindingType === BIND_LEXICAL) { var scope = this.currentScope(); redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; scope.lexical.push(name); if (this.inModule && (scope.flags & SCOPE_TOP)) { delete this.undefinedExports[name]; } } else if (bindingType === BIND_SIMPLE_CATCH) { var scope$1 = this.currentScope(); scope$1.lexical.push(name); } else if (bindingType === BIND_FUNCTION) { var scope$2 = this.currentScope(); if (this.treatFunctionsAsVar) { redeclared = scope$2.lexical.indexOf(name) > -1; } else { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } scope$2.functions.push(name); } else { for (var i = this.scopeStack.length - 1; i >= 0; --i) { var scope$3 = this$1.scopeStack[i]; if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || !this$1.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { redeclared = true; break } scope$3.var.push(name); if (this$1.inModule && (scope$3.flags & SCOPE_TOP)) { delete this$1.undefinedExports[name]; } if (scope$3.flags & SCOPE_VAR) { break } } } if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } }; pp$5.checkLocalExport = function(id) { // scope.functions must be empty as Module code is always strict. if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && this.scopeStack[0].var.indexOf(id.name) === -1) { this.undefinedExports[id.name] = id; } }; pp$5.currentScope = function() { return this.scopeStack[this.scopeStack.length - 1] }; pp$5.currentVarScope = function() { var this$1 = this; for (var i = this.scopeStack.length - 1;; i--) { var scope = this$1.scopeStack[i]; if (scope.flags & SCOPE_VAR) { return scope } } }; // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. pp$5.currentThisScope = function() { var this$1 = this; for (var i = this.scopeStack.length - 1;; i--) { var scope = this$1.scopeStack[i]; if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } } }; var Node = function Node(parser, pos, loc) { this.type = ""; this.start = pos; this.end = 0; if (parser.options.locations) { this.loc = new SourceLocation(parser, loc); } if (parser.options.directSourceFile) { this.sourceFile = parser.options.directSourceFile; } if (parser.options.ranges) { this.range = [pos, 0]; } }; // Start an AST node, attaching a start offset. var pp$6 = Parser.prototype; pp$6.startNode = function() { return new Node(this, this.start, this.startLoc) }; pp$6.startNodeAt = function(pos, loc) { return new Node(this, pos, loc) }; // Finish an AST node, adding `type` and `end` properties. function finishNodeAt(node, type, pos, loc) { node.type = type; node.end = pos; if (this.options.locations) { node.loc.end = loc; } if (this.options.ranges) { node.range[1] = pos; } return node } pp$6.finishNode = function(node, type) { return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) }; // Finish node at given position pp$6.finishNodeAt = function(node, type, pos, loc) { return finishNodeAt.call(this, node, type, pos, loc) }; // The algorithm used to determine whether a regexp can appear at a // given point in the program is loosely based on sweet.js' approach. // See https://github.com/mozilla/sweet.js/wiki/design var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { this.token = token; this.isExpr = !!isExpr; this.preserveSpace = !!preserveSpace; this.override = override; this.generator = !!generator; }; var types$1 = { b_stat: new TokContext("{", false), b_expr: new TokContext("{", true), b_tmpl: new TokContext("${", false), p_stat: new TokContext("(", false), p_expr: new TokContext("(", true), q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), f_stat: new TokContext("function", false), f_expr: new TokContext("function", true), f_expr_gen: new TokContext("function", true, false, null, true), f_gen: new TokContext("function", false, false, null, true) }; var pp$7 = Parser.prototype; pp$7.initialContext = function() { return [types$1.b_stat] }; pp$7.braceIsBlock = function(prevType) { var parent = this.curContext(); if (parent === types$1.f_expr || parent === types$1.f_stat) { return true } if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) { return !parent.isExpr } // The check for `tt.name && exprAllowed` detects whether we are // after a `yield` or `of` construct. See the `updateContext` for // `tt.name`. if (prevType === types._return || prevType === types.name && this.exprAllowed) { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) { return true } if (prevType === types.braceL) { return parent === types$1.b_stat } if (prevType === types._var || prevType === types._const || prevType === types.name) { return false } return !this.exprAllowed }; pp$7.inGeneratorContext = function() { var this$1 = this; for (var i = this.context.length - 1; i >= 1; i--) { var context = this$1.context[i]; if (context.token === "function") { return context.generator } } return false }; pp$7.updateContext = function(prevType) { var update, type = this.type; if (type.keyword && prevType === types.dot) { this.exprAllowed = false; } else if (update = type.updateContext) { update.call(this, prevType); } else { this.exprAllowed = type.beforeExpr; } }; // Token-specific context update code types.parenR.updateContext = types.braceR.updateContext = function() { if (this.context.length === 1) { this.exprAllowed = true; return } var out = this.context.pop(); if (out === types$1.b_stat && this.curContext().token === "function") { out = this.context.pop(); } this.exprAllowed = !out.isExpr; }; types.braceL.updateContext = function(prevType) { this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); this.exprAllowed = true; }; types.dollarBraceL.updateContext = function() { this.context.push(types$1.b_tmpl); this.exprAllowed = true; }; types.parenL.updateContext = function(prevType) { var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); this.exprAllowed = true; }; types.incDec.updateContext = function() { // tokExprAllowed stays unchanged }; types._function.updateContext = types._class.updateContext = function(prevType) { if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) { this.context.push(types$1.f_expr); } else { this.context.push(types$1.f_stat); } this.exprAllowed = false; }; types.backQuote.updateContext = function() { if (this.curContext() === types$1.q_tmpl) { this.context.pop(); } else { this.context.push(types$1.q_tmpl); } this.exprAllowed = false; }; types.star.updateContext = function(prevType) { if (prevType === types._function) { var index = this.context.length - 1; if (this.context[index] === types$1.f_expr) { this.context[index] = types$1.f_expr_gen; } else { this.context[index] = types$1.f_gen; } } this.exprAllowed = true; }; types.name.updateContext = function(prevType) { var allowed = false; if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { if (this.value === "of" && !this.exprAllowed || this.value === "yield" && this.inGeneratorContext()) { allowed = true; } } this.exprAllowed = allowed; }; // This file contains Unicode properties extracted from the ECMAScript // specification. The lists are extracted like so: // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) // #table-binary-unicode-properties var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; var unicodeBinaryProperties = { 9: ecma9BinaryProperties, 10: ecma9BinaryProperties + " Extended_Pictographic" }; // #table-unicode-general-category-values var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; // #table-unicode-script-values var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; var unicodeScriptValues = { 9: ecma9ScriptValues, 10: ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd" }; var data = {}; function buildUnicodeData(ecmaVersion) { var d = data[ecmaVersion] = { binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), nonBinary: { General_Category: wordsRegexp(unicodeGeneralCategoryValues), Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) } }; d.nonBinary.Script_Extensions = d.nonBinary.Script; d.nonBinary.gc = d.nonBinary.General_Category; d.nonBinary.sc = d.nonBinary.Script; d.nonBinary.scx = d.nonBinary.Script_Extensions; } buildUnicodeData(9); buildUnicodeData(10); var pp$9 = Parser.prototype; var RegExpValidationState = function RegExpValidationState(parser) { this.parser = parser; this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); this.unicodeProperties = data[parser.options.ecmaVersion >= 10 ? 10 : parser.options.ecmaVersion]; this.source = ""; this.flags = ""; this.start = 0; this.switchU = false; this.switchN = false; this.pos = 0; this.lastIntValue = 0; this.lastStringValue = ""; this.lastAssertionIsQuantifiable = false; this.numCapturingParens = 0; this.maxBackReference = 0; this.groupNames = []; this.backReferenceNames = []; }; RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { var unicode = flags.indexOf("u") !== -1; this.start = start | 0; this.source = pattern + ""; this.flags = flags; this.switchU = unicode && this.parser.options.ecmaVersion >= 6; this.switchN = unicode && this.parser.options.ecmaVersion >= 9; }; RegExpValidationState.prototype.raise = function raise (message) { this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); }; // If u flag is given, this returns the code point at the index (it combines a surrogate pair). // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). RegExpValidationState.prototype.at = function at (i) { var s = this.source; var l = s.length; if (i >= l) { return -1 } var c = s.charCodeAt(i); if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return c } return (c << 10) + s.charCodeAt(i + 1) - 0x35FDC00 }; RegExpValidationState.prototype.nextIndex = function nextIndex (i) { var s = this.source; var l = s.length; if (i >= l) { return l } var c = s.charCodeAt(i); if (!this.switchU || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { return i + 1 } return i + 2 }; RegExpValidationState.prototype.current = function current () { return this.at(this.pos) }; RegExpValidationState.prototype.lookahead = function lookahead () { return this.at(this.nextIndex(this.pos)) }; RegExpValidationState.prototype.advance = function advance () { this.pos = this.nextIndex(this.pos); }; RegExpValidationState.prototype.eat = function eat (ch) { if (this.current() === ch) { this.advance(); return true } return false }; function codePointToString$1(ch) { if (ch <= 0xFFFF) { return String.fromCharCode(ch) } ch -= 0x10000; return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) } /** * Validate the flags part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$9.validateRegExpFlags = function(state) { var this$1 = this; var validFlags = state.validFlags; var flags = state.flags; for (var i = 0; i < flags.length; i++) { var flag = flags.charAt(i); if (validFlags.indexOf(flag) === -1) { this$1.raise(state.start, "Invalid regular expression flag"); } if (flags.indexOf(flag, i + 1) > -1) { this$1.raise(state.start, "Duplicate regular expression flag"); } } }; /** * Validate the pattern part of a given RegExpLiteral. * * @param {RegExpValidationState} state The state to validate RegExp. * @returns {void} */ pp$9.validateRegExpPattern = function(state) { this.regexp_pattern(state); // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of // parsing contains a |GroupName|, reparse with the goal symbol // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* // exception if _P_ did not conform to the grammar, if any elements of _P_ // were not matched by the parse, or if any Early Error conditions exist. if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { state.switchN = true; this.regexp_pattern(state); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern pp$9.regexp_pattern = function(state) { state.pos = 0; state.lastIntValue = 0; state.lastStringValue = ""; state.lastAssertionIsQuantifiable = false; state.numCapturingParens = 0; state.maxBackReference = 0; state.groupNames.length = 0; state.backReferenceNames.length = 0; this.regexp_disjunction(state); if (state.pos !== state.source.length) { // Make the same messages as V8. if (state.eat(0x29 /* ) */)) { state.raise("Unmatched ')'"); } if (state.eat(0x5D /* [ */) || state.eat(0x7D /* } */)) { state.raise("Lone quantifier brackets"); } } if (state.maxBackReference > state.numCapturingParens) { state.raise("Invalid escape"); } for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { var name = list[i]; if (state.groupNames.indexOf(name) === -1) { state.raise("Invalid named capture referenced"); } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction pp$9.regexp_disjunction = function(state) { var this$1 = this; this.regexp_alternative(state); while (state.eat(0x7C /* | */)) { this$1.regexp_alternative(state); } // Make the same message as V8. if (this.regexp_eatQuantifier(state, true)) { state.raise("Nothing to repeat"); } if (state.eat(0x7B /* { */)) { state.raise("Lone quantifier brackets"); } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative pp$9.regexp_alternative = function(state) { while (state.pos < state.source.length && this.regexp_eatTerm(state)) { } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term pp$9.regexp_eatTerm = function(state) { if (this.regexp_eatAssertion(state)) { // Handle `QuantifiableAssertion Quantifier` alternative. // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion // is a QuantifiableAssertion. if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { // Make the same message as V8. if (state.switchU) { state.raise("Invalid quantifier"); } } return true } if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { this.regexp_eatQuantifier(state); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion pp$9.regexp_eatAssertion = function(state) { var start = state.pos; state.lastAssertionIsQuantifiable = false; // ^, $ if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { return true } // \b \B if (state.eat(0x5C /* \ */)) { if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { return true } state.pos = start; } // Lookahead / Lookbehind if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { var lookbehind = false; if (this.options.ecmaVersion >= 9) { lookbehind = state.eat(0x3C /* < */); } if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { this.regexp_disjunction(state); if (!state.eat(0x29 /* ) */)) { state.raise("Unterminated group"); } state.lastAssertionIsQuantifiable = !lookbehind; return true } } state.pos = start; return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier pp$9.regexp_eatQuantifier = function(state, noError) { if ( noError === void 0 ) noError = false; if (this.regexp_eatQuantifierPrefix(state, noError)) { state.eat(0x3F /* ? */); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix pp$9.regexp_eatQuantifierPrefix = function(state, noError) { return ( state.eat(0x2A /* * */) || state.eat(0x2B /* + */) || state.eat(0x3F /* ? */) || this.regexp_eatBracedQuantifier(state, noError) ) }; pp$9.regexp_eatBracedQuantifier = function(state, noError) { var start = state.pos; if (state.eat(0x7B /* { */)) { var min = 0, max = -1; if (this.regexp_eatDecimalDigits(state)) { min = state.lastIntValue; if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { max = state.lastIntValue; } if (state.eat(0x7D /* } */)) { // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term if (max !== -1 && max < min && !noError) { state.raise("numbers out of order in {} quantifier"); } return true } } if (state.switchU && !noError) { state.raise("Incomplete quantifier"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom pp$9.regexp_eatAtom = function(state) { return ( this.regexp_eatPatternCharacters(state) || state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) ) }; pp$9.regexp_eatReverseSolidusAtomEscape = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatAtomEscape(state)) { return true } state.pos = start; } return false }; pp$9.regexp_eatUncapturingGroup = function(state) { var start = state.pos; if (state.eat(0x28 /* ( */)) { if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { return true } state.raise("Unterminated group"); } state.pos = start; } return false }; pp$9.regexp_eatCapturingGroup = function(state) { if (state.eat(0x28 /* ( */)) { if (this.options.ecmaVersion >= 9) { this.regexp_groupSpecifier(state); } else if (state.current() === 0x3F /* ? */) { state.raise("Invalid group"); } this.regexp_disjunction(state); if (state.eat(0x29 /* ) */)) { state.numCapturingParens += 1; return true } state.raise("Unterminated group"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom pp$9.regexp_eatExtendedAtom = function(state) { return ( state.eat(0x2E /* . */) || this.regexp_eatReverseSolidusAtomEscape(state) || this.regexp_eatCharacterClass(state) || this.regexp_eatUncapturingGroup(state) || this.regexp_eatCapturingGroup(state) || this.regexp_eatInvalidBracedQuantifier(state) || this.regexp_eatExtendedPatternCharacter(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier pp$9.regexp_eatInvalidBracedQuantifier = function(state) { if (this.regexp_eatBracedQuantifier(state, true)) { state.raise("Nothing to repeat"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter pp$9.regexp_eatSyntaxCharacter = function(state) { var ch = state.current(); if (isSyntaxCharacter(ch)) { state.lastIntValue = ch; state.advance(); return true } return false }; function isSyntaxCharacter(ch) { return ( ch === 0x24 /* $ */ || ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || ch === 0x2E /* . */ || ch === 0x3F /* ? */ || ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || ch >= 0x7B /* { */ && ch <= 0x7D /* } */ ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter // But eat eager. pp$9.regexp_eatPatternCharacters = function(state) { var start = state.pos; var ch = 0; while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { state.advance(); } return state.pos !== start }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter pp$9.regexp_eatExtendedPatternCharacter = function(state) { var ch = state.current(); if ( ch !== -1 && ch !== 0x24 /* $ */ && !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && ch !== 0x2E /* . */ && ch !== 0x3F /* ? */ && ch !== 0x5B /* [ */ && ch !== 0x5E /* ^ */ && ch !== 0x7C /* | */ ) { state.advance(); return true } return false }; // GroupSpecifier[U] :: // [empty] // `?` GroupName[?U] pp$9.regexp_groupSpecifier = function(state) { if (state.eat(0x3F /* ? */)) { if (this.regexp_eatGroupName(state)) { if (state.groupNames.indexOf(state.lastStringValue) !== -1) { state.raise("Duplicate capture group name"); } state.groupNames.push(state.lastStringValue); return } state.raise("Invalid group"); } }; // GroupName[U] :: // `<` RegExpIdentifierName[?U] `>` // Note: this updates `state.lastStringValue` property with the eaten name. pp$9.regexp_eatGroupName = function(state) { state.lastStringValue = ""; if (state.eat(0x3C /* < */)) { if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { return true } state.raise("Invalid capture group name"); } return false }; // RegExpIdentifierName[U] :: // RegExpIdentifierStart[?U] // RegExpIdentifierName[?U] RegExpIdentifierPart[?U] // Note: this updates `state.lastStringValue` property with the eaten name. pp$9.regexp_eatRegExpIdentifierName = function(state) { state.lastStringValue = ""; if (this.regexp_eatRegExpIdentifierStart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); while (this.regexp_eatRegExpIdentifierPart(state)) { state.lastStringValue += codePointToString$1(state.lastIntValue); } return true } return false }; // RegExpIdentifierStart[U] :: // UnicodeIDStart // `$` // `_` // `\` RegExpUnicodeEscapeSequence[?U] pp$9.regexp_eatRegExpIdentifierStart = function(state) { var start = state.pos; var ch = state.current(); state.advance(); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { ch = state.lastIntValue; } if (isRegExpIdentifierStart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierStart(ch) { return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ } // RegExpIdentifierPart[U] :: // UnicodeIDContinue // `$` // `_` // `\` RegExpUnicodeEscapeSequence[?U] // // pp$9.regexp_eatRegExpIdentifierPart = function(state) { var start = state.pos; var ch = state.current(); state.advance(); if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state)) { ch = state.lastIntValue; } if (isRegExpIdentifierPart(ch)) { state.lastIntValue = ch; return true } state.pos = start; return false }; function isRegExpIdentifierPart(ch) { return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* */ || ch === 0x200D /* */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape pp$9.regexp_eatAtomEscape = function(state) { if ( this.regexp_eatBackReference(state) || this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) || (state.switchN && this.regexp_eatKGroupName(state)) ) { return true } if (state.switchU) { // Make the same message as V8. if (state.current() === 0x63 /* c */) { state.raise("Invalid unicode escape"); } state.raise("Invalid escape"); } return false }; pp$9.regexp_eatBackReference = function(state) { var start = state.pos; if (this.regexp_eatDecimalEscape(state)) { var n = state.lastIntValue; if (state.switchU) { // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape if (n > state.maxBackReference) { state.maxBackReference = n; } return true } if (n <= state.numCapturingParens) { return true } state.pos = start; } return false }; pp$9.regexp_eatKGroupName = function(state) { if (state.eat(0x6B /* k */)) { if (this.regexp_eatGroupName(state)) { state.backReferenceNames.push(state.lastStringValue); return true } state.raise("Invalid named reference"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape pp$9.regexp_eatCharacterEscape = function(state) { return ( this.regexp_eatControlEscape(state) || this.regexp_eatCControlLetter(state) || this.regexp_eatZero(state) || this.regexp_eatHexEscapeSequence(state) || this.regexp_eatRegExpUnicodeEscapeSequence(state) || (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || this.regexp_eatIdentityEscape(state) ) }; pp$9.regexp_eatCControlLetter = function(state) { var start = state.pos; if (state.eat(0x63 /* c */)) { if (this.regexp_eatControlLetter(state)) { return true } state.pos = start; } return false }; pp$9.regexp_eatZero = function(state) { if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { state.lastIntValue = 0; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape pp$9.regexp_eatControlEscape = function(state) { var ch = state.current(); if (ch === 0x74 /* t */) { state.lastIntValue = 0x09; /* \t */ state.advance(); return true } if (ch === 0x6E /* n */) { state.lastIntValue = 0x0A; /* \n */ state.advance(); return true } if (ch === 0x76 /* v */) { state.lastIntValue = 0x0B; /* \v */ state.advance(); return true } if (ch === 0x66 /* f */) { state.lastIntValue = 0x0C; /* \f */ state.advance(); return true } if (ch === 0x72 /* r */) { state.lastIntValue = 0x0D; /* \r */ state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter pp$9.regexp_eatControlLetter = function(state) { var ch = state.current(); if (isControlLetter(ch)) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; function isControlLetter(ch) { return ( (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence pp$9.regexp_eatRegExpUnicodeEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x75 /* u */)) { if (this.regexp_eatFixedHexDigits(state, 4)) { var lead = state.lastIntValue; if (state.switchU && lead >= 0xD800 && lead <= 0xDBFF) { var leadSurrogateEnd = state.pos; if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { var trail = state.lastIntValue; if (trail >= 0xDC00 && trail <= 0xDFFF) { state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; return true } } state.pos = leadSurrogateEnd; state.lastIntValue = lead; } return true } if ( state.switchU && state.eat(0x7B /* { */) && this.regexp_eatHexDigits(state) && state.eat(0x7D /* } */) && isValidUnicode(state.lastIntValue) ) { return true } if (state.switchU) { state.raise("Invalid unicode escape"); } state.pos = start; } return false }; function isValidUnicode(ch) { return ch >= 0 && ch <= 0x10FFFF } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape pp$9.regexp_eatIdentityEscape = function(state) { if (state.switchU) { if (this.regexp_eatSyntaxCharacter(state)) { return true } if (state.eat(0x2F /* / */)) { state.lastIntValue = 0x2F; /* / */ return true } return false } var ch = state.current(); if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape pp$9.regexp_eatDecimalEscape = function(state) { state.lastIntValue = 0; var ch = state.current(); if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { do { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape pp$9.regexp_eatCharacterClassEscape = function(state) { var ch = state.current(); if (isCharacterClassEscape(ch)) { state.lastIntValue = -1; state.advance(); return true } if ( state.switchU && this.options.ecmaVersion >= 9 && (ch === 0x50 /* P */ || ch === 0x70 /* p */) ) { state.lastIntValue = -1; state.advance(); if ( state.eat(0x7B /* { */) && this.regexp_eatUnicodePropertyValueExpression(state) && state.eat(0x7D /* } */) ) { return true } state.raise("Invalid property name"); } return false }; function isCharacterClassEscape(ch) { return ( ch === 0x64 /* d */ || ch === 0x44 /* D */ || ch === 0x73 /* s */ || ch === 0x53 /* S */ || ch === 0x77 /* w */ || ch === 0x57 /* W */ ) } // UnicodePropertyValueExpression :: // UnicodePropertyName `=` UnicodePropertyValue // LoneUnicodePropertyNameOrValue pp$9.regexp_eatUnicodePropertyValueExpression = function(state) { var start = state.pos; // UnicodePropertyName `=` UnicodePropertyValue if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { var name = state.lastStringValue; if (this.regexp_eatUnicodePropertyValue(state)) { var value = state.lastStringValue; this.regexp_validateUnicodePropertyNameAndValue(state, name, value); return true } } state.pos = start; // LoneUnicodePropertyNameOrValue if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { var nameOrValue = state.lastStringValue; this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); return true } return false }; pp$9.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { if (!has(state.unicodeProperties.nonBinary, name)) { state.raise("Invalid property name"); } if (!state.unicodeProperties.nonBinary[name].test(value)) { state.raise("Invalid property value"); } }; pp$9.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { if (!state.unicodeProperties.binary.test(nameOrValue)) { state.raise("Invalid property name"); } }; // UnicodePropertyName :: // UnicodePropertyNameCharacters pp$9.regexp_eatUnicodePropertyName = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyNameCharacter(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyNameCharacter(ch) { return isControlLetter(ch) || ch === 0x5F /* _ */ } // UnicodePropertyValue :: // UnicodePropertyValueCharacters pp$9.regexp_eatUnicodePropertyValue = function(state) { var ch = 0; state.lastStringValue = ""; while (isUnicodePropertyValueCharacter(ch = state.current())) { state.lastStringValue += codePointToString$1(ch); state.advance(); } return state.lastStringValue !== "" }; function isUnicodePropertyValueCharacter(ch) { return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) } // LoneUnicodePropertyNameOrValue :: // UnicodePropertyValueCharacters pp$9.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { return this.regexp_eatUnicodePropertyValue(state) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass pp$9.regexp_eatCharacterClass = function(state) { if (state.eat(0x5B /* [ */)) { state.eat(0x5E /* ^ */); this.regexp_classRanges(state); if (state.eat(0x5D /* [ */)) { return true } // Unreachable since it threw "unterminated regular expression" error before. state.raise("Unterminated character class"); } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash pp$9.regexp_classRanges = function(state) { var this$1 = this; while (this.regexp_eatClassAtom(state)) { var left = state.lastIntValue; if (state.eat(0x2D /* - */) && this$1.regexp_eatClassAtom(state)) { var right = state.lastIntValue; if (state.switchU && (left === -1 || right === -1)) { state.raise("Invalid character class"); } if (left !== -1 && right !== -1 && left > right) { state.raise("Range out of order in character class"); } } } }; // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash pp$9.regexp_eatClassAtom = function(state) { var start = state.pos; if (state.eat(0x5C /* \ */)) { if (this.regexp_eatClassEscape(state)) { return true } if (state.switchU) { // Make the same message as V8. var ch$1 = state.current(); if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { state.raise("Invalid class escape"); } state.raise("Invalid escape"); } state.pos = start; } var ch = state.current(); if (ch !== 0x5D /* [ */) { state.lastIntValue = ch; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape pp$9.regexp_eatClassEscape = function(state) { var start = state.pos; if (state.eat(0x62 /* b */)) { state.lastIntValue = 0x08; /* */ return true } if (state.switchU && state.eat(0x2D /* - */)) { state.lastIntValue = 0x2D; /* - */ return true } if (!state.switchU && state.eat(0x63 /* c */)) { if (this.regexp_eatClassControlLetter(state)) { return true } state.pos = start; } return ( this.regexp_eatCharacterClassEscape(state) || this.regexp_eatCharacterEscape(state) ) }; // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter pp$9.regexp_eatClassControlLetter = function(state) { var ch = state.current(); if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { state.lastIntValue = ch % 0x20; state.advance(); return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$9.regexp_eatHexEscapeSequence = function(state) { var start = state.pos; if (state.eat(0x78 /* x */)) { if (this.regexp_eatFixedHexDigits(state, 2)) { return true } if (state.switchU) { state.raise("Invalid escape"); } state.pos = start; } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits pp$9.regexp_eatDecimalDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isDecimalDigit(ch = state.current())) { state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); state.advance(); } return state.pos !== start }; function isDecimalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits pp$9.regexp_eatHexDigits = function(state) { var start = state.pos; var ch = 0; state.lastIntValue = 0; while (isHexDigit(ch = state.current())) { state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return state.pos !== start }; function isHexDigit(ch) { return ( (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) ) } function hexToInt(ch) { if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { return 10 + (ch - 0x41 /* A */) } if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { return 10 + (ch - 0x61 /* a */) } return ch - 0x30 /* 0 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence // Allows only 0-377(octal) i.e. 0-255(decimal). pp$9.regexp_eatLegacyOctalEscapeSequence = function(state) { if (this.regexp_eatOctalDigit(state)) { var n1 = state.lastIntValue; if (this.regexp_eatOctalDigit(state)) { var n2 = state.lastIntValue; if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; } else { state.lastIntValue = n1 * 8 + n2; } } else { state.lastIntValue = n1; } return true } return false }; // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit pp$9.regexp_eatOctalDigit = function(state) { var ch = state.current(); if (isOctalDigit(ch)) { state.lastIntValue = ch - 0x30; /* 0 */ state.advance(); return true } state.lastIntValue = 0; return false }; function isOctalDigit(ch) { return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ } // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence pp$9.regexp_eatFixedHexDigits = function(state, length) { var start = state.pos; state.lastIntValue = 0; for (var i = 0; i < length; ++i) { var ch = state.current(); if (!isHexDigit(ch)) { state.pos = start; return false } state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); state.advance(); } return true }; // Object type used to represent tokens. Note that normally, tokens // simply exist as properties on the parser object. This is only // used for the onToken callback and the external tokenizer. var Token = function Token(p) { this.type = p.type; this.value = p.value; this.start = p.start; this.end = p.end; if (p.options.locations) { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } if (p.options.ranges) { this.range = [p.start, p.end]; } }; // ## Tokenizer var pp$8 = Parser.prototype; // Move to the next token pp$8.next = function() { if (this.options.onToken) { this.options.onToken(new Token(this)); } this.lastTokEnd = this.end; this.lastTokStart = this.start; this.lastTokEndLoc = this.endLoc; this.lastTokStartLoc = this.startLoc; this.nextToken(); }; pp$8.getToken = function() { this.next(); return new Token(this) }; // If we're in an ES6 environment, make parsers iterable if (typeof Symbol !== "undefined") { pp$8[Symbol.iterator] = function() { var this$1 = this; return { next: function () { var token = this$1.getToken(); return { done: token.type === types.eof, value: token } } } }; } // Toggle strict mode. Re-reads the next number or string to please // pedantic tests (`"use strict"; 010;` should fail). pp$8.curContext = function() { return this.context[this.context.length - 1] }; // Read a single token, updating the parser object's token-related // properties. pp$8.nextToken = function() { var curContext = this.curContext(); if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } this.start = this.pos; if (this.options.locations) { this.startLoc = this.curPosition(); } if (this.pos >= this.input.length) { return this.finishToken(types.eof) } if (curContext.override) { return curContext.override(this) } else { this.readToken(this.fullCharCodeAtPos()); } }; pp$8.readToken = function(code) { // Identifier or keyword. '\uXXXX' sequences are allowed in // identifiers, so '\' also dispatches to that. if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) { return this.readWord() } return this.getTokenFromCode(code) }; pp$8.fullCharCodeAtPos = function() { var code = this.input.charCodeAt(this.pos); if (code <= 0xd7ff || code >= 0xe000) { return code } var next = this.input.charCodeAt(this.pos + 1); return (code << 10) + next - 0x35fdc00 }; pp$8.skipBlockComment = function() { var this$1 = this; var startLoc = this.options.onComment && this.curPosition(); var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } this.pos = end + 2; if (this.options.locations) { lineBreakG.lastIndex = start; var match; while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { ++this$1.curLine; this$1.lineStart = match.index + match[0].length; } } if (this.options.onComment) { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition()); } }; pp$8.skipLineComment = function(startSkip) { var this$1 = this; var start = this.pos; var startLoc = this.options.onComment && this.curPosition(); var ch = this.input.charCodeAt(this.pos += startSkip); while (this.pos < this.input.length && !isNewLine(ch)) { ch = this$1.input.charCodeAt(++this$1.pos); } if (this.options.onComment) { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition()); } }; // Called at the start of the parse and after every token. Skips // whitespace and comments, and. pp$8.skipSpace = function() { var this$1 = this; loop: while (this.pos < this.input.length) { var ch = this$1.input.charCodeAt(this$1.pos); switch (ch) { case 32: case 160: // ' ' ++this$1.pos; break case 13: if (this$1.input.charCodeAt(this$1.pos + 1) === 10) { ++this$1.pos; } case 10: case 8232: case 8233: ++this$1.pos; if (this$1.options.locations) { ++this$1.curLine; this$1.lineStart = this$1.pos; } break case 47: // '/' switch (this$1.input.charCodeAt(this$1.pos + 1)) { case 42: // '*' this$1.skipBlockComment(); break case 47: this$1.skipLineComment(2); break default: break loop } break default: if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { ++this$1.pos; } else { break loop } } } }; // Called at the end of every token. Sets `end`, `val`, and // maintains `context` and `exprAllowed`, and skips the space after // the token, so that the next one's `start` will point at the // right position. pp$8.finishToken = function(type, val) { this.end = this.pos; if (this.options.locations) { this.endLoc = this.curPosition(); } var prevType = this.type; this.type = type; this.value = val; this.updateContext(prevType); }; // ### Token reading // This is the function that is called to fetch the next token. It // is somewhat obscure, because it works in character codes rather // than characters, and because operator parsing has been inlined // into it. // // All in the name of speed. // pp$8.readToken_dot = function() { var next = this.input.charCodeAt(this.pos + 1); if (next >= 48 && next <= 57) { return this.readNumber(true) } var next2 = this.input.charCodeAt(this.pos + 2); if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' this.pos += 3; return this.finishToken(types.ellipsis) } else { ++this.pos; return this.finishToken(types.dot) } }; pp$8.readToken_slash = function() { // '/' var next = this.input.charCodeAt(this.pos + 1); if (this.exprAllowed) { ++this.pos; return this.readRegexp() } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.slash, 1) }; pp$8.readToken_mult_modulo_exp = function(code) { // '%*' var next = this.input.charCodeAt(this.pos + 1); var size = 1; var tokentype = code === 42 ? types.star : types.modulo; // exponentiation operator ** and **= if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { ++size; tokentype = types.starstar; next = this.input.charCodeAt(this.pos + 2); } if (next === 61) { return this.finishOp(types.assign, size + 1) } return this.finishOp(tokentype, size) }; pp$8.readToken_pipe_amp = function(code) { // '|&' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) }; pp$8.readToken_caret = function() { // '^' var next = this.input.charCodeAt(this.pos + 1); if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.bitwiseXOR, 1) }; pp$8.readToken_plus_min = function(code) { // '+-' var next = this.input.charCodeAt(this.pos + 1); if (next === code) { if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { // A `-->` line comment this.skipLineComment(3); this.skipSpace(); return this.nextToken() } return this.finishOp(types.incDec, 2) } if (next === 61) { return this.finishOp(types.assign, 2) } return this.finishOp(types.plusMin, 1) }; pp$8.readToken_lt_gt = function(code) { // '<>' var next = this.input.charCodeAt(this.pos + 1); var size = 1; if (next === code) { size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } return this.finishOp(types.bitShift, size) } if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && this.input.charCodeAt(this.pos + 3) === 45) { // `*rp1 . . (+12) . . rp2o *---------->* rp2 . . . . . . . . . 10 20 . . |.........|...................| . . . . . . (+8) . po *------>*p . . . . . 12 . 24 . |...........|.......................| 36 ------- (+10) rp1o *-------->*rp1 . . (-10) . . rp2 *<---------* rpo2 . . . . . . . . . 10 . 30 . . |.........|.............................| . . . (+5) . po *--->* p . . . . . . 20 . |....|..............| 5 15 ------- (+10) rp1o *-------->*rp1 . . . . rp2o *-------->*rp2 (+10) po *-------->* p ------- (+10) rp1o *-------->*rp1 . . . .(+30) rp2o *---------------------------->*rp2 (+25) po *----------------------->* p vim: set ts=4 sw=4 expandtab: *****/ // The Font object /** * @typedef FontOptions * @type Object * @property {Boolean} empty - whether to create a new empty font * @property {string} familyName * @property {string} styleName * @property {string=} fullName * @property {string=} postScriptName * @property {string=} designer * @property {string=} designerURL * @property {string=} manufacturer * @property {string=} manufacturerURL * @property {string=} license * @property {string=} licenseURL * @property {string=} version * @property {string=} description * @property {string=} copyright * @property {string=} trademark * @property {Number} unitsPerEm * @property {Number} ascender * @property {Number} descender * @property {Number} createdTimestamp * @property {string=} weightClass * @property {string=} widthClass * @property {string=} fsSelection */ /** * A Font represents a loaded OpenType font file. * It contains a set of glyphs and methods to draw text on a drawing context, * or to get a path representing the text. * @exports opentype.Font * @class * @param {FontOptions} * @constructor */ function Font(options) { options = options || {}; if (!options.empty) { // Check that we've provided the minimum set of names. checkArgument(options.familyName, 'When creating a new Font object, familyName is required.'); checkArgument(options.styleName, 'When creating a new Font object, styleName is required.'); checkArgument(options.unitsPerEm, 'When creating a new Font object, unitsPerEm is required.'); checkArgument(options.ascender, 'When creating a new Font object, ascender is required.'); checkArgument(options.descender, 'When creating a new Font object, descender is required.'); checkArgument(options.descender < 0, 'Descender should be negative (e.g. -512).'); // OS X will complain if the names are empty, so we put a single space everywhere by default. this.names = { fontFamily: {en: options.familyName || ' '}, fontSubfamily: {en: options.styleName || ' '}, fullName: {en: options.fullName || options.familyName + ' ' + options.styleName}, postScriptName: {en: options.postScriptName || options.familyName + options.styleName}, designer: {en: options.designer || ' '}, designerURL: {en: options.designerURL || ' '}, manufacturer: {en: options.manufacturer || ' '}, manufacturerURL: {en: options.manufacturerURL || ' '}, license: {en: options.license || ' '}, licenseURL: {en: options.licenseURL || ' '}, version: {en: options.version || 'Version 0.1'}, description: {en: options.description || ' '}, copyright: {en: options.copyright || ' '}, trademark: {en: options.trademark || ' '} }; this.unitsPerEm = options.unitsPerEm || 1000; this.ascender = options.ascender; this.descender = options.descender; this.createdTimestamp = options.createdTimestamp; this.tables = { os2: { usWeightClass: options.weightClass || this.usWeightClasses.MEDIUM, usWidthClass: options.widthClass || this.usWidthClasses.MEDIUM, fsSelection: options.fsSelection || this.fsSelectionValues.REGULAR } }; } this.supported = true; // Deprecated: parseBuffer will throw an error if font is not supported. this.glyphs = new glyphset.GlyphSet(this, options.glyphs || []); this.encoding = new DefaultEncoding(this); this.substitution = new Substitution(this); this.tables = this.tables || {}; Object.defineProperty(this, 'hinting', { get: function() { if (this._hinting) { return this._hinting; } if (this.outlinesFormat === 'truetype') { return (this._hinting = new Hinting(this)); } } }); } /** * Check if the font has a glyph for the given character. * @param {string} * @return {Boolean} */ Font.prototype.hasChar = function(c) { return this.encoding.charToGlyphIndex(c) !== null; }; /** * Convert the given character to a single glyph index. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {Number} */ Font.prototype.charToGlyphIndex = function(s) { return this.encoding.charToGlyphIndex(s); }; /** * Convert the given character to a single Glyph object. * Note that this function assumes that there is a one-to-one mapping between * the given character and a glyph; for complex scripts this might not be the case. * @param {string} * @return {opentype.Glyph} */ Font.prototype.charToGlyph = function(c) { var glyphIndex = this.charToGlyphIndex(c); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * Convert the given text to a list of Glyph objects. * Note that there is no strict one-to-one mapping between characters and * glyphs, so the list of returned glyphs can be larger or smaller than the * length of the given string. * @param {string} * @param {GlyphRenderOptions} [options] * @return {opentype.Glyph[]} */ Font.prototype.stringToGlyphs = function(s, options) { var this$1 = this; options = options || this.defaultRenderOptions; // Get glyph indexes var indexes = []; for (var i = 0; i < s.length; i += 1) { var c = s[i]; indexes.push(this$1.charToGlyphIndex(c)); } var length = indexes.length; // Apply substitutions on glyph indexes if (options.features) { var script = options.script || this.substitution.getDefaultScriptName(); var manyToOne = []; if (options.features.liga) { manyToOne = manyToOne.concat(this.substitution.getFeature('liga', script, options.language)); } if (options.features.rlig) { manyToOne = manyToOne.concat(this.substitution.getFeature('rlig', script, options.language)); } for (var i$1 = 0; i$1 < length; i$1 += 1) { for (var j = 0; j < manyToOne.length; j++) { var ligature = manyToOne[j]; var components = ligature.sub; var compCount = components.length; var k = 0; while (k < compCount && components[k] === indexes[i$1 + k]) { k++; } if (k === compCount) { indexes.splice(i$1, compCount, ligature.by); length = length - compCount + 1; } } } } // convert glyph indexes to glyph objects var glyphs = new Array(length); var notdef = this.glyphs.get(0); for (var i$2 = 0; i$2 < length; i$2 += 1) { glyphs[i$2] = this$1.glyphs.get(indexes[i$2]) || notdef; } return glyphs; }; /** * @param {string} * @return {Number} */ Font.prototype.nameToGlyphIndex = function(name) { return this.glyphNames.nameToGlyphIndex(name); }; /** * @param {string} * @return {opentype.Glyph} */ Font.prototype.nameToGlyph = function(name) { var glyphIndex = this.nameToGlyphIndex(name); var glyph = this.glyphs.get(glyphIndex); if (!glyph) { // .notdef glyph = this.glyphs.get(0); } return glyph; }; /** * @param {Number} * @return {String} */ Font.prototype.glyphIndexToName = function(gid) { if (!this.glyphNames.glyphIndexToName) { return ''; } return this.glyphNames.glyphIndexToName(gid); }; /** * Retrieve the value of the kerning pair between the left glyph (or its index) * and the right glyph (or its index). If no kerning pair is found, return 0. * The kerning value gets added to the advance width when calculating the spacing * between glyphs. * @param {opentype.Glyph} leftGlyph * @param {opentype.Glyph} rightGlyph * @return {Number} */ Font.prototype.getKerningValue = function(leftGlyph, rightGlyph) { leftGlyph = leftGlyph.index || leftGlyph; rightGlyph = rightGlyph.index || rightGlyph; var gposKerning = this.getGposKerningValue; return gposKerning ? gposKerning(leftGlyph, rightGlyph) : (this.kerningPairs[leftGlyph + ',' + rightGlyph] || 0); }; /** * @typedef GlyphRenderOptions * @type Object * @property {string} [script] - script used to determine which features to apply. By default, 'DFLT' or 'latn' is used. * See https://www.microsoft.com/typography/otspec/scripttags.htm * @property {string} [language='dflt'] - language system used to determine which features to apply. * See https://www.microsoft.com/typography/developers/opentype/languagetags.aspx * @property {boolean} [kerning=true] - whether to include kerning values * @property {object} [features] - OpenType Layout feature tags. Used to enable or disable the features of the given script/language system. * See https://www.microsoft.com/typography/otspec/featuretags.htm */ Font.prototype.defaultRenderOptions = { kerning: true, features: { liga: true, rlig: true } }; /** * Helper function that invokes the given callback for each glyph in the given text. * The callback gets `(glyph, x, y, fontSize, options)`.* @param {string} text * @param {string} text - The text to apply. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @param {Function} callback */ Font.prototype.forEachGlyph = function(text, x, y, fontSize, options, callback) { var this$1 = this; x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize !== undefined ? fontSize : 72; options = options || this.defaultRenderOptions; var fontScale = 1 / this.unitsPerEm * fontSize; var glyphs = this.stringToGlyphs(text, options); for (var i = 0; i < glyphs.length; i += 1) { var glyph = glyphs[i]; callback.call(this$1, glyph, x, y, fontSize, options); if (glyph.advanceWidth) { x += glyph.advanceWidth * fontScale; } if (options.kerning && i < glyphs.length - 1) { var kerningValue = this$1.getKerningValue(glyph, glyphs[i + 1]); x += kerningValue * fontScale; } if (options.letterSpacing) { x += options.letterSpacing * fontSize; } else if (options.tracking) { x += (options.tracking / 1000) * fontSize; } } return x; }; /** * Create a Path object that represents the given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path} */ Font.prototype.getPath = function(text, x, y, fontSize, options) { var fullPath = new Path(); this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); fullPath.extend(glyphPath); }); return fullPath; }; /** * Create an array of Path objects that represent the glyphs of a given text. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return {opentype.Path[]} */ Font.prototype.getPaths = function(text, x, y, fontSize, options) { var glyphPaths = []; this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { var glyphPath = glyph.getPath(gX, gY, gFontSize, options, this); glyphPaths.push(glyphPath); }); return glyphPaths; }; /** * Returns the advance width of a text. * * This is something different than Path.getBoundingBox() as for example a * suffixed whitespace increases the advanceWidth but not the bounding box * or an overhanging letter like a calligraphic 'f' might have a quite larger * bounding box than its advance width. * * This corresponds to canvas2dContext.measureText(text).width * * @param {string} text - The text to create. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options * @return advance width */ Font.prototype.getAdvanceWidth = function(text, fontSize, options) { return this.forEachGlyph(text, 0, 0, fontSize, options, function() {}); }; /** * Draw the text on the given drawing context. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.draw = function(ctx, text, x, y, fontSize, options) { this.getPath(text, x, y, fontSize, options).draw(ctx); }; /** * Draw the points of all glyphs in the text. * On-curve points will be drawn in blue, off-curve points will be drawn in red. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawPoints = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawPoints(ctx, gX, gY, gFontSize); }); }; /** * Draw lines indicating important font measurements for all glyphs in the text. * Black lines indicate the origin of the coordinate system (point 0,0). * Blue lines indicate the glyph bounding box. * Green line indicates the advance width of the glyph. * @param {CanvasRenderingContext2D} ctx - A 2D drawing context, like Canvas. * @param {string} text - The text to create. * @param {number} [x=0] - Horizontal position of the beginning of the text. * @param {number} [y=0] - Vertical position of the *baseline* of the text. * @param {number} [fontSize=72] - Font size in pixels. We scale the glyph units by `1 / unitsPerEm * fontSize`. * @param {GlyphRenderOptions=} options */ Font.prototype.drawMetrics = function(ctx, text, x, y, fontSize, options) { this.forEachGlyph(text, x, y, fontSize, options, function(glyph, gX, gY, gFontSize) { glyph.drawMetrics(ctx, gX, gY, gFontSize); }); }; /** * @param {string} * @return {string} */ Font.prototype.getEnglishName = function(name) { var translations = this.names[name]; if (translations) { return translations.en; } }; /** * Validate */ Font.prototype.validate = function() { var warnings = []; var _this = this; function assert(predicate, message) { if (!predicate) { warnings.push(message); } } function assertNamePresent(name) { var englishName = _this.getEnglishName(name); assert(englishName && englishName.trim().length > 0, 'No English ' + name + ' specified.'); } // Identification information assertNamePresent('fontFamily'); assertNamePresent('weightName'); assertNamePresent('manufacturer'); assertNamePresent('copyright'); assertNamePresent('version'); // Dimension information assert(this.unitsPerEm > 0, 'No unitsPerEm specified.'); }; /** * Convert the font object to a SFNT data structure. * This structure contains all the necessary tables and metadata to create a binary OTF file. * @return {opentype.Table} */ Font.prototype.toTables = function() { return sfnt.fontToTable(this); }; /** * @deprecated Font.toBuffer is deprecated. Use Font.toArrayBuffer instead. */ Font.prototype.toBuffer = function() { console.warn('Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.'); return this.toArrayBuffer(); }; /** * Converts a `opentype.Font` into an `ArrayBuffer` * @return {ArrayBuffer} */ Font.prototype.toArrayBuffer = function() { var sfntTable = this.toTables(); var bytes = sfntTable.encode(); var buffer = new ArrayBuffer(bytes.length); var intArray = new Uint8Array(buffer); for (var i = 0; i < bytes.length; i++) { intArray[i] = bytes[i]; } return buffer; }; /** * Initiate a download of the OpenType font. */ Font.prototype.download = function(fileName) { var familyName = this.getEnglishName('fontFamily'); var styleName = this.getEnglishName('fontSubfamily'); fileName = fileName || familyName.replace(/\s/g, '') + '-' + styleName + '.otf'; var arrayBuffer = this.toArrayBuffer(); if (isBrowser()) { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, arrayBuffer.byteLength, function(fs) { fs.root.getFile(fileName, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { var dataView = new DataView(arrayBuffer); var blob = new Blob([dataView], {type: 'font/opentype'}); writer.write(blob); writer.addEventListener('writeend', function() { // Navigating to the file will download it. location.href = fileEntry.toURL(); }, false); }); }); }, function(err) { throw new Error(err.name + ': ' + err.message); }); } else { var fs = _dereq_('fs'); var buffer = arrayBufferToNodeBuffer(arrayBuffer); fs.writeFileSync(fileName, buffer); } }; /** * @private */ Font.prototype.fsSelectionValues = { ITALIC: 0x001, //1 UNDERSCORE: 0x002, //2 NEGATIVE: 0x004, //4 OUTLINED: 0x008, //8 STRIKEOUT: 0x010, //16 BOLD: 0x020, //32 REGULAR: 0x040, //64 USER_TYPO_METRICS: 0x080, //128 WWS: 0x100, //256 OBLIQUE: 0x200 //512 }; /** * @private */ Font.prototype.usWidthClasses = { ULTRA_CONDENSED: 1, EXTRA_CONDENSED: 2, CONDENSED: 3, SEMI_CONDENSED: 4, MEDIUM: 5, SEMI_EXPANDED: 6, EXPANDED: 7, EXTRA_EXPANDED: 8, ULTRA_EXPANDED: 9 }; /** * @private */ Font.prototype.usWeightClasses = { THIN: 100, EXTRA_LIGHT: 200, LIGHT: 300, NORMAL: 400, MEDIUM: 500, SEMI_BOLD: 600, BOLD: 700, EXTRA_BOLD: 800, BLACK: 900 }; // The `fvar` table stores font variation axes and instances. // https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6fvar.html function addName(name, names) { var nameString = JSON.stringify(name); var nameID = 256; for (var nameKey in names) { var n = parseInt(nameKey); if (!n || n < 256) { continue; } if (JSON.stringify(names[nameKey]) === nameString) { return n; } if (nameID <= n) { nameID = n + 1; } } names[nameID] = name; return nameID; } function makeFvarAxis(n, axis, names) { var nameID = addName(axis.name, names); return [ {name: 'tag_' + n, type: 'TAG', value: axis.tag}, {name: 'minValue_' + n, type: 'FIXED', value: axis.minValue << 16}, {name: 'defaultValue_' + n, type: 'FIXED', value: axis.defaultValue << 16}, {name: 'maxValue_' + n, type: 'FIXED', value: axis.maxValue << 16}, {name: 'flags_' + n, type: 'USHORT', value: 0}, {name: 'nameID_' + n, type: 'USHORT', value: nameID} ]; } function parseFvarAxis(data, start, names) { var axis = {}; var p = new parse.Parser(data, start); axis.tag = p.parseTag(); axis.minValue = p.parseFixed(); axis.defaultValue = p.parseFixed(); axis.maxValue = p.parseFixed(); p.skip('uShort', 1); // reserved for flags; no values defined axis.name = names[p.parseUShort()] || {}; return axis; } function makeFvarInstance(n, inst, axes, names) { var nameID = addName(inst.name, names); var fields = [ {name: 'nameID_' + n, type: 'USHORT', value: nameID}, {name: 'flags_' + n, type: 'USHORT', value: 0} ]; for (var i = 0; i < axes.length; ++i) { var axisTag = axes[i].tag; fields.push({ name: 'axis_' + n + ' ' + axisTag, type: 'FIXED', value: inst.coordinates[axisTag] << 16 }); } return fields; } function parseFvarInstance(data, start, axes, names) { var inst = {}; var p = new parse.Parser(data, start); inst.name = names[p.parseUShort()] || {}; p.skip('uShort', 1); // reserved for flags; no values defined inst.coordinates = {}; for (var i = 0; i < axes.length; ++i) { inst.coordinates[axes[i].tag] = p.parseFixed(); } return inst; } function makeFvarTable(fvar, names) { var result = new table.Table('fvar', [ {name: 'version', type: 'ULONG', value: 0x10000}, {name: 'offsetToData', type: 'USHORT', value: 0}, {name: 'countSizePairs', type: 'USHORT', value: 2}, {name: 'axisCount', type: 'USHORT', value: fvar.axes.length}, {name: 'axisSize', type: 'USHORT', value: 20}, {name: 'instanceCount', type: 'USHORT', value: fvar.instances.length}, {name: 'instanceSize', type: 'USHORT', value: 4 + fvar.axes.length * 4} ]); result.offsetToData = result.sizeOf(); for (var i = 0; i < fvar.axes.length; i++) { result.fields = result.fields.concat(makeFvarAxis(i, fvar.axes[i], names)); } for (var j = 0; j < fvar.instances.length; j++) { result.fields = result.fields.concat(makeFvarInstance(j, fvar.instances[j], fvar.axes, names)); } return result; } function parseFvarTable(data, start, names) { var p = new parse.Parser(data, start); var tableVersion = p.parseULong(); check.argument(tableVersion === 0x00010000, 'Unsupported fvar table version.'); var offsetToData = p.parseOffset16(); // Skip countSizePairs. p.skip('uShort', 1); var axisCount = p.parseUShort(); var axisSize = p.parseUShort(); var instanceCount = p.parseUShort(); var instanceSize = p.parseUShort(); var axes = []; for (var i = 0; i < axisCount; i++) { axes.push(parseFvarAxis(data, start + offsetToData + i * axisSize, names)); } var instances = []; var instanceStart = start + offsetToData + axisCount * axisSize; for (var j = 0; j < instanceCount; j++) { instances.push(parseFvarInstance(data, instanceStart + j * instanceSize, axes, names)); } return {axes: axes, instances: instances}; } var fvar = { make: makeFvarTable, parse: parseFvarTable }; // The `GPOS` table contains kerning pairs, among other things. // https://www.microsoft.com/typography/OTSPEC/gpos.htm // Parse ScriptList and FeatureList tables of GPOS, GSUB, GDEF, BASE, JSTF tables. // These lists are unused by now, this function is just the basis for a real parsing. function parseTaggedListTable(data, start) { var p = new parse.Parser(data, start); var n = p.parseUShort(); var list = []; for (var i = 0; i < n; i++) { list[p.parseTag()] = { offset: p.parseUShort() }; } return list; } // Parse a coverage table in a GSUB, GPOS or GDEF table. // Format 1 is a simple list of glyph ids, // Format 2 is a list of ranges. It is expanded in a list of glyphs, maybe not the best idea. function parseCoverageTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); var count = p.parseUShort(); if (format === 1) { return p.parseUShortList(count); } else if (format === 2) { var coverage = []; for (; count--;) { var begin = p.parseUShort(); var end = p.parseUShort(); var index = p.parseUShort(); for (var i = begin; i <= end; i++) { coverage[index++] = i; } } return coverage; } } // Parse a Class Definition Table in a GSUB, GPOS or GDEF table. // Returns a function that gets a class value from a glyph ID. function parseClassDefTable(data, start) { var p = new parse.Parser(data, start); var format = p.parseUShort(); if (format === 1) { // Format 1 specifies a range of consecutive glyph indices, one class per glyph ID. var startGlyph = p.parseUShort(); var glyphCount = p.parseUShort(); var classes = p.parseUShortList(glyphCount); return function(glyphID) { return classes[glyphID - startGlyph] || 0; }; } else if (format === 2) { // Format 2 defines multiple groups of glyph indices that belong to the same class. var rangeCount = p.parseUShort(); var startGlyphs = []; var endGlyphs = []; var classValues = []; for (var i = 0; i < rangeCount; i++) { startGlyphs[i] = p.parseUShort(); endGlyphs[i] = p.parseUShort(); classValues[i] = p.parseUShort(); } return function(glyphID) { var l = 0; var r = startGlyphs.length - 1; while (l < r) { var c = (l + r + 1) >> 1; if (glyphID < startGlyphs[c]) { r = c - 1; } else { l = c; } } if (startGlyphs[l] <= glyphID && glyphID <= endGlyphs[l]) { return classValues[l] || 0; } return 0; }; } } // Parse a pair adjustment positioning subtable, format 1 or format 2 // The subtable is returned in the form of a lookup function. function parsePairPosSubTable(data, start) { var p = new parse.Parser(data, start); // This part is common to format 1 and format 2 subtables var format = p.parseUShort(); var coverageOffset = p.parseUShort(); var coverage = parseCoverageTable(data, start + coverageOffset); // valueFormat 4: XAdvance only, 1: XPlacement only, 0: no ValueRecord for second glyph // Only valueFormat1=4 and valueFormat2=0 is supported. var valueFormat1 = p.parseUShort(); var valueFormat2 = p.parseUShort(); var value1; var value2; if (valueFormat1 !== 4 || valueFormat2 !== 0) { return; } var sharedPairSets = {}; if (format === 1) { // Pair Positioning Adjustment: Format 1 var pairSetCount = p.parseUShort(); var pairSet = []; // Array of offsets to PairSet tables-from beginning of PairPos subtable-ordered by Coverage Index var pairSetOffsets = p.parseOffset16List(pairSetCount); for (var firstGlyph = 0; firstGlyph < pairSetCount; firstGlyph++) { var pairSetOffset = pairSetOffsets[firstGlyph]; var sharedPairSet = sharedPairSets[pairSetOffset]; if (!sharedPairSet) { // Parse a pairset table in a pair adjustment subtable format 1 sharedPairSet = {}; p.relativeOffset = pairSetOffset; var pairValueCount = p.parseUShort(); for (; pairValueCount--;) { var secondGlyph = p.parseUShort(); if (valueFormat1) { value1 = p.parseShort(); } if (valueFormat2) { value2 = p.parseShort(); } // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. sharedPairSet[secondGlyph] = value1; } } pairSet[coverage[firstGlyph]] = sharedPairSet; } return function(leftGlyph, rightGlyph) { var pairs = pairSet[leftGlyph]; if (pairs) { return pairs[rightGlyph]; } }; } else if (format === 2) { // Pair Positioning Adjustment: Format 2 var classDef1Offset = p.parseUShort(); var classDef2Offset = p.parseUShort(); var class1Count = p.parseUShort(); var class2Count = p.parseUShort(); var getClass1 = parseClassDefTable(data, start + classDef1Offset); var getClass2 = parseClassDefTable(data, start + classDef2Offset); // Parse kerning values by class pair. var kerningMatrix = []; for (var i = 0; i < class1Count; i++) { var kerningRow = kerningMatrix[i] = []; for (var j = 0; j < class2Count; j++) { if (valueFormat1) { value1 = p.parseShort(); } if (valueFormat2) { value2 = p.parseShort(); } // We only support valueFormat1 = 4 and valueFormat2 = 0, // so value1 is the XAdvance and value2 is empty. kerningRow[j] = value1; } } // Convert coverage list to a hash var covered = {}; for (var i$1 = 0; i$1 < coverage.length; i$1++) { covered[coverage[i$1]] = 1; } // Get the kerning value for a specific glyph pair. return function(leftGlyph, rightGlyph) { if (!covered[leftGlyph]) { return; } var class1 = getClass1(leftGlyph); var class2 = getClass2(rightGlyph); var kerningRow = kerningMatrix[class1]; if (kerningRow) { return kerningRow[class2]; } }; } } // Parse a LookupTable (present in of GPOS, GSUB, GDEF, BASE, JSTF tables). function parseLookupTable(data, start) { var p = new parse.Parser(data, start); var lookupType = p.parseUShort(); var lookupFlag = p.parseUShort(); var useMarkFilteringSet = lookupFlag & 0x10; var subTableCount = p.parseUShort(); var subTableOffsets = p.parseOffset16List(subTableCount); var table = { lookupType: lookupType, lookupFlag: lookupFlag, markFilteringSet: useMarkFilteringSet ? p.parseUShort() : -1 }; // LookupType 2, Pair adjustment if (lookupType === 2) { var subtables = []; for (var i = 0; i < subTableCount; i++) { var pairPosSubTable = parsePairPosSubTable(data, start + subTableOffsets[i]); if (pairPosSubTable) { subtables.push(pairPosSubTable); } } // Return a function which finds the kerning values in the subtables. table.getKerningValue = function(leftGlyph, rightGlyph) { for (var i = subtables.length; i--;) { var value = subtables[i](leftGlyph, rightGlyph); if (value !== undefined) { return value; } } return 0; }; } return table; } // Parse the `GPOS` table which contains, among other things, kerning pairs. // https://www.microsoft.com/typography/OTSPEC/gpos.htm function parseGposTable(data, start, font) { var p = new parse.Parser(data, start); var tableVersion = p.parseFixed(); check.argument(tableVersion === 1, 'Unsupported GPOS table version.'); // ScriptList and FeatureList - ignored for now parseTaggedListTable(data, start + p.parseUShort()); // 'kern' is the feature we are looking for. parseTaggedListTable(data, start + p.parseUShort()); // LookupList var lookupListOffset = p.parseUShort(); p.relativeOffset = lookupListOffset; var lookupCount = p.parseUShort(); var lookupTableOffsets = p.parseOffset16List(lookupCount); var lookupListAbsoluteOffset = start + lookupListOffset; for (var i = 0; i < lookupCount; i++) { var table = parseLookupTable(data, lookupListAbsoluteOffset + lookupTableOffsets[i]); if (table.lookupType === 2 && !font.getGposKerningValue) { font.getGposKerningValue = table.getKerningValue; } } } var gpos = { parse: parseGposTable }; // The `kern` table contains kerning pairs. // Note that some fonts use the GPOS OpenType layout table to specify kerning. // https://www.microsoft.com/typography/OTSPEC/kern.htm function parseWindowsKernTable(p) { var pairs = {}; // Skip nTables. p.skip('uShort'); var subtableVersion = p.parseUShort(); check.argument(subtableVersion === 0, 'Unsupported kern sub-table version.'); // Skip subtableLength, subtableCoverage p.skip('uShort', 2); var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } return pairs; } function parseMacKernTable(p) { var pairs = {}; // The Mac kern table stores the version as a fixed (32 bits) but we only loaded the first 16 bits. // Skip the rest. p.skip('uShort'); var nTables = p.parseULong(); //check.argument(nTables === 1, 'Only 1 subtable is supported (got ' + nTables + ').'); if (nTables > 1) { console.warn('Only the first kern subtable is supported.'); } p.skip('uLong'); var coverage = p.parseUShort(); var subtableVersion = coverage & 0xFF; p.skip('uShort'); if (subtableVersion === 0) { var nPairs = p.parseUShort(); // Skip searchRange, entrySelector, rangeShift. p.skip('uShort', 3); for (var i = 0; i < nPairs; i += 1) { var leftIndex = p.parseUShort(); var rightIndex = p.parseUShort(); var value = p.parseShort(); pairs[leftIndex + ',' + rightIndex] = value; } } return pairs; } // Parse the `kern` table which contains kerning pairs. function parseKernTable(data, start) { var p = new parse.Parser(data, start); var tableVersion = p.parseUShort(); if (tableVersion === 0) { return parseWindowsKernTable(p); } else if (tableVersion === 1) { return parseMacKernTable(p); } else { throw new Error('Unsupported kern table version (' + tableVersion + ').'); } } var kern = { parse: parseKernTable }; // The `loca` table stores the offsets to the locations of the glyphs in the font. // https://www.microsoft.com/typography/OTSPEC/loca.htm // Parse the `loca` table. This table stores the offsets to the locations of the glyphs in the font, // relative to the beginning of the glyphData table. // The number of glyphs stored in the `loca` table is specified in the `maxp` table (under numGlyphs) // The loca table has two versions: a short version where offsets are stored as uShorts, and a long // version where offsets are stored as uLongs. The `head` table specifies which version to use // (under indexToLocFormat). function parseLocaTable(data, start, numGlyphs, shortVersion) { var p = new parse.Parser(data, start); var parseFn = shortVersion ? p.parseUShort : p.parseULong; // There is an extra entry after the last index element to compute the length of the last glyph. // That's why we use numGlyphs + 1. var glyphOffsets = []; for (var i = 0; i < numGlyphs + 1; i += 1) { var glyphOffset = parseFn.call(p); if (shortVersion) { // The short table version stores the actual offset divided by 2. glyphOffset *= 2; } glyphOffsets.push(glyphOffset); } return glyphOffsets; } var loca = { parse: parseLocaTable }; // opentype.js // https://github.com/nodebox/opentype.js // (c) 2015 Frederik De Bleser // opentype.js may be freely distributed under the MIT license. /* global DataView, Uint8Array, XMLHttpRequest */ /** * The opentype library. * @namespace opentype */ // File loaders ///////////////////////////////////////////////////////// /** * Loads a font from a file. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} path - The path of the file * @param {Function} callback - The function to call when the font load completes */ function loadFromFile(path, callback) { var fs = _dereq_('fs'); fs.readFile(path, function(err, buffer) { if (err) { return callback(err.message); } callback(null, nodeBufferToArrayBuffer(buffer)); }); } /** * Loads a font from a URL. The callback throws an error message as the first parameter if it fails * and the font as an ArrayBuffer in the second parameter if it succeeds. * @param {string} url - The URL of the font file. * @param {Function} callback - The function to call when the font load completes */ function loadFromUrl(url, callback) { var request = new XMLHttpRequest(); request.open('get', url, true); request.responseType = 'arraybuffer'; request.onload = function() { if (request.status !== 200) { return callback('Font could not be loaded: ' + request.statusText); } return callback(null, request.response); }; request.onerror = function () { callback('Font could not be loaded'); }; request.send(); } // Table Directory Entries ////////////////////////////////////////////// /** * Parses OpenType table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseOpenTypeTableEntries(data, numTables) { var tableEntries = []; var p = 12; for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var checksum = parse.getULong(data, p + 4); var offset = parse.getULong(data, p + 8); var length = parse.getULong(data, p + 12); tableEntries.push({tag: tag, checksum: checksum, offset: offset, length: length, compression: false}); p += 16; } return tableEntries; } /** * Parses WOFF table entries. * @param {DataView} * @param {Number} * @return {Object[]} */ function parseWOFFTableEntries(data, numTables) { var tableEntries = []; var p = 44; // offset to the first table directory entry. for (var i = 0; i < numTables; i += 1) { var tag = parse.getTag(data, p); var offset = parse.getULong(data, p + 4); var compLength = parse.getULong(data, p + 8); var origLength = parse.getULong(data, p + 12); var compression = (void 0); if (compLength < origLength) { compression = 'WOFF'; } else { compression = false; } tableEntries.push({tag: tag, offset: offset, compression: compression, compressedLength: compLength, length: origLength}); p += 20; } return tableEntries; } /** * @typedef TableData * @type Object * @property {DataView} data - The DataView * @property {number} offset - The data offset. */ /** * @param {DataView} * @param {Object} * @return {TableData} */ function uncompressTable(data, tableEntry) { if (tableEntry.compression === 'WOFF') { var inBuffer = new Uint8Array(data.buffer, tableEntry.offset + 2, tableEntry.compressedLength - 2); var outBuffer = new Uint8Array(tableEntry.length); index(inBuffer, outBuffer); if (outBuffer.byteLength !== tableEntry.length) { throw new Error('Decompression error: ' + tableEntry.tag + ' decompressed length doesn\'t match recorded length'); } var view = new DataView(outBuffer.buffer, 0); return {data: view, offset: 0}; } else { return {data: data, offset: tableEntry.offset}; } } // Public API /////////////////////////////////////////////////////////// /** * Parse the OpenType file data (as an ArrayBuffer) and return a Font object. * Throws an error if the font could not be parsed. * @param {ArrayBuffer} * @return {opentype.Font} */ function parseBuffer(buffer) { var indexToLocFormat; var ltagTable; // Since the constructor can also be called to create new fonts from scratch, we indicate this // should be an empty font that we'll fill with our own data. var font = new Font({empty: true}); // OpenType fonts use big endian byte ordering. // We can't rely on typed array view types, because they operate with the endianness of the host computer. // Instead we use DataViews where we can specify endianness. var data = new DataView(buffer, 0); var numTables; var tableEntries = []; var signature = parse.getTag(data, 0); if (signature === String.fromCharCode(0, 1, 0, 0) || signature === 'true' || signature === 'typ1') { font.outlinesFormat = 'truetype'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'OTTO') { font.outlinesFormat = 'cff'; numTables = parse.getUShort(data, 4); tableEntries = parseOpenTypeTableEntries(data, numTables); } else if (signature === 'wOFF') { var flavor = parse.getTag(data, 4); if (flavor === String.fromCharCode(0, 1, 0, 0)) { font.outlinesFormat = 'truetype'; } else if (flavor === 'OTTO') { font.outlinesFormat = 'cff'; } else { throw new Error('Unsupported OpenType flavor ' + signature); } numTables = parse.getUShort(data, 12); tableEntries = parseWOFFTableEntries(data, numTables); } else { throw new Error('Unsupported OpenType signature ' + signature); } var cffTableEntry; var fvarTableEntry; var glyfTableEntry; var gposTableEntry; var gsubTableEntry; var hmtxTableEntry; var kernTableEntry; var locaTableEntry; var nameTableEntry; var metaTableEntry; var p; for (var i = 0; i < numTables; i += 1) { var tableEntry = tableEntries[i]; var table = (void 0); switch (tableEntry.tag) { case 'cmap': table = uncompressTable(data, tableEntry); font.tables.cmap = cmap.parse(table.data, table.offset); font.encoding = new CmapEncoding(font.tables.cmap); break; case 'cvt ' : table = uncompressTable(data, tableEntry); p = new parse.Parser(table.data, table.offset); font.tables.cvt = p.parseShortList(tableEntry.length / 2); break; case 'fvar': fvarTableEntry = tableEntry; break; case 'fpgm' : table = uncompressTable(data, tableEntry); p = new parse.Parser(table.data, table.offset); font.tables.fpgm = p.parseByteList(tableEntry.length); break; case 'head': table = uncompressTable(data, tableEntry); font.tables.head = head.parse(table.data, table.offset); font.unitsPerEm = font.tables.head.unitsPerEm; indexToLocFormat = font.tables.head.indexToLocFormat; break; case 'hhea': table = uncompressTable(data, tableEntry); font.tables.hhea = hhea.parse(table.data, table.offset); font.ascender = font.tables.hhea.ascender; font.descender = font.tables.hhea.descender; font.numberOfHMetrics = font.tables.hhea.numberOfHMetrics; break; case 'hmtx': hmtxTableEntry = tableEntry; break; case 'ltag': table = uncompressTable(data, tableEntry); ltagTable = ltag.parse(table.data, table.offset); break; case 'maxp': table = uncompressTable(data, tableEntry); font.tables.maxp = maxp.parse(table.data, table.offset); font.numGlyphs = font.tables.maxp.numGlyphs; break; case 'name': nameTableEntry = tableEntry; break; case 'OS/2': table = uncompressTable(data, tableEntry); font.tables.os2 = os2.parse(table.data, table.offset); break; case 'post': table = uncompressTable(data, tableEntry); font.tables.post = post.parse(table.data, table.offset); font.glyphNames = new GlyphNames(font.tables.post); break; case 'prep' : table = uncompressTable(data, tableEntry); p = new parse.Parser(table.data, table.offset); font.tables.prep = p.parseByteList(tableEntry.length); break; case 'glyf': glyfTableEntry = tableEntry; break; case 'loca': locaTableEntry = tableEntry; break; case 'CFF ': cffTableEntry = tableEntry; break; case 'kern': kernTableEntry = tableEntry; break; case 'GPOS': gposTableEntry = tableEntry; break; case 'GSUB': gsubTableEntry = tableEntry; break; case 'meta': metaTableEntry = tableEntry; break; } } var nameTable = uncompressTable(data, nameTableEntry); font.tables.name = _name.parse(nameTable.data, nameTable.offset, ltagTable); font.names = font.tables.name; if (glyfTableEntry && locaTableEntry) { var shortVersion = indexToLocFormat === 0; var locaTable = uncompressTable(data, locaTableEntry); var locaOffsets = loca.parse(locaTable.data, locaTable.offset, font.numGlyphs, shortVersion); var glyfTable = uncompressTable(data, glyfTableEntry); font.glyphs = glyf.parse(glyfTable.data, glyfTable.offset, locaOffsets, font); } else if (cffTableEntry) { var cffTable = uncompressTable(data, cffTableEntry); cff.parse(cffTable.data, cffTable.offset, font); } else { throw new Error('Font doesn\'t contain TrueType or CFF outlines.'); } var hmtxTable = uncompressTable(data, hmtxTableEntry); hmtx.parse(hmtxTable.data, hmtxTable.offset, font.numberOfHMetrics, font.numGlyphs, font.glyphs); addGlyphNames(font); if (kernTableEntry) { var kernTable = uncompressTable(data, kernTableEntry); font.kerningPairs = kern.parse(kernTable.data, kernTable.offset); } else { font.kerningPairs = {}; } if (gposTableEntry) { var gposTable = uncompressTable(data, gposTableEntry); gpos.parse(gposTable.data, gposTable.offset, font); } if (gsubTableEntry) { var gsubTable = uncompressTable(data, gsubTableEntry); font.tables.gsub = gsub.parse(gsubTable.data, gsubTable.offset); } if (fvarTableEntry) { var fvarTable = uncompressTable(data, fvarTableEntry); font.tables.fvar = fvar.parse(fvarTable.data, fvarTable.offset, font.names); } if (metaTableEntry) { var metaTable = uncompressTable(data, metaTableEntry); font.tables.meta = meta.parse(metaTable.data, metaTable.offset); font.metas = font.tables.meta; } return font; } /** * Asynchronously load the font from a URL or a filesystem. When done, call the callback * with two arguments `(err, font)`. The `err` will be null on success, * the `font` is a Font object. * We use the node.js callback convention so that * opentype.js can integrate with frameworks like async.js. * @alias opentype.load * @param {string} url - The URL of the font to load. * @param {Function} callback - The callback. */ function load(url, callback) { var isNode$$1 = typeof window === 'undefined'; var loadFn = isNode$$1 ? loadFromFile : loadFromUrl; loadFn(url, function(err, arrayBuffer) { if (err) { return callback(err); } var font; try { font = parseBuffer(arrayBuffer); } catch (e) { return callback(e, null); } return callback(null, font); }); } /** * Synchronously load the font from a URL or file. * When done, returns the font object or throws an error. * @alias opentype.loadSync * @param {string} url - The URL of the font to load. * @return {opentype.Font} */ function loadSync(url) { var fs = _dereq_('fs'); var buffer = fs.readFileSync(url); return parseBuffer(nodeBufferToArrayBuffer(buffer)); } exports.Font = Font; exports.Glyph = Glyph; exports.Path = Path; exports.BoundingBox = BoundingBox; exports._parse = parse; exports.parse = parseBuffer; exports.load = load; exports.loadSync = loadSync; Object.defineProperty(exports, '__esModule', { value: true }); }))); }).call(this,_dereq_("buffer").Buffer) },{"buffer":4,"fs":3}],11:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],12:[function(_dereq_,module,exports){ (function(self) { 'use strict'; if (self.fetch) { return } var support = { searchParams: 'URLSearchParams' in self, iterable: 'Symbol' in self && 'iterator' in Symbol, blob: 'FileReader' in self && 'Blob' in self && (function() { try { new Blob() return true } catch(e) { return false } })(), formData: 'FormData' in self, arrayBuffer: 'ArrayBuffer' in self } if (support.arrayBuffer) { var viewClasses = [ '[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]' ] var isDataView = function(obj) { return obj && DataView.prototype.isPrototypeOf(obj) } var isArrayBufferView = ArrayBuffer.isView || function(obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 } } function normalizeName(name) { if (typeof name !== 'string') { name = String(name) } if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name') } return name.toLowerCase() } function normalizeValue(value) { if (typeof value !== 'string') { value = String(value) } return value } // Build a destructive iterator for the value list function iteratorFor(items) { var iterator = { next: function() { var value = items.shift() return {done: value === undefined, value: value} } } if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator } } return iterator } function Headers(headers) { this.map = {} if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value) }, this) } else if (Array.isArray(headers)) { headers.forEach(function(header) { this.append(header[0], header[1]) }, this) } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]) }, this) } } Headers.prototype.append = function(name, value) { name = normalizeName(name) value = normalizeValue(value) var oldValue = this.map[name] this.map[name] = oldValue ? oldValue+','+value : value } Headers.prototype['delete'] = function(name) { delete this.map[normalizeName(name)] } Headers.prototype.get = function(name) { name = normalizeName(name) return this.has(name) ? this.map[name] : null } Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) } Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = normalizeValue(value) } Headers.prototype.forEach = function(callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { callback.call(thisArg, this.map[name], name, this) } } } Headers.prototype.keys = function() { var items = [] this.forEach(function(value, name) { items.push(name) }) return iteratorFor(items) } Headers.prototype.values = function() { var items = [] this.forEach(function(value) { items.push(value) }) return iteratorFor(items) } Headers.prototype.entries = function() { var items = [] this.forEach(function(value, name) { items.push([name, value]) }) return iteratorFor(items) } if (support.iterable) { Headers.prototype[Symbol.iterator] = Headers.prototype.entries } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')) } body.bodyUsed = true } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result) } reader.onerror = function() { reject(reader.error) } }) } function readBlobAsArrayBuffer(blob) { var reader = new FileReader() var promise = fileReaderReady(reader) reader.readAsArrayBuffer(blob) return promise } function readBlobAsText(blob) { var reader = new FileReader() var promise = fileReaderReady(reader) reader.readAsText(blob) return promise } function readArrayBufferAsText(buf) { var view = new Uint8Array(buf) var chars = new Array(view.length) for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]) } return chars.join('') } function bufferClone(buf) { if (buf.slice) { return buf.slice(0) } else { var view = new Uint8Array(buf.byteLength) view.set(new Uint8Array(buf)) return view.buffer } } function Body() { this.bodyUsed = false this._initBody = function(body) { this._bodyInit = body if (!body) { this._bodyText = '' } else if (typeof body === 'string') { this._bodyText = body } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this._bodyText = body.toString() } else if (support.arrayBuffer && support.blob && isDataView(body)) { this._bodyArrayBuffer = bufferClone(body.buffer) // IE 10-11 can't handle a DataView body. this._bodyInit = new Blob([this._bodyArrayBuffer]) } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) { this._bodyArrayBuffer = bufferClone(body) } else { throw new Error('unsupported BodyInit type') } if (!this.headers.get('content-type')) { if (typeof body === 'string') { this.headers.set('content-type', 'text/plain;charset=UTF-8') } else if (this._bodyBlob && this._bodyBlob.type) { this.headers.set('content-type', this._bodyBlob.type) } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8') } } } if (support.blob) { this.blob = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(new Blob([this._bodyArrayBuffer])) } else if (this._bodyFormData) { throw new Error('could not read FormData body as blob') } else { return Promise.resolve(new Blob([this._bodyText])) } } this.arrayBuffer = function() { if (this._bodyArrayBuffer) { return consumed(this) || Promise.resolve(this._bodyArrayBuffer) } else { return this.blob().then(readBlobAsArrayBuffer) } } } this.text = function() { var rejected = consumed(this) if (rejected) { return rejected } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob) } else if (this._bodyArrayBuffer) { return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)) } else if (this._bodyFormData) { throw new Error('could not read FormData body as text') } else { return Promise.resolve(this._bodyText) } } if (support.formData) { this.formData = function() { return this.text().then(decode) } } this.json = function() { return this.text().then(JSON.parse) } return this } // HTTP methods whose capitalization should be normalized var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'] function normalizeMethod(method) { var upcased = method.toUpperCase() return (methods.indexOf(upcased) > -1) ? upcased : method } function Request(input, options) { options = options || {} var body = options.body if (input instanceof Request) { if (input.bodyUsed) { throw new TypeError('Already read') } this.url = input.url this.credentials = input.credentials if (!options.headers) { this.headers = new Headers(input.headers) } this.method = input.method this.mode = input.mode if (!body && input._bodyInit != null) { body = input._bodyInit input.bodyUsed = true } } else { this.url = String(input) } this.credentials = options.credentials || this.credentials || 'omit' if (options.headers || !this.headers) { this.headers = new Headers(options.headers) } this.method = normalizeMethod(options.method || this.method || 'GET') this.mode = options.mode || this.mode || null this.referrer = null if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests') } this._initBody(body) } Request.prototype.clone = function() { return new Request(this, { body: this._bodyInit }) } function decode(body) { var form = new FormData() body.trim().split('&').forEach(function(bytes) { if (bytes) { var split = bytes.split('=') var name = split.shift().replace(/\+/g, ' ') var value = split.join('=').replace(/\+/g, ' ') form.append(decodeURIComponent(name), decodeURIComponent(value)) } }) return form } function parseHeaders(rawHeaders) { var headers = new Headers() rawHeaders.split(/\r?\n/).forEach(function(line) { var parts = line.split(':') var key = parts.shift().trim() if (key) { var value = parts.join(':').trim() headers.append(key, value) } }) return headers } Body.call(Request.prototype) function Response(bodyInit, options) { if (!options) { options = {} } this.type = 'default' this.status = 'status' in options ? options.status : 200 this.ok = this.status >= 200 && this.status < 300 this.statusText = 'statusText' in options ? options.statusText : 'OK' this.headers = new Headers(options.headers) this.url = options.url || '' this._initBody(bodyInit) } Body.call(Response.prototype) Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers(this.headers), url: this.url }) } Response.error = function() { var response = new Response(null, {status: 0, statusText: ''}) response.type = 'error' return response } var redirectStatuses = [301, 302, 303, 307, 308] Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code') } return new Response(null, {status: status, headers: {location: url}}) } self.Headers = Headers self.Request = Request self.Response = Response self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init) var xhr = new XMLHttpRequest() xhr.onload = function() { var options = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || '') } options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') var body = 'response' in xhr ? xhr.response : xhr.responseText resolve(new Response(body, options)) } xhr.onerror = function() { reject(new TypeError('Network request failed')) } xhr.ontimeout = function() { reject(new TypeError('Network request failed')) } xhr.open(request.method, request.url, true) if (request.credentials === 'include') { xhr.withCredentials = true } if ('responseType' in xhr && support.blob) { xhr.responseType = 'blob' } request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value) }) xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit) }) } self.fetch.polyfill = true })(typeof self !== 'undefined' ? self : this); },{}],13:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('./core/core'); _dereq_('./color/p5.Color'); _dereq_('./core/p5.Element'); _dereq_('./typography/p5.Font'); _dereq_('./core/p5.Graphics'); _dereq_('./core/p5.Renderer2D'); _dereq_('./image/p5.Image'); _dereq_('./math/p5.Vector'); _dereq_('./io/p5.TableRow'); _dereq_('./io/p5.Table'); _dereq_('./io/p5.XML'); _dereq_('./color/creating_reading'); _dereq_('./color/setting'); _dereq_('./core/constants'); _dereq_('./utilities/conversion'); _dereq_('./utilities/array_functions'); _dereq_('./utilities/string_functions'); _dereq_('./core/environment'); _dereq_('./image/image'); _dereq_('./image/loading_displaying'); _dereq_('./image/pixels'); _dereq_('./io/files'); _dereq_('./events/keyboard'); _dereq_('./events/acceleration'); //john _dereq_('./events/mouse'); _dereq_('./utilities/time_date'); _dereq_('./events/touch'); _dereq_('./math/math'); _dereq_('./math/calculation'); _dereq_('./math/random'); _dereq_('./math/noise'); _dereq_('./math/trigonometry'); _dereq_('./core/rendering'); _dereq_('./core/2d_primitives'); _dereq_('./core/attributes'); _dereq_('./core/curves'); _dereq_('./core/vertex'); _dereq_('./core/structure'); _dereq_('./core/transform'); _dereq_('./typography/attributes'); _dereq_('./typography/loading_displaying'); _dereq_('./data/p5.TypedDict'); _dereq_('./webgl/p5.RendererGL'); _dereq_('./webgl/p5.Geometry'); _dereq_('./webgl/p5.RendererGL.Retained'); _dereq_('./webgl/p5.RendererGL.Immediate'); _dereq_('./webgl/primitives'); _dereq_('./webgl/loading'); _dereq_('./webgl/p5.Matrix'); _dereq_('./webgl/material'); _dereq_('./webgl/light'); _dereq_('./webgl/p5.Shader'); _dereq_('./webgl/camera'); _dereq_('./webgl/interaction'); _dereq_('./core/init.js'); module.exports = p5; },{"./color/creating_reading":15,"./color/p5.Color":16,"./color/setting":17,"./core/2d_primitives":18,"./core/attributes":19,"./core/constants":21,"./core/core":22,"./core/curves":23,"./core/environment":24,"./core/init.js":26,"./core/p5.Element":27,"./core/p5.Graphics":28,"./core/p5.Renderer2D":30,"./core/rendering":31,"./core/structure":33,"./core/transform":34,"./core/vertex":35,"./data/p5.TypedDict":36,"./events/acceleration":37,"./events/keyboard":38,"./events/mouse":39,"./events/touch":40,"./image/image":42,"./image/loading_displaying":43,"./image/p5.Image":44,"./image/pixels":45,"./io/files":46,"./io/p5.Table":47,"./io/p5.TableRow":48,"./io/p5.XML":49,"./math/calculation":50,"./math/math":51,"./math/noise":52,"./math/p5.Vector":53,"./math/random":54,"./math/trigonometry":55,"./typography/attributes":56,"./typography/loading_displaying":57,"./typography/p5.Font":58,"./utilities/array_functions":59,"./utilities/conversion":60,"./utilities/string_functions":61,"./utilities/time_date":62,"./webgl/camera":63,"./webgl/interaction":64,"./webgl/light":65,"./webgl/loading":66,"./webgl/material":67,"./webgl/p5.Geometry":68,"./webgl/p5.Matrix":69,"./webgl/p5.RendererGL":72,"./webgl/p5.RendererGL.Immediate":70,"./webgl/p5.RendererGL.Retained":71,"./webgl/p5.Shader":73,"./webgl/primitives":75}],14:[function(_dereq_,module,exports){ /** * @module Conversion * @submodule Color Conversion * @for p5 * @requires core */ 'use strict'; /** * Conversions adapted from . * * In these functions, hue is always in the range [0,1); all other components * are in the range [0,1]. 'Brightness' and 'value' are used interchangeably. */ var p5 = _dereq_('../core/core'); p5.ColorConversion = {}; /** * Convert an HSBA array to HSLA. */ p5.ColorConversion._hsbaToHSLA = function(hsba) { var hue = hsba[0]; var sat = hsba[1]; var val = hsba[2]; // Calculate lightness. var li = (2 - sat) * val / 2; // Convert saturation. if (li !== 0) { if (li === 1) { sat = 0; } else if (li < 0.5) { sat = sat / (2 - sat); } else { sat = sat * val / (2 - li * 2); } } // Hue and alpha stay the same. return [hue, sat, li, hsba[3]]; }; /** * Convert an HSBA array to RGBA. */ p5.ColorConversion._hsbaToRGBA = function(hsba) { var hue = hsba[0] * 6; // We will split hue into 6 sectors. var sat = hsba[1]; var val = hsba[2]; var RGBA = []; if (sat === 0) { RGBA = [val, val, val, hsba[3]]; // Return early if grayscale. } else { var sector = Math.floor(hue); var tint1 = val * (1 - sat); var tint2 = val * (1 - sat * (hue - sector)); var tint3 = val * (1 - sat * (1 + sector - hue)); var red, green, blue; if (sector === 1) { // Yellow to green. red = tint2; green = val; blue = tint1; } else if (sector === 2) { // Green to cyan. red = tint1; green = val; blue = tint3; } else if (sector === 3) { // Cyan to blue. red = tint1; green = tint2; blue = val; } else if (sector === 4) { // Blue to magenta. red = tint3; green = tint1; blue = val; } else if (sector === 5) { // Magenta to red. red = val; green = tint1; blue = tint2; } else { // Red to yellow (sector could be 0 or 6). red = val; green = tint3; blue = tint1; } RGBA = [red, green, blue, hsba[3]]; } return RGBA; }; /** * Convert an HSLA array to HSBA. */ p5.ColorConversion._hslaToHSBA = function(hsla) { var hue = hsla[0]; var sat = hsla[1]; var li = hsla[2]; // Calculate brightness. var val; if (li < 0.5) { val = (1 + sat) * li; } else { val = li + sat - li * sat; } // Convert saturation. sat = 2 * (val - li) / val; // Hue and alpha stay the same. return [hue, sat, val, hsla[3]]; }; /** * Convert an HSLA array to RGBA. * * We need to change basis from HSLA to something that can be more easily be * projected onto RGBA. We will choose hue and brightness as our first two * components, and pick a convenient third one ('zest') so that we don't need * to calculate formal HSBA saturation. */ p5.ColorConversion._hslaToRGBA = function(hsla) { var hue = hsla[0] * 6; // We will split hue into 6 sectors. var sat = hsla[1]; var li = hsla[2]; var RGBA = []; if (sat === 0) { RGBA = [li, li, li, hsla[3]]; // Return early if grayscale. } else { // Calculate brightness. var val; if (li < 0.5) { val = (1 + sat) * li; } else { val = li + sat - li * sat; } // Define zest. var zest = 2 * li - val; // Implement projection (project onto green by default). var hzvToRGB = function(hue, zest, val) { if (hue < 0) { // Hue must wrap to allow projection onto red and blue. hue += 6; } else if (hue >= 6) { hue -= 6; } if (hue < 1) { // Red to yellow (increasing green). return zest + (val - zest) * hue; } else if (hue < 3) { // Yellow to cyan (greatest green). return val; } else if (hue < 4) { // Cyan to blue (decreasing green). return zest + (val - zest) * (4 - hue); } else { // Blue to red (least green). return zest; } }; // Perform projections, offsetting hue as necessary. RGBA = [ hzvToRGB(hue + 2, zest, val), hzvToRGB(hue, zest, val), hzvToRGB(hue - 2, zest, val), hsla[3] ]; } return RGBA; }; /** * Convert an RGBA array to HSBA. */ p5.ColorConversion._rgbaToHSBA = function(rgba) { var red = rgba[0]; var green = rgba[1]; var blue = rgba[2]; var val = Math.max(red, green, blue); var chroma = val - Math.min(red, green, blue); var hue, sat; if (chroma === 0) { // Return early if grayscale. hue = 0; sat = 0; } else { sat = chroma / val; if (red === val) { // Magenta to yellow. hue = (green - blue) / chroma; } else if (green === val) { // Yellow to cyan. hue = 2 + (blue - red) / chroma; } else if (blue === val) { // Cyan to magenta. hue = 4 + (red - green) / chroma; } if (hue < 0) { // Confine hue to the interval [0, 1). hue += 6; } else if (hue >= 6) { hue -= 6; } } return [hue / 6, sat, val, rgba[3]]; }; /** * Convert an RGBA array to HSLA. */ p5.ColorConversion._rgbaToHSLA = function(rgba) { var red = rgba[0]; var green = rgba[1]; var blue = rgba[2]; var val = Math.max(red, green, blue); var min = Math.min(red, green, blue); var li = val + min; // We will halve this later. var chroma = val - min; var hue, sat; if (chroma === 0) { // Return early if grayscale. hue = 0; sat = 0; } else { if (li < 1) { sat = chroma / li; } else { sat = chroma / (2 - li); } if (red === val) { // Magenta to yellow. hue = (green - blue) / chroma; } else if (green === val) { // Yellow to cyan. hue = 2 + (blue - red) / chroma; } else if (blue === val) { // Cyan to magenta. hue = 4 + (red - green) / chroma; } if (hue < 0) { // Confine hue to the interval [0, 1). hue += 6; } else if (hue >= 6) { hue -= 6; } } return [hue / 6, sat, li / 2, rgba[3]]; }; module.exports = p5.ColorConversion; },{"../core/core":22}],15:[function(_dereq_,module,exports){ /** * @module Color * @submodule Creating & Reading * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); _dereq_('./p5.Color'); _dereq_('../core/error_helpers'); /** * Extracts the alpha value from a color or pixel array. * * @method alpha * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the alpha value * @example *
* * noStroke(); * var c = color(0, 126, 255, 102); * fill(c); * rect(15, 15, 35, 70); * var value = alpha(c); // Sets 'value' to 102 * fill(value); * rect(50, 15, 35, 70); * *
* * @alt * Left half of canvas light blue and right half light charcoal grey. * Left half of canvas light purple and right half a royal blue. * Left half of canvas salmon pink and the right half white. * Yellow rect in middle right of canvas, with 55 pixel width and height. * Yellow ellipse in top left canvas, black ellipse in bottom right,both 80x80. * Bright fuschia rect in middle of canvas, 60 pixel width and height. * Two bright green rects on opposite sides of the canvas, both 45x80. * Four blue rects in each corner of the canvas, each are 35x35. * Bright sea green rect on left and darker rect on right of canvas, both 45x80. * Dark green rect on left and light green rect on right of canvas, both 45x80. * Dark blue rect on left and light teal rect on right of canvas, both 45x80. * blue rect on left and green on right, both with black outlines & 35x60. * salmon pink rect on left and black on right, both 35x60. * 4 rects, tan, brown, brownish purple and purple, with white outlines & 20x60. * light pastel green rect on left and dark grey rect on right, both 35x60. * yellow rect on left and red rect on right, both with black outlines & 35x60. * grey canvas * deep pink rect on left and grey rect on right, both 35x60. */ p5.prototype.alpha = function(c) { p5._validateParameters('alpha', arguments); return this.color(c)._getAlpha(); }; /** * Extracts the blue value from a color or pixel array. * * @method blue * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the blue value * @example *
* * var c = color(175, 100, 220); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * * var blueValue = blue(c); // Get blue in 'c' * print(blueValue); // Prints "220.0" * fill(0, 0, blueValue); // Use 'blueValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * *
* * @alt * Left half of canvas light purple and right half a royal blue. * */ p5.prototype.blue = function(c) { p5._validateParameters('blue', arguments); return this.color(c)._getBlue(); }; /** * Extracts the HSB brightness value from a color or pixel array. * * @method brightness * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the brightness value * @example *
* * noStroke(); * colorMode(HSB, 255); * var c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); * var value = brightness(c); // Sets 'value' to 255 * fill(value); * rect(50, 20, 35, 60); * *
* * @alt * Left half of canvas salmon pink and the right half white. * */ p5.prototype.brightness = function(c) { p5._validateParameters('brightness', arguments); return this.color(c)._getBrightness(); }; /** * Creates colors for storing in variables of the color datatype. The * parameters are interpreted as RGB or HSB values depending on the * current colorMode(). The default mode is RGB values from 0 to 255 * and, therefore, the function call color(255, 204, 0) will return a * bright yellow color. *

* Note that if only one value is provided to color(), it will be interpreted * as a grayscale value. Add a second value, and it will be used for alpha * transparency. When three values are specified, they are interpreted as * either RGB or HSB values. Adding a fourth value applies alpha * transparency. *

* If a single string argument is provided, RGB, RGBA and Hex CSS color * strings and all named color strings are supported. In this case, an alpha * number value as a second argument is not supported, the RGBA form should be * used. * * @method color * @param {Number} gray number specifying value between white * and black. * @param {Number} [alpha] alpha value relative to current color range * (default is 0-255) * @return {p5.Color} resulting color * * @example *
* * var c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * rect(30, 20, 55, 55); // Draw rectangle * *
* *
* * var c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * ellipse(25, 25, 80, 80); // Draw left circle * * // Using only one value with color() * // generates a grayscale value. * c = color(65); // Update 'c' with grayscale value * fill(c); // Use updated 'c' as fill color * ellipse(75, 75, 80, 80); // Draw right circle * *
* *
* * // Named SVG & CSS colors may be used, * var c = color('magenta'); * fill(c); // Use 'c' as fill color * noStroke(); // Don't draw a stroke around shapes * rect(20, 20, 60, 60); // Draw rectangle * *
* *
* * // as can hex color codes: * noStroke(); // Don't draw a stroke around shapes * var c = color('#0f0'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * * c = color('#00ff00'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw rectangle * *
* *
* * // RGB and RGBA color strings are also supported: * // these all set to the same color (solid blue) * var c; * noStroke(); // Don't draw a stroke around shapes * c = color('rgb(0,0,255)'); * fill(c); // Use 'c' as fill color * rect(10, 10, 35, 35); // Draw rectangle * * c = color('rgb(0%, 0%, 100%)'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 35, 35); // Draw rectangle * * c = color('rgba(0, 0, 255, 1)'); * fill(c); // Use updated 'c' as fill color * rect(10, 55, 35, 35); // Draw rectangle * * c = color('rgba(0%, 0%, 100%, 1)'); * fill(c); // Use updated 'c' as fill color * rect(55, 55, 35, 35); // Draw rectangle * *
* *
* * // HSL color is also supported and can be specified * // by value * var c; * noStroke(); // Don't draw a stroke around shapes * c = color('hsl(160, 100%, 50%)'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * * c = color('hsla(160, 100%, 50%, 0.5)'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw rectangle * *
* *
* * // HSB color is also supported and can be specified * // by value * var c; * noStroke(); // Don't draw a stroke around shapes * c = color('hsb(160, 100%, 50%)'); * fill(c); // Use 'c' as fill color * rect(0, 10, 45, 80); // Draw rectangle * * c = color('hsba(160, 100%, 50%, 0.5)'); * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw rectangle * *
* *
* * var c; // Declare color 'c' * noStroke(); // Don't draw a stroke around shapes * * // If no colorMode is specified, then the * // default of RGB with scale of 0-255 is used. * c = color(50, 55, 100); // Create a color for 'c' * fill(c); // Use color variable 'c' as fill color * rect(0, 10, 45, 80); // Draw left rect * * colorMode(HSB, 100); // Use HSB with scale of 0-100 * c = color(50, 55, 100); // Update 'c' with new color * fill(c); // Use updated 'c' as fill color * rect(55, 10, 45, 80); // Draw right rect * *
* * @alt * Yellow rect in middle right of canvas, with 55 pixel width and height. * Yellow ellipse in top left of canvas, black ellipse in bottom right,both 80x80. * Bright fuschia rect in middle of canvas, 60 pixel width and height. * Two bright green rects on opposite sides of the canvas, both 45x80. * Four blue rects in each corner of the canvas, each are 35x35. * Bright sea green rect on left and darker rect on right of canvas, both 45x80. * Dark green rect on left and lighter green rect on right of canvas, both 45x80. * Dark blue rect on left and light teal rect on right of canvas, both 45x80. * */ /** * @method color * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @return {p5.Color} */ /** * @method color * @param {String} value a color string * @return {p5.Color} */ /** * @method color * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @return {p5.Color} */ /** * @method color * @param {p5.Color} color * @return {p5.Color} */ p5.prototype.color = function() { p5._validateParameters('color', arguments); if (arguments[0] instanceof p5.Color) { return arguments[0]; // Do nothing if argument is already a color object. } var args = arguments[0] instanceof Array ? arguments[0] : arguments; return new p5.Color(this, args); }; /** * Extracts the green value from a color or pixel array. * * @method green * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the green value * @example *
* * var c = color(20, 75, 200); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * * var greenValue = green(c); // Get green in 'c' * print(greenValue); // Print "75.0" * fill(0, greenValue, 0); // Use 'greenValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * *
* * @alt * blue rect on left and green on right, both with black outlines & 35x60. * */ p5.prototype.green = function(c) { p5._validateParameters('green', arguments); return this.color(c)._getGreen(); }; /** * Extracts the hue value from a color or pixel array. * * Hue exists in both HSB and HSL. This function will return the * HSB-normalized hue when supplied with an HSB color object (or when supplied * with a pixel array while the color mode is HSB), but will default to the * HSL-normalized hue otherwise. (The values will only be different if the * maximum hue setting for each system is different.) * * @method hue * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the hue * @example *
* * noStroke(); * colorMode(HSB, 255); * var c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); * var value = hue(c); // Sets 'value' to "0" * fill(value); * rect(50, 20, 35, 60); * *
* * @alt * salmon pink rect on left and black on right, both 35x60. * */ p5.prototype.hue = function(c) { p5._validateParameters('hue', arguments); return this.color(c)._getHue(); }; /** * Blends two colors to find a third color somewhere between them. The amt * parameter is the amount to interpolate between the two values where 0.0 * equal to the first color, 0.1 is very near the first color, 0.5 is halfway * in between, etc. An amount below 0 will be treated as 0. Likewise, amounts * above 1 will be capped at 1. This is different from the behavior of lerp(), * but necessary because otherwise numbers outside the range will produce * strange and unexpected colors. *

* The way that colours are interpolated depends on the current color mode. * * @method lerpColor * @param {p5.Color} c1 interpolate from this color * @param {p5.Color} c2 interpolate to this color * @param {Number} amt number between 0 and 1 * @return {p5.Color} interpolated color * @example *
* * colorMode(RGB); * stroke(255); * background(51); * var from = color(218, 165, 32); * var to = color(72, 61, 139); * colorMode(RGB); // Try changing to HSB. * var interA = lerpColor(from, to, 0.33); * var interB = lerpColor(from, to, 0.66); * fill(from); * rect(10, 20, 20, 60); * fill(interA); * rect(30, 20, 20, 60); * fill(interB); * rect(50, 20, 20, 60); * fill(to); * rect(70, 20, 20, 60); * *
* * @alt * 4 rects one tan, brown, brownish purple, purple, with white outlines & 20x60 * */ p5.prototype.lerpColor = function(c1, c2, amt) { p5._validateParameters('lerpColor', arguments); var mode = this._colorMode; var maxes = this._colorMaxes; var l0, l1, l2, l3; var fromArray, toArray; if (mode === constants.RGB) { fromArray = c1.levels.map(function(level) { return level / 255; }); toArray = c2.levels.map(function(level) { return level / 255; }); } else if (mode === constants.HSB) { c1._getBrightness(); // Cache hsba so it definitely exists. c2._getBrightness(); fromArray = c1.hsba; toArray = c2.hsba; } else if (mode === constants.HSL) { c1._getLightness(); // Cache hsla so it definitely exists. c2._getLightness(); fromArray = c1.hsla; toArray = c2.hsla; } else { throw new Error(mode + 'cannot be used for interpolation.'); } // Prevent extrapolation. amt = Math.max(Math.min(amt, 1), 0); // Define lerp here itself if user isn't using math module. // Maintains the definition as found in math/calculation.js if (typeof this.lerp === 'undefined') { this.lerp = function(start, stop, amt) { return amt * (stop - start) + start; }; } // Perform interpolation. l0 = this.lerp(fromArray[0], toArray[0], amt); l1 = this.lerp(fromArray[1], toArray[1], amt); l2 = this.lerp(fromArray[2], toArray[2], amt); l3 = this.lerp(fromArray[3], toArray[3], amt); // Scale components. l0 *= maxes[mode][0]; l1 *= maxes[mode][1]; l2 *= maxes[mode][2]; l3 *= maxes[mode][3]; return this.color(l0, l1, l2, l3); }; /** * Extracts the HSL lightness value from a color or pixel array. * * @method lightness * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the lightness * @example *
* * noStroke(); * colorMode(HSL); * var c = color(156, 100, 50, 1); * fill(c); * rect(15, 20, 35, 60); * var value = lightness(c); // Sets 'value' to 50 * fill(value); * rect(50, 20, 35, 60); * *
* * @alt * light pastel green rect on left and dark grey rect on right, both 35x60. * */ p5.prototype.lightness = function(c) { p5._validateParameters('lightness', arguments); return this.color(c)._getLightness(); }; /** * Extracts the red value from a color or pixel array. * * @method red * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the red value * @example *
* * var c = color(255, 204, 0); // Define color 'c' * fill(c); // Use color variable 'c' as fill color * rect(15, 20, 35, 60); // Draw left rectangle * * var redValue = red(c); // Get red in 'c' * print(redValue); // Print "255.0" * fill(redValue, 0, 0); // Use 'redValue' in new fill * rect(50, 20, 35, 60); // Draw right rectangle * *
* *
* * colorMode(RGB, 255); * var c = color(127, 255, 0); * colorMode(RGB, 1); * var myColor = red(c); * print(myColor); * *
* * @alt * yellow rect on left and red rect on right, both with black outlines and 35x60. * grey canvas */ p5.prototype.red = function(c) { p5._validateParameters('red', arguments); return this.color(c)._getRed(); }; /** * Extracts the saturation value from a color or pixel array. * * Saturation is scaled differently in HSB and HSL. This function will return * the HSB saturation when supplied with an HSB color object (or when supplied * with a pixel array while the color mode is HSB), but will default to the * HSL saturation otherwise. * * @method saturation * @param {p5.Color|Number[]|String} color p5.Color object, color components, * or CSS color * @return {Number} the saturation value * @example *
* * noStroke(); * colorMode(HSB, 255); * var c = color(0, 126, 255); * fill(c); * rect(15, 20, 35, 60); * var value = saturation(c); // Sets 'value' to 126 * fill(value); * rect(50, 20, 35, 60); * *
* * @alt *deep pink rect on left and grey rect on right, both 35x60. * */ p5.prototype.saturation = function(c) { p5._validateParameters('saturation', arguments); return this.color(c)._getSaturation(); }; module.exports = p5; },{"../core/constants":21,"../core/core":22,"../core/error_helpers":25,"./p5.Color":16}],16:[function(_dereq_,module,exports){ /** * @module Color * @submodule Creating & Reading * @for p5 * @requires core * @requires constants * @requires color_conversion */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); var color_conversion = _dereq_('./color_conversion'); /** * Each color stores the color mode and level maxes that applied at the * time of its construction. These are used to interpret the input arguments * (at construction and later for that instance of color) and to format the * output e.g. when saturation() is requested. * * Internally we store an array representing the ideal RGBA values in floating * point form, normalized from 0 to 1. From this we calculate the closest * screen color (RGBA levels from 0 to 255) and expose this to the renderer. * * We also cache normalized, floating point components of the color in various * representations as they are calculated. This is done to prevent repeating a * conversion that has already been performed. * * @class p5.Color */ p5.Color = function(pInst, vals) { // Record color mode and maxes at time of construction. this._storeModeAndMaxes(pInst._colorMode, pInst._colorMaxes); // Calculate normalized RGBA values. if ( this.mode !== constants.RGB && this.mode !== constants.HSL && this.mode !== constants.HSB ) { throw new Error(this.mode + ' is an invalid colorMode.'); } else { this._array = p5.Color._parseInputs.apply(this, vals); } // Expose closest screen color. this._calculateLevels(); return this; }; /** * This function returns the color formatted as a string. This can be useful * for debugging, or for using p5.js with other libraries. * @method toString * @param {String} [format] How the color string will be formatted. * Leaving this empty formats the string as rgba(r, g, b, a). * '#rgb' '#rgba' '#rrggbb' and '#rrggbbaa' format as hexadecimal color codes. * 'rgb' 'hsb' and 'hsl' return the color formatted in the specified color mode. * 'rgba' 'hsba' and 'hsla' are the same as above but with alpha channels. * 'rgb%' 'hsb%' 'hsl%' 'rgba%' 'hsba%' and 'hsla%' format as percentages. * @return {String} the formatted string * @example *
* * var myColor; * function setup() { * createCanvas(200, 200); * stroke(255); * myColor = color(100, 100, 250); * fill(myColor); * } * * function draw() { * text(myColor.toString(), 10, 10); * text(myColor.toString('#rrggbb'), 10, 95); * text(myColor.toString('rgba%'), 10, 180); * } * *
* * @alt * canvas with text representation of color */ p5.Color.prototype.toString = function(format) { if (!this.hsba) this.hsba = color_conversion._rgbaToHSBA(this._array); if (!this.hsla) this.hsla = color_conversion._rgbaToHSLA(this._array); var a = this.levels; var f = this._array; var alpha = f[3]; // String representation uses normalized alpha switch (format) { case '#rrggbb': return '#'.concat( a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16), a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16), a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16) ); case '#rrggbbaa': return '#'.concat( a[0] < 16 ? '0'.concat(a[0].toString(16)) : a[0].toString(16), a[1] < 16 ? '0'.concat(a[1].toString(16)) : a[1].toString(16), a[2] < 16 ? '0'.concat(a[2].toString(16)) : a[2].toString(16), a[3] < 16 ? '0'.concat(a[2].toString(16)) : a[3].toString(16) ); case '#rgb': return '#'.concat( Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16) ); case '#rgba': return '#'.concat( Math.round(f[0] * 15).toString(16), Math.round(f[1] * 15).toString(16), Math.round(f[2] * 15).toString(16), Math.round(f[3] * 15).toString(16) ); case 'rgb': return 'rgb('.concat(a[0], ', ', a[1], ', ', a[2], ')'); case 'rgb%': return 'rgb('.concat( (100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%)' ); case 'rgba%': return 'rgba('.concat( (100 * f[0]).toPrecision(3), '%, ', (100 * f[1]).toPrecision(3), '%, ', (100 * f[2]).toPrecision(3), '%, ', (100 * f[3]).toPrecision(3), '%)' ); case 'hsb': case 'hsv': return 'hsb('.concat( this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ')' ); case 'hsb%': case 'hsv%': return 'hsb('.concat( (100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%)' ); case 'hsba': case 'hsva': return 'hsba('.concat( this.hsba[0] * this.maxes[constants.HSB][0], ', ', this.hsba[1] * this.maxes[constants.HSB][1], ', ', this.hsba[2] * this.maxes[constants.HSB][2], ', ', alpha, ')' ); case 'hsba%': case 'hsva%': return 'hsba('.concat( (100 * this.hsba[0]).toPrecision(3), '%, ', (100 * this.hsba[1]).toPrecision(3), '%, ', (100 * this.hsba[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)' ); case 'hsl': return 'hsl('.concat( this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ')' ); case 'hsl%': return 'hsl('.concat( (100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%)' ); case 'hsla': return 'hsla('.concat( this.hsla[0] * this.maxes[constants.HSL][0], ', ', this.hsla[1] * this.maxes[constants.HSL][1], ', ', this.hsla[2] * this.maxes[constants.HSL][2], ', ', alpha, ')' ); case 'hsla%': return 'hsl('.concat( (100 * this.hsla[0]).toPrecision(3), '%, ', (100 * this.hsla[1]).toPrecision(3), '%, ', (100 * this.hsla[2]).toPrecision(3), '%, ', (100 * alpha).toPrecision(3), '%)' ); case 'rgba': default: return 'rgba(' + a[0] + ',' + a[1] + ',' + a[2] + ',' + alpha + ')'; } }; /** * @method setRed * @param {Number} red the new red value * @example *
* * var backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); * } * * function draw() { * backgroundColor.setRed(128 + 128 * sin(millis() / 1000)); * background(backgroundColor); * } * *
* * @alt * canvas with gradually changing background color */ p5.Color.prototype.setRed = function(new_red) { this._array[0] = new_red / this.maxes[constants.RGB][0]; this._calculateLevels(); }; /** * @method setGreen * @param {Number} green the new green value * @example *
* * var backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); * } * * function draw() { * backgroundColor.setGreen(128 + 128 * sin(millis() / 1000)); * background(backgroundColor); * } * *
* * @alt * canvas with gradually changing background color **/ p5.Color.prototype.setGreen = function(new_green) { this._array[1] = new_green / this.maxes[constants.RGB][1]; this._calculateLevels(); }; /** * @method setBlue * @param {Number} blue the new blue value * @example *
* * var backgroundColor; * * function setup() { * backgroundColor = color(100, 50, 150); * } * * function draw() { * backgroundColor.setBlue(128 + 128 * sin(millis() / 1000)); * background(backgroundColor); * } * *
* * @alt * canvas with gradually changing background color **/ p5.Color.prototype.setBlue = function(new_blue) { this._array[2] = new_blue / this.maxes[constants.RGB][2]; this._calculateLevels(); }; /** * @method setAlpha * @param {Number} alpha the new alpha value * @example *
* * var squareColor; * * function setup() { * ellipseMode(CORNERS); * strokeWeight(4); * squareColor = color(100, 50, 150); * } * * function draw() { * background(255); * * noFill(); * stroke(0); * ellipse(10, 10, width - 10, height - 10); * * squareColor.setAlpha(128 + 128 * sin(millis() / 1000)); * fill(squareColor); * noStroke(); * rect(13, 13, width - 26, height - 26); * } * *
* * @alt * circle behind a square with gradually changing opacity **/ p5.Color.prototype.setAlpha = function(new_alpha) { this._array[3] = new_alpha / this.maxes[this.mode][3]; this._calculateLevels(); }; // calculates and stores the closest screen levels p5.Color.prototype._calculateLevels = function() { this.levels = this._array.map(function(level) { return Math.round(level * 255); }); }; p5.Color.prototype._getAlpha = function() { return this._array[3] * this.maxes[this.mode][3]; }; // stores the color mode and maxes in this instance of Color // for later use (by _parseInputs()) p5.Color.prototype._storeModeAndMaxes = function(new_mode, new_maxes) { this.mode = new_mode; this.maxes = new_maxes; }; p5.Color.prototype._getMode = function() { return this.mode; }; p5.Color.prototype._getMaxes = function() { return this.maxes; }; p5.Color.prototype._getBlue = function() { return this._array[2] * this.maxes[constants.RGB][2]; }; p5.Color.prototype._getBrightness = function() { if (!this.hsba) { this.hsba = color_conversion._rgbaToHSBA(this._array); } return this.hsba[2] * this.maxes[constants.HSB][2]; }; p5.Color.prototype._getGreen = function() { return this._array[1] * this.maxes[constants.RGB][1]; }; /** * Hue is the same in HSB and HSL, but the maximum value may be different. * This function will return the HSB-normalized saturation when supplied with * an HSB color object, but will default to the HSL-normalized saturation * otherwise. */ p5.Color.prototype._getHue = function() { if (this.mode === constants.HSB) { if (!this.hsba) { this.hsba = color_conversion._rgbaToHSBA(this._array); } return this.hsba[0] * this.maxes[constants.HSB][0]; } else { if (!this.hsla) { this.hsla = color_conversion._rgbaToHSLA(this._array); } return this.hsla[0] * this.maxes[constants.HSL][0]; } }; p5.Color.prototype._getLightness = function() { if (!this.hsla) { this.hsla = color_conversion._rgbaToHSLA(this._array); } return this.hsla[2] * this.maxes[constants.HSL][2]; }; p5.Color.prototype._getRed = function() { return this._array[0] * this.maxes[constants.RGB][0]; }; /** * Saturation is scaled differently in HSB and HSL. This function will return * the HSB saturation when supplied with an HSB color object, but will default * to the HSL saturation otherwise. */ p5.Color.prototype._getSaturation = function() { if (this.mode === constants.HSB) { if (!this.hsba) { this.hsba = color_conversion._rgbaToHSBA(this._array); } return this.hsba[1] * this.maxes[constants.HSB][1]; } else { if (!this.hsla) { this.hsla = color_conversion._rgbaToHSLA(this._array); } return this.hsla[1] * this.maxes[constants.HSL][1]; } }; /** * CSS named colors. */ var namedColors = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#00ffff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgreen: '#006400', darkgrey: '#a9a9a9', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', grey: '#808080', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa', lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff', lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgreen: '#90ee90', lightgrey: '#d3d3d3', lightpink: '#ffb6c1', lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#ff00ff', maroon: '#800000', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370db', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98', paleturquoise: '#afeeee', palevioletred: '#db7093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32' }; /** * These regular expressions are used to build up the patterns for matching * viable CSS color strings: fragmenting the regexes in this way increases the * legibility and comprehensibility of the code. * * Note that RGB values of .9 are not parsed by IE, but are supported here for * color string consistency. */ var WHITESPACE = /\s*/; // Match zero or more whitespace characters. var INTEGER = /(\d{1,3})/; // Match integers: 79, 255, etc. var DECIMAL = /((?:\d+(?:\.\d+)?)|(?:\.\d+))/; // Match 129.6, 79, .9, etc. var PERCENT = new RegExp(DECIMAL.source + '%'); // Match 12.9%, 79%, .9%, etc. /** * Full color string patterns. The capture groups are necessary. */ var colorPatterns = { // Match colors in format #XXX, e.g. #416. HEX3: /^#([a-f0-9])([a-f0-9])([a-f0-9])$/i, // Match colors in format #XXXX, e.g. #5123. HEX4: /^#([a-f0-9])([a-f0-9])([a-f0-9])([a-f0-9])$/i, // Match colors in format #XXXXXX, e.g. #b4d455. HEX6: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i, // Match colors in format #XXXXXXXX, e.g. #b4d45535. HEX8: /^#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})$/i, // Match colors in format rgb(R, G, B), e.g. rgb(255, 0, 128). RGB: new RegExp( [ '^rgb\\(', INTEGER.source, ',', INTEGER.source, ',', INTEGER.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format rgb(R%, G%, B%), e.g. rgb(100%, 0%, 28.9%). RGB_PERCENT: new RegExp( [ '^rgb\\(', PERCENT.source, ',', PERCENT.source, ',', PERCENT.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format rgb(R, G, B, A), e.g. rgb(255, 0, 128, 0.25). RGBA: new RegExp( [ '^rgba\\(', INTEGER.source, ',', INTEGER.source, ',', INTEGER.source, ',', DECIMAL.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format rgb(R%, G%, B%, A), e.g. rgb(100%, 0%, 28.9%, 0.5). RGBA_PERCENT: new RegExp( [ '^rgba\\(', PERCENT.source, ',', PERCENT.source, ',', PERCENT.source, ',', DECIMAL.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format hsla(H, S%, L%), e.g. hsl(100, 40%, 28.9%). HSL: new RegExp( [ '^hsl\\(', INTEGER.source, ',', PERCENT.source, ',', PERCENT.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format hsla(H, S%, L%, A), e.g. hsla(100, 40%, 28.9%, 0.5). HSLA: new RegExp( [ '^hsla\\(', INTEGER.source, ',', PERCENT.source, ',', PERCENT.source, ',', DECIMAL.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format hsb(H, S%, B%), e.g. hsb(100, 40%, 28.9%). HSB: new RegExp( [ '^hsb\\(', INTEGER.source, ',', PERCENT.source, ',', PERCENT.source, '\\)$' ].join(WHITESPACE.source), 'i' ), // Match colors in format hsba(H, S%, B%, A), e.g. hsba(100, 40%, 28.9%, 0.5). HSBA: new RegExp( [ '^hsba\\(', INTEGER.source, ',', PERCENT.source, ',', PERCENT.source, ',', DECIMAL.source, '\\)$' ].join(WHITESPACE.source), 'i' ) }; /** * For a number of different inputs, returns a color formatted as [r, g, b, a] * arrays, with each component normalized between 0 and 1. * * @private * @param {Array} [...args] An 'array-like' object that represents a list of * arguments * @return {Number[]} a color formatted as [r, g, b, a] * Example: * input ==> output * g ==> [g, g, g, 255] * g,a ==> [g, g, g, a] * r, g, b ==> [r, g, b, 255] * r, g, b, a ==> [r, g, b, a] * [g] ==> [g, g, g, 255] * [g, a] ==> [g, g, g, a] * [r, g, b] ==> [r, g, b, 255] * [r, g, b, a] ==> [r, g, b, a] * @example *
* * // todo * *
* * @alt * //todo * */ p5.Color._parseInputs = function(r, g, b, a) { var numArgs = arguments.length; var mode = this.mode; var maxes = this.maxes; var results = []; if (numArgs >= 3) { // Argument is a list of component values. results[0] = r / maxes[mode][0]; results[1] = g / maxes[mode][1]; results[2] = b / maxes[mode][2]; // Alpha may be undefined, so default it to 100%. if (typeof a === 'number') { results[3] = a / maxes[mode][3]; } else { results[3] = 1; } // Constrain components to the range [0,1]. results = results.map(function(value) { return Math.max(Math.min(value, 1), 0); }); // Convert to RGBA and return. if (mode === constants.HSL) { return color_conversion._hslaToRGBA(results); } else if (mode === constants.HSB) { return color_conversion._hsbaToRGBA(results); } else { return results; } } else if (numArgs === 1 && typeof r === 'string') { var str = r.trim().toLowerCase(); // Return if string is a named colour. if (namedColors[str]) { return p5.Color._parseInputs.call(this, namedColors[str]); } // Try RGBA pattern matching. if (colorPatterns.HEX3.test(str)) { // #rgb results = colorPatterns.HEX3.exec(str) .slice(1) .map(function(color) { return parseInt(color + color, 16) / 255; }); results[3] = 1; return results; } else if (colorPatterns.HEX6.test(str)) { // #rrggbb results = colorPatterns.HEX6.exec(str) .slice(1) .map(function(color) { return parseInt(color, 16) / 255; }); results[3] = 1; return results; } else if (colorPatterns.HEX4.test(str)) { // #rgba results = colorPatterns.HEX4.exec(str) .slice(1) .map(function(color) { return parseInt(color + color, 16) / 255; }); return results; } else if (colorPatterns.HEX8.test(str)) { // #rrggbbaa results = colorPatterns.HEX8.exec(str) .slice(1) .map(function(color) { return parseInt(color, 16) / 255; }); return results; } else if (colorPatterns.RGB.test(str)) { // rgb(R,G,B) results = colorPatterns.RGB.exec(str) .slice(1) .map(function(color) { return color / 255; }); results[3] = 1; return results; } else if (colorPatterns.RGB_PERCENT.test(str)) { // rgb(R%,G%,B%) results = colorPatterns.RGB_PERCENT.exec(str) .slice(1) .map(function(color) { return parseFloat(color) / 100; }); results[3] = 1; return results; } else if (colorPatterns.RGBA.test(str)) { // rgba(R,G,B,A) results = colorPatterns.RGBA.exec(str) .slice(1) .map(function(color, idx) { if (idx === 3) { return parseFloat(color); } return color / 255; }); return results; } else if (colorPatterns.RGBA_PERCENT.test(str)) { // rgba(R%,G%,B%,A%) results = colorPatterns.RGBA_PERCENT.exec(str) .slice(1) .map(function(color, idx) { if (idx === 3) { return parseFloat(color); } return parseFloat(color) / 100; }); return results; } // Try HSLA pattern matching. if (colorPatterns.HSL.test(str)) { // hsl(H,S,L) results = colorPatterns.HSL.exec(str) .slice(1) .map(function(color, idx) { if (idx === 0) { return parseInt(color, 10) / 360; } return parseInt(color, 10) / 100; }); results[3] = 1; } else if (colorPatterns.HSLA.test(str)) { // hsla(H,S,L,A) results = colorPatterns.HSLA.exec(str) .slice(1) .map(function(color, idx) { if (idx === 0) { return parseInt(color, 10) / 360; } else if (idx === 3) { return parseFloat(color); } return parseInt(color, 10) / 100; }); } results = results.map(function(value) { return Math.max(Math.min(value, 1), 0); }); if (results.length) { return color_conversion._hslaToRGBA(results); } // Try HSBA pattern matching. if (colorPatterns.HSB.test(str)) { // hsb(H,S,B) results = colorPatterns.HSB.exec(str) .slice(1) .map(function(color, idx) { if (idx === 0) { return parseInt(color, 10) / 360; } return parseInt(color, 10) / 100; }); results[3] = 1; } else if (colorPatterns.HSBA.test(str)) { // hsba(H,S,B,A) results = colorPatterns.HSBA.exec(str) .slice(1) .map(function(color, idx) { if (idx === 0) { return parseInt(color, 10) / 360; } else if (idx === 3) { return parseFloat(color); } return parseInt(color, 10) / 100; }); } results = results.map(function(value) { return Math.max(Math.min(value, 1), 0); }); if (results.length) { return color_conversion._hsbaToRGBA(results); } // Input did not match any CSS color pattern: default to white. results = [1, 1, 1, 1]; } else if ((numArgs === 1 || numArgs === 2) && typeof r === 'number') { // 'Grayscale' mode. /** * For HSB and HSL, interpret the gray level as a brightness/lightness * value (they are equivalent when chroma is zero). For RGB, normalize the * gray level according to the blue maximum. */ results[0] = r / maxes[mode][2]; results[1] = r / maxes[mode][2]; results[2] = r / maxes[mode][2]; // Alpha may be undefined, so default it to 100%. if (typeof g === 'number') { results[3] = g / maxes[mode][3]; } else { results[3] = 1; } // Constrain components to the range [0,1]. results = results.map(function(value) { return Math.max(Math.min(value, 1), 0); }); } else { throw new Error(arguments + 'is not a valid color representation.'); } return results; }; module.exports = p5.Color; },{"../core/constants":21,"../core/core":22,"./color_conversion":14}],17:[function(_dereq_,module,exports){ /** * @module Color * @submodule Setting * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); _dereq_('./p5.Color'); /** * The background() function sets the color used for the background of the * p5.js canvas. The default background is light gray. This function is * typically used within draw() to clear the display window at the beginning * of each frame, but it can be used inside setup() to set the background on * the first frame of animation or if the background need only be set once. *

* The color is either specified in terms of the RGB, HSB, or HSL color * depending on the current colorMode. (The default color space is RGB, with * each value in the range from 0 to 255). The alpha range by default is also 0 to 255. *

* If a single string argument is provided, RGB, RGBA and Hex CSS color strings * and all named color strings are supported. In this case, an alpha number * value as a second argument is not supported, the RGBA form should be used. *

* A p5.Color object can also be provided to set the background color. *

* A p5.Image can also be provided to set the background image. * * @method background * @param {p5.Color} color any value created by the color() function * @chainable * * @example *
* * // Grayscale integer value * background(51); * *
* *
* * // R, G & B integer values * background(255, 204, 0); * *
* *
* * // H, S & B integer values * colorMode(HSB); * background(255, 204, 100); * *
* *
* * // Named SVG/CSS color string * background('red'); * *
* *
* * // three-digit hexadecimal RGB notation * background('#fae'); * *
* *
* * // six-digit hexadecimal RGB notation * background('#222222'); * *
* *
* * // integer RGB notation * background('rgb(0,255,0)'); * *
* *
* * // integer RGBA notation * background('rgba(0,255,0, 0.25)'); * *
* *
* * // percentage RGB notation * background('rgb(100%,0%,10%)'); * *
* *
* * // percentage RGBA notation * background('rgba(100%,0%,100%,0.5)'); * *
* *
* * // p5 Color object * background(color(0, 0, 255)); * *
* * @alt * canvas with darkest charcoal grey background. * canvas with yellow background. * canvas with royal blue background. * canvas with red background. * canvas with pink background. * canvas with black background. * canvas with bright green background. * canvas with soft green background. * canvas with red background. * canvas with light purple background. * canvas with blue background. */ /** * @method background * @param {String} colorstring color string, possible formats include: integer * rgb() or rgba(), percentage rgb() or rgba(), * 3-digit hex, 6-digit hex * @param {Number} [a] opacity of the background relative to current * color range (default is 0-255) * @chainable */ /** * @method background * @param {Number} gray specifies a value between white and black * @param {Number} [a] * @chainable */ /** * @method background * @param {Number} v1 red or hue value (depending on the current color * mode) * @param {Number} v2 green or saturation value (depending on the current * color mode) * @param {Number} v3 blue or brightness value (depending on the current * color mode) * @param {Number} [a] * @chainable */ /** * @method background * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable */ /** * @method background * @param {p5.Image} image image created with loadImage() or createImage(), * to set as background * (must be same size as the sketch window) * @param {Number} [a] * @chainable */ p5.prototype.background = function() { if (arguments[0] instanceof p5.Image) { this.image(arguments[0], 0, 0, this.width, this.height); } else { this._renderer.background.apply(this._renderer, arguments); } return this; }; /** * Clears the pixels within a buffer. This function only works on p5.Canvas * objects created with the createCanvas() function; it won't work with the * main display window. Unlike the main graphics context, pixels in * additional graphics areas created with createGraphics() can be entirely * or partially transparent. This function clears everything to make all of * the pixels 100% transparent. * * @method clear * @chainable * @example *
* * // Clear the screen on mouse press. * function setup() { * createCanvas(100, 100); * } * * function draw() { * ellipse(mouseX, mouseY, 20, 20); * } * * function mousePressed() { * clear(); * } * *
* * @alt * 20x20 white ellipses are continually drawn at mouse x and y coordinates. * */ p5.prototype.clear = function() { this._renderer.clear(); return this; }; /** * colorMode() changes the way p5.js interprets color data. By default, the * parameters for fill(), stroke(), background(), and color() are defined by * values between 0 and 255 using the RGB color model. This is equivalent to * setting colorMode(RGB, 255). Setting colorMode(HSB) lets you use the HSB * system instead. By default, this is colorMode(HSB, 360, 100, 100, 1). You * can also use HSL. *

* Note: existing color objects remember the mode that they were created in, * so you can change modes as you like without affecting their appearance. * * * @method colorMode * @param {Constant} mode either RGB, HSB or HSL, corresponding to * Red/Green/Blue and Hue/Saturation/Brightness * (or Lightness) * @param {Number} [max] range for all values * @chainable * * @example *
* * noStroke(); * colorMode(RGB, 100); * for (var i = 0; i < 100; i++) { * for (var j = 0; j < 100; j++) { * stroke(i, j, 0); * point(i, j); * } * } * *
* *
* * noStroke(); * colorMode(HSB, 100); * for (var i = 0; i < 100; i++) { * for (var j = 0; j < 100; j++) { * stroke(i, j, 100); * point(i, j); * } * } * *
* *
* * colorMode(RGB, 255); * var c = color(127, 255, 0); * * colorMode(RGB, 1); * var myColor = c._getRed(); * text(myColor, 10, 10, 80, 80); * *
* *
* * noFill(); * colorMode(RGB, 255, 255, 255, 1); * background(255); * * strokeWeight(4); * stroke(255, 0, 10, 0.3); * ellipse(40, 40, 50, 50); * ellipse(50, 50, 40, 40); * *
* * @alt *Green to red gradient from bottom L to top R. shading originates from top left. *Rainbow gradient from left to right. Brightness increasing to white at top. *unknown image. *50x50 ellipse at middle L & 40x40 ellipse at center. Transluscent pink outlines. * */ /** * @method colorMode * @param {Constant} mode * @param {Number} max1 range for the red or hue depending on the * current color mode * @param {Number} max2 range for the green or saturation depending * on the current color mode * @param {Number} max3 range for the blue or brightness/lighntess * depending on the current color mode * @param {Number} [maxA] range for the alpha * @chainable */ p5.prototype.colorMode = function(mode, max1, max2, max3, maxA) { p5._validateParameters('colorMode', arguments); if ( mode === constants.RGB || mode === constants.HSB || mode === constants.HSL ) { // Set color mode. this._colorMode = mode; // Set color maxes. var maxes = this._colorMaxes[mode]; if (arguments.length === 2) { maxes[0] = max1; // Red maxes[1] = max1; // Green maxes[2] = max1; // Blue maxes[3] = max1; // Alpha } else if (arguments.length === 4) { maxes[0] = max1; // Red maxes[1] = max2; // Green maxes[2] = max3; // Blue } else if (arguments.length === 5) { maxes[0] = max1; // Red maxes[1] = max2; // Green maxes[2] = max3; // Blue maxes[3] = maxA; // Alpha } } return this; }; /** * Sets the color used to fill shapes. For example, if you run * fill(204, 102, 0), all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current colorMode(). (The default color space is RGB, with each value * in the range from 0 to 255). The alpha range by default is also 0 to 255. *

* If a single string argument is provided, RGB, RGBA and Hex CSS color strings * and all named color strings are supported. In this case, an alpha number * value as a second argument is not supported, the RGBA form should be used. *

* A p5 Color object can also be provided to set the fill color. * * @method fill * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @chainable * @example *
* * // Grayscale integer value * fill(51); * rect(20, 20, 60, 60); * *
* *
* * // R, G & B integer values * fill(255, 204, 0); * rect(20, 20, 60, 60); * *
* *
* * // H, S & B integer values * colorMode(HSB); * fill(255, 204, 100); * rect(20, 20, 60, 60); * *
* *
* * // Named SVG/CSS color string * fill('red'); * rect(20, 20, 60, 60); * *
* *
* * // three-digit hexadecimal RGB notation * fill('#fae'); * rect(20, 20, 60, 60); * *
* *
* * // six-digit hexadecimal RGB notation * fill('#222222'); * rect(20, 20, 60, 60); * *
* *
* * // integer RGB notation * fill('rgb(0,255,0)'); * rect(20, 20, 60, 60); * *
* *
* * // integer RGBA notation * fill('rgba(0,255,0, 0.25)'); * rect(20, 20, 60, 60); * *
* *
* * // percentage RGB notation * fill('rgb(100%,0%,10%)'); * rect(20, 20, 60, 60); * *
* *
* * // percentage RGBA notation * fill('rgba(100%,0%,100%,0.5)'); * rect(20, 20, 60, 60); * *
* *
* * // p5 Color object * fill(color(0, 0, 255)); * rect(20, 20, 60, 60); * *
* @alt * 60x60 dark charcoal grey rect with black outline in center of canvas. * 60x60 yellow rect with black outline in center of canvas. * 60x60 royal blue rect with black outline in center of canvas. * 60x60 red rect with black outline in center of canvas. * 60x60 pink rect with black outline in center of canvas. * 60x60 black rect with black outline in center of canvas. * 60x60 light green rect with black outline in center of canvas. * 60x60 soft green rect with black outline in center of canvas. * 60x60 red rect with black outline in center of canvas. * 60x60 dark fushcia rect with black outline in center of canvas. * 60x60 blue rect with black outline in center of canvas. */ /** * @method fill * @param {String} value a color string * @chainable */ /** * @method fill * @param {Number} gray a gray value * @param {Number} [alpha] * @chainable */ /** * @method fill * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable */ /** * @method fill * @param {p5.Color} color the fill color * @chainable */ p5.prototype.fill = function() { this._renderer._setProperty('_fillSet', true); this._renderer._setProperty('_doFill', true); this._renderer.fill.apply(this._renderer, arguments); return this; }; /** * Disables filling geometry. If both noStroke() and noFill() are called, * nothing will be drawn to the screen. * * @method noFill * @chainable * @example *
* * rect(15, 10, 55, 55); * noFill(); * rect(20, 20, 60, 60); * *
* *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * noFill(); * stroke(100, 100, 240); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(45, 45, 45); * } * *
* * @alt * white rect top middle and noFill rect center. Both 60x60 with black outlines. * black canvas with purple cube wireframe spinning */ p5.prototype.noFill = function() { this._renderer._setProperty('_doFill', false); return this; }; /** * Disables drawing the stroke (outline). If both noStroke() and noFill() * are called, nothing will be drawn to the screen. * * @method noStroke * @chainable * @example *
* * noStroke(); * rect(20, 20, 60, 60); * *
* *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * noStroke(); * fill(240, 150, 150); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(45, 45, 45); * } * *
* * @alt * 60x60 white rect at center. no outline. * black canvas with pink cube spinning */ p5.prototype.noStroke = function() { this._renderer._setProperty('_doStroke', false); return this; }; /** * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current colorMode() (the default color space is RGB, with each value in * the range from 0 to 255). The alpha range by default is also 0 to 255. *

* If a single string argument is provided, RGB, RGBA and Hex CSS color * strings and all named color strings are supported. In this case, an alpha * number value as a second argument is not supported, the RGBA form should be * used. *

* A p5 Color object can also be provided to set the stroke color. * * * @method stroke * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @chainable * * @example *
* * // Grayscale integer value * strokeWeight(4); * stroke(51); * rect(20, 20, 60, 60); * *
* *
* * // R, G & B integer values * stroke(255, 204, 0); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // H, S & B integer values * colorMode(HSB); * strokeWeight(4); * stroke(255, 204, 100); * rect(20, 20, 60, 60); * *
* *
* * // Named SVG/CSS color string * stroke('red'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // three-digit hexadecimal RGB notation * stroke('#fae'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // six-digit hexadecimal RGB notation * stroke('#222222'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // integer RGB notation * stroke('rgb(0,255,0)'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // integer RGBA notation * stroke('rgba(0,255,0,0.25)'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // percentage RGB notation * stroke('rgb(100%,0%,10%)'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // percentage RGBA notation * stroke('rgba(100%,0%,100%,0.5)'); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* *
* * // p5 Color object * stroke(color(0, 0, 255)); * strokeWeight(4); * rect(20, 20, 60, 60); * *
* * @alt * 60x60 white rect at center. Dark charcoal grey outline. * 60x60 white rect at center. Yellow outline. * 60x60 white rect at center. Royal blue outline. * 60x60 white rect at center. Red outline. * 60x60 white rect at center. Pink outline. * 60x60 white rect at center. Black outline. * 60x60 white rect at center. Bright green outline. * 60x60 white rect at center. Soft green outline. * 60x60 white rect at center. Red outline. * 60x60 white rect at center. Dark fushcia outline. * 60x60 white rect at center. Blue outline. */ /** * @method stroke * @param {String} value a color string * @chainable */ /** * @method stroke * @param {Number} gray a gray value * @param {Number} [alpha] * @chainable */ /** * @method stroke * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable */ /** * @method stroke * @param {p5.Color} color the stroke color * @chainable */ p5.prototype.stroke = function() { this._renderer._setProperty('_strokeSet', true); this._renderer._setProperty('_doStroke', true); this._renderer.stroke.apply(this._renderer, arguments); return this; }; module.exports = p5; },{"../core/constants":21,"../core/core":22,"./p5.Color":16}],18:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 2D Primitives * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); var canvas = _dereq_('./canvas'); _dereq_('./error_helpers'); /** * Draw an arc to the screen. If called with only x, y, w, h, start, and * stop, the arc will be drawn and filled as an open pie segment. If a mode parameter is provided, the arc * will be filled like an open semi-circle (OPEN) , a closed semi-circle (CHORD), or as a closed pie segment (PIE). The * origin may be changed with the ellipseMode() function.

* Note that drawing a full circle (ex: 0 to TWO_PI) will appear blank * because 0 and TWO_PI are the same position on the unit circle. The * best way to handle this is by using the ellipse() function instead * to create a closed ellipse, and to use the arc() function * only to draw parts of an ellipse. * * @method arc * @param {Number} x x-coordinate of the arc's ellipse * @param {Number} y y-coordinate of the arc's ellipse * @param {Number} w width of the arc's ellipse by default * @param {Number} h height of the arc's ellipse by default * @param {Number} start angle to start the arc, specified in radians * @param {Number} stop angle to stop the arc, specified in radians * @param {Constant} [mode] optional parameter to determine the way of drawing * the arc. either CHORD, PIE or OPEN * @chainable * @example *
* * arc(50, 55, 50, 50, 0, HALF_PI); * noFill(); * arc(50, 55, 60, 60, HALF_PI, PI); * arc(50, 55, 70, 70, PI, PI + QUARTER_PI); * arc(50, 55, 80, 80, PI + QUARTER_PI, TWO_PI); * *
* *
* * arc(50, 50, 80, 80, 0, PI + QUARTER_PI); * *
* *
* * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, OPEN); * *
* *
* * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, CHORD); * *
* *
* * arc(50, 50, 80, 80, 0, PI + QUARTER_PI, PIE); * *
* * @alt *shattered outline of an ellipse with a quarter of a white circle bottom-right. *white ellipse with top right quarter missing. *white ellipse with black outline with top right missing. *white ellipse with top right missing with black outline around shape. *white ellipse with top right quarter missing with black outline around the shape. * */ p5.prototype.arc = function(x, y, w, h, start, stop, mode) { p5._validateParameters('arc', arguments); if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } start = this._toRadians(start); stop = this._toRadians(stop); // Make all angles positive... while (start < 0) { start += constants.TWO_PI; } while (stop < 0) { stop += constants.TWO_PI; } // ...and confine them to the interval [0,TWO_PI). start %= constants.TWO_PI; stop %= constants.TWO_PI; // account for full circle if (stop === start) { stop += constants.TWO_PI; } // Adjust angles to counter linear scaling. if (start <= constants.HALF_PI) { start = Math.atan(w / h * Math.tan(start)); } else if (start > constants.HALF_PI && start <= 3 * constants.HALF_PI) { start = Math.atan(w / h * Math.tan(start)) + constants.PI; } else { start = Math.atan(w / h * Math.tan(start)) + constants.TWO_PI; } if (stop <= constants.HALF_PI) { stop = Math.atan(w / h * Math.tan(stop)); } else if (stop > constants.HALF_PI && stop <= 3 * constants.HALF_PI) { stop = Math.atan(w / h * Math.tan(stop)) + constants.PI; } else { stop = Math.atan(w / h * Math.tan(stop)) + constants.TWO_PI; } // Exceed the interval if necessary in order to preserve the size and // orientation of the arc. if (start > stop) { stop += constants.TWO_PI; } // p5 supports negative width and heights for ellipses w = Math.abs(w); h = Math.abs(h); this._renderer.arc(x, y, w, h, start, stop, mode); return this; }; /** * Draws an ellipse (oval) to the screen. An ellipse with equal width and * height is a circle. By default, the first two parameters set the location, * and the third and fourth parameters set the shape's width and height. If * no height is specified, the value of width is used for both the width and * height. If a negative height or width is specified, the absolute value is taken. * The origin may be changed with the ellipseMode() function. * * @method ellipse * @param {Number} x x-coordinate of the ellipse. * @param {Number} y y-coordinate of the ellipse. * @param {Number} w width of the ellipse. * @param {Number} [h] height of the ellipse. * @chainable * @example *
* * ellipse(56, 46, 55, 55); * *
* * @alt *white ellipse with black outline in middle-right of canvas that is 55x55. * */ /** * @method ellipse * @param {Number} x * @param {Number} y * @param {Number} w * @param {Number} h * @param {Integer} detail number of radial sectors to draw */ p5.prototype.ellipse = function(x, y, w, h, detailX) { p5._validateParameters('ellipse', arguments); // p5 supports negative width and heights for rects if (w < 0) { w = Math.abs(w); } if (typeof h === 'undefined') { // Duplicate 3rd argument if only 3 given. h = w; } else if (h < 0) { h = Math.abs(h); } if (this._renderer._doStroke || this._renderer._doFill) { var vals = canvas.modeAdjust(x, y, w, h, this._renderer._ellipseMode); this._renderer.ellipse([vals.x, vals.y, vals.w, vals.h, detailX]); } return this; }; /** * Draws a line (a direct path between two points) to the screen. The version * of line() with four parameters draws the line in 2D. To color a line, use * the stroke() function. A line cannot be filled, therefore the fill() * function will not affect the color of a line. 2D lines are drawn with a * width of one pixel by default, but this can be changed with the * strokeWeight() function. * * @method line * @param {Number} x1 the x-coordinate of the first point * @param {Number} y1 the y-coordinate of the first point * @param {Number} x2 the x-coordinate of the second point * @param {Number} y2 the y-coordinate of the second point * @chainable * @example *
* * line(30, 20, 85, 75); * *
* *
* * line(30, 20, 85, 20); * stroke(126); * line(85, 20, 85, 75); * stroke(255); * line(85, 75, 30, 75); * *
* * @alt *line 78 pixels long running from mid-top to bottom-right of canvas. *3 lines of various stroke sizes. Form top, bottom and right sides of a square. * */ /** * @method line * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 the z-coordinate of the first point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 the z-coordinate of the second point * @chainable */ p5.prototype.line = function() { p5._validateParameters('line', arguments); if (this._renderer._doStroke) { this._renderer.line.apply(this._renderer, arguments); } return this; }; /** * Draws a point, a coordinate in space at the dimension of one pixel. * The first parameter is the horizontal value for the point, the second * value is the vertical value for the point. The color of the point is * determined by the current stroke. * * @method point * @param {Number} x the x-coordinate * @param {Number} y the y-coordinate * @param {Number} [z] the z-coordinate (for WEBGL mode) * @chainable * @example *
* * point(30, 20); * point(85, 20); * point(85, 75); * point(30, 75); * *
* * @alt *4 points centered in the middle-right of the canvas. * */ p5.prototype.point = function() { p5._validateParameters('point', arguments); if (this._renderer._doStroke) { this._renderer.point.apply(this._renderer, arguments); } return this; }; /** * Draw a quad. A quad is a quadrilateral, a four sided polygon. It is * similar to a rectangle, but the angles between its edges are not * constrained to ninety degrees. The first pair of parameters (x1,y1) * sets the first vertex and the subsequent pairs should proceed * clockwise or counter-clockwise around the defined shape. * * @method quad * @param {Number} x1 the x-coordinate of the first point * @param {Number} y1 the y-coordinate of the first point * @param {Number} x2 the x-coordinate of the second point * @param {Number} y2 the y-coordinate of the second point * @param {Number} x3 the x-coordinate of the third point * @param {Number} y3 the y-coordinate of the third point * @param {Number} x4 the x-coordinate of the fourth point * @param {Number} y4 the y-coordinate of the fourth point * @chainable * @example *
* * quad(38, 31, 86, 20, 69, 63, 30, 76); * *
* * @alt *irregular white quadrilateral shape with black outline mid-right of canvas. * */ /** * @method quad * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 * @param {Number} x3 * @param {Number} y3 * @param {Number} z3 * @param {Number} x4 * @param {Number} y4 * @param {Number} z4 * @chainable */ p5.prototype.quad = function() { p5._validateParameters('quad', arguments); if (this._renderer._doStroke || this._renderer._doFill) { this._renderer.quad.apply(this._renderer, arguments); } return this; }; /** * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. The way these parameters are interpreted, however, * may be changed with the rectMode() function. *

* The fifth, sixth, seventh and eighth parameters, if specified, * determine corner radius for the top-right, top-left, lower-right and * lower-left corners, respectively. An omitted corner radius parameter is set * to the value of the previously specified radius value in the parameter list. * * @method rect * @param {Number} x x-coordinate of the rectangle. * @param {Number} y y-coordinate of the rectangle. * @param {Number} w width of the rectangle. * @param {Number} h height of the rectangle. * @param {Number} [tl] optional radius of top-left corner. * @param {Number} [tr] optional radius of top-right corner. * @param {Number} [br] optional radius of bottom-right corner. * @param {Number} [bl] optional radius of bottom-left corner. * @chainable * @example *
* * // Draw a rectangle at location (30, 20) with a width and height of 55. * rect(30, 20, 55, 55); * *
* *
* * // Draw a rectangle with rounded corners, each having a radius of 20. * rect(30, 20, 55, 55, 20); * *
* *
* * // Draw a rectangle with rounded corners having the following radii: * // top-left = 20, top-right = 15, bottom-right = 10, bottom-left = 5. * rect(30, 20, 55, 55, 20, 15, 10, 5); * *
* * @alt * 55x55 white rect with black outline in mid-right of canvas. * 55x55 white rect with black outline and rounded edges in mid-right of canvas. * 55x55 white rect with black outline and rounded edges of different radii. */ /** * @method rect * @param {Number} x * @param {Number} y * @param {Number} w * @param {Number} h * @param {Integer} [detailX] number of segments in the x-direction * @param {Integer} [detailY] number of segments in the y-direction * @chainable */ p5.prototype.rect = function() { p5._validateParameters('rect', arguments); if (this._renderer._doStroke || this._renderer._doFill) { var vals = canvas.modeAdjust( arguments[0], arguments[1], arguments[2], arguments[3], this._renderer._rectMode ); var args = [vals.x, vals.y, vals.w, vals.h]; // append the additional arguments (either cornder radii, or // segment details) to the argument list for (var i = 4; i < arguments.length; i++) { args[i] = arguments[i]; } this._renderer.rect(args); } return this; }; /** * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * @method triangle * @param {Number} x1 x-coordinate of the first point * @param {Number} y1 y-coordinate of the first point * @param {Number} x2 x-coordinate of the second point * @param {Number} y2 y-coordinate of the second point * @param {Number} x3 x-coordinate of the third point * @param {Number} y3 y-coordinate of the third point * @chainable * @example *
* * triangle(30, 75, 58, 20, 86, 75); * *
* *@alt * white triangle with black outline in mid-right of canvas. * */ p5.prototype.triangle = function() { p5._validateParameters('triangle', arguments); if (this._renderer._doStroke || this._renderer._doFill) { this._renderer.triangle(arguments); } return this; }; module.exports = p5; },{"./canvas":20,"./constants":21,"./core":22,"./error_helpers":25}],19:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Attributes * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); /** * Modifies the location from which ellipses are drawn by changing the way * in which parameters given to ellipse() are interpreted. *

* The default mode is ellipseMode(CENTER), which interprets the first two * parameters of ellipse() as the shape's center point, while the third and * fourth parameters are its width and height. *

* ellipseMode(RADIUS) also uses the first two parameters of ellipse() as * the shape's center point, but uses the third and fourth parameters to * specify half of the shapes's width and height. *

* ellipseMode(CORNER) interprets the first two parameters of ellipse() as * the upper-left corner of the shape, while the third and fourth parameters * are its width and height. *

* ellipseMode(CORNERS) interprets the first two parameters of ellipse() as * the location of one corner of the ellipse's bounding box, and the third * and fourth parameters as the location of the opposite corner. *

* The parameter must be written in ALL CAPS because Javascript is a * case-sensitive language. * * @method ellipseMode * @param {Constant} mode either CENTER, RADIUS, CORNER, or CORNERS * @chainable * @example *
* * ellipseMode(RADIUS); // Set ellipseMode to RADIUS * fill(255); // Set fill to white * ellipse(50, 50, 30, 30); // Draw white ellipse using RADIUS mode * * ellipseMode(CENTER); // Set ellipseMode to CENTER * fill(100); // Set fill to gray * ellipse(50, 50, 30, 30); // Draw gray ellipse using CENTER mode * *
* *
* * ellipseMode(CORNER); // Set ellipseMode is CORNER * fill(255); // Set fill to white * ellipse(25, 25, 50, 50); // Draw white ellipse using CORNER mode * * ellipseMode(CORNERS); // Set ellipseMode to CORNERS * fill(100); // Set fill to gray * ellipse(25, 25, 50, 50); // Draw gray ellipse using CORNERS mode * *
* * @alt * 60x60 white ellipse and 30x30 grey ellipse with black outlines at center. * 60x60 white ellipse @center and 30x30 grey ellipse top-right, black outlines. * */ p5.prototype.ellipseMode = function(m) { p5._validateParameters('ellipseMode', arguments); if ( m === constants.CORNER || m === constants.CORNERS || m === constants.RADIUS || m === constants.CENTER ) { this._renderer._ellipseMode = m; } return this; }; /** * Draws all geometry with jagged (aliased) edges. Note that smooth() is * active by default, so it is necessary to call noSmooth() to disable * smoothing of geometry, images, and fonts. * * @method noSmooth * @chainable * @example *
* * background(0); * noStroke(); * smooth(); * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); * *
* * @alt * 2 pixelated 36x36 white ellipses to left & right of center, black background * */ p5.prototype.noSmooth = function() { this._renderer.noSmooth(); return this; }; /** * Modifies the location from which rectangles are drawn by changing the way * in which parameters given to rect() are interpreted. *

* The default mode is rectMode(CORNER), which interprets the first two * parameters of rect() as the upper-left corner of the shape, while the * third and fourth parameters are its width and height. *

* rectMode(CORNERS) interprets the first two parameters of rect() as the * location of one corner, and the third and fourth parameters as the * location of the opposite corner. *

* rectMode(CENTER) interprets the first two parameters of rect() as the * shape's center point, while the third and fourth parameters are its * width and height. *

* rectMode(RADIUS) also uses the first two parameters of rect() as the * shape's center point, but uses the third and fourth parameters to specify * half of the shapes's width and height. *

* The parameter must be written in ALL CAPS because Javascript is a * case-sensitive language. * * @method rectMode * @param {Constant} mode either CORNER, CORNERS, CENTER, or RADIUS * @chainable * @example *
* * rectMode(CORNER); // Default rectMode is CORNER * fill(255); // Set fill to white * rect(25, 25, 50, 50); // Draw white rect using CORNER mode * * rectMode(CORNERS); // Set rectMode to CORNERS * fill(100); // Set fill to gray * rect(25, 25, 50, 50); // Draw gray rect using CORNERS mode * *
* *
* * rectMode(RADIUS); // Set rectMode to RADIUS * fill(255); // Set fill to white * rect(50, 50, 30, 30); // Draw white rect using RADIUS mode * * rectMode(CENTER); // Set rectMode to CENTER * fill(100); // Set fill to gray * rect(50, 50, 30, 30); // Draw gray rect using CENTER mode * *
* * @alt * 50x50 white rect at center and 25x25 grey rect in the top left of the other. * 50x50 white rect at center and 25x25 grey rect in the center of the other. * */ p5.prototype.rectMode = function(m) { p5._validateParameters('rectMode', arguments); if ( m === constants.CORNER || m === constants.CORNERS || m === constants.RADIUS || m === constants.CENTER ) { this._renderer._rectMode = m; } return this; }; /** * Draws all geometry with smooth (anti-aliased) edges. smooth() will also * improve image quality of resized images. Note that smooth() is active by * default; noSmooth() can be used to disable smoothing of geometry, * images, and fonts. * * @method smooth * @chainable * @example *
* * background(0); * noStroke(); * smooth(); * ellipse(30, 48, 36, 36); * noSmooth(); * ellipse(70, 48, 36, 36); * *
* * @alt * 2 pixelated 36x36 white ellipses one left one right of center. On black. * */ p5.prototype.smooth = function() { this._renderer.smooth(); return this; }; /** * Sets the style for rendering line endings. These ends are either squared, * extended, or rounded, each of which specified with the corresponding * parameters: SQUARE, PROJECT, and ROUND. The default cap is ROUND. * * @method strokeCap * @param {Constant} cap either SQUARE, PROJECT, or ROUND * @chainable * @example *
* * strokeWeight(12.0); * strokeCap(ROUND); * line(20, 30, 80, 30); * strokeCap(SQUARE); * line(20, 50, 80, 50); * strokeCap(PROJECT); * line(20, 70, 80, 70); * *
* * @alt * 3 lines. Top line: rounded ends, mid: squared, bottom:longer squared ends. * */ p5.prototype.strokeCap = function(cap) { p5._validateParameters('strokeCap', arguments); if ( cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT ) { this._renderer.strokeCap(cap); } return this; }; /** * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * * @method strokeJoin * @param {Constant} join either MITER, BEVEL, ROUND * @chainable * @example *
* * noFill(); * strokeWeight(10.0); * strokeJoin(MITER); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * *
* *
* * noFill(); * strokeWeight(10.0); * strokeJoin(BEVEL); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * *
* *
* * noFill(); * strokeWeight(10.0); * strokeJoin(ROUND); * beginShape(); * vertex(35, 20); * vertex(65, 50); * vertex(35, 80); * endShape(); * *
* * @alt * Right-facing arrowhead shape with pointed tip in center of canvas. * Right-facing arrowhead shape with flat tip in center of canvas. * Right-facing arrowhead shape with rounded tip in center of canvas. * */ p5.prototype.strokeJoin = function(join) { p5._validateParameters('strokeJoin', arguments); if ( join === constants.ROUND || join === constants.BEVEL || join === constants.MITER ) { this._renderer.strokeJoin(join); } return this; }; /** * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * * @method strokeWeight * @param {Number} weight the weight (in pixels) of the stroke * @chainable * @example *
* * strokeWeight(1); // Default * line(20, 20, 80, 20); * strokeWeight(4); // Thicker * line(20, 40, 80, 40); * strokeWeight(10); // Beastly * line(20, 70, 80, 70); * *
* * @alt * 3 horizontal black lines. Top line: thin, mid: medium, bottom:thick. * */ p5.prototype.strokeWeight = function(w) { p5._validateParameters('strokeWeight', arguments); this._renderer.strokeWeight(w); return this; }; module.exports = p5; },{"./constants":21,"./core":22}],20:[function(_dereq_,module,exports){ /** * @requires constants */ 'use strict'; var constants = _dereq_('./constants'); module.exports = { modeAdjust: function(a, b, c, d, mode) { if (mode === constants.CORNER) { return { x: a, y: b, w: c, h: d }; } else if (mode === constants.CORNERS) { return { x: a, y: b, w: c - a, h: d - b }; } else if (mode === constants.RADIUS) { return { x: a - c, y: b - d, w: 2 * c, h: 2 * d }; } else if (mode === constants.CENTER) { return { x: a - c * 0.5, y: b - d * 0.5, w: c, h: d }; } }, arcModeAdjust: function(a, b, c, d, mode) { if (mode === constants.CORNER) { return { x: a + c * 0.5, y: b + d * 0.5, w: c, h: d }; } else if (mode === constants.CORNERS) { return { x: a, y: b, w: c + a, h: d + b }; } else if (mode === constants.RADIUS) { return { x: a, y: b, w: 2 * c, h: 2 * d }; } else if (mode === constants.CENTER) { return { x: a, y: b, w: c, h: d }; } } }; },{"./constants":21}],21:[function(_dereq_,module,exports){ /** * @module Constants * @submodule Constants * @for p5 */ 'use strict'; var PI = Math.PI; module.exports = { // GRAPHICS RENDERER /** * @property {String} P2D * @final */ P2D: 'p2d', /** * @property {String} WEBGL * @final */ WEBGL: 'webgl', // ENVIRONMENT ARROW: 'default', CROSS: 'crosshair', HAND: 'pointer', MOVE: 'move', TEXT: 'text', WAIT: 'wait', // TRIGONOMETRY /** * HALF_PI is a mathematical constant with the value * 1.57079632679489661923. It is half the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions sin() and cos(). * * @property {Number} HALF_PI * @final * * @example *
* arc(50, 50, 80, 80, 0, HALF_PI); *
* * @alt * 80x80 white quarter-circle with curve toward bottom right of canvas. * */ HALF_PI: PI / 2, /** * PI is a mathematical constant with the value * 3.14159265358979323846. It is the ratio of the circumference * of a circle to its diameter. It is useful in combination with * the trigonometric functions sin() and cos(). * * @property {Number} PI * @final * * @example *
* arc(50, 50, 80, 80, 0, PI); *
* * @alt * white half-circle with curve toward bottom of canvas. * */ PI: PI, /** * QUARTER_PI is a mathematical constant with the value 0.7853982. * It is one quarter the ratio of the circumference of a circle to * its diameter. It is useful in combination with the trigonometric * functions sin() and cos(). * * @property {Number} QUARTER_PI * @final * * @example *
* arc(50, 50, 80, 80, 0, QUARTER_PI); *
* * @alt * white eighth-circle rotated about 40 degrees with curve bottom right canvas. * */ QUARTER_PI: PI / 4, /** * TAU is an alias for TWO_PI, a mathematical constant with the * value 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions sin() and cos(). * * @property {Number} TAU * @final * * @example *
* arc(50, 50, 80, 80, 0, TAU); *
* * @alt * 80x80 white ellipse shape in center of canvas. * */ TAU: PI * 2, /** * TWO_PI is a mathematical constant with the value * 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions sin() and cos(). * * @property {Number} TWO_PI * @final * * @example *
* arc(50, 50, 80, 80, 0, TWO_PI); *
* * @alt * 80x80 white ellipse shape in center of canvas. * */ TWO_PI: PI * 2, /** * Constant to be used with angleMode() function, to set the mode which * p5.js interprates and calculates angles (either DEGREES or RADIANS). * @property {String} DEGREES * @final * * @example *
* function setup() { * angleMode(DEGREES); * } *
*/ DEGREES: 'degrees', /** * Constant to be used with angleMode() function, to set the mode which * p5.js interprates and calculates angles (either RADIANS or DEGREES). * @property {String} RADIANS * @final * * @example *
* function setup() { * angleMode(RADIANS); * } *
*/ RADIANS: 'radians', DEG_TO_RAD: PI / 180.0, RAD_TO_DEG: 180.0 / PI, // SHAPE /** * @property {String} CORNER * @final */ CORNER: 'corner', /** * @property {String} CORNERS * @final */ CORNERS: 'corners', /** * @property {String} RADIUS * @final */ RADIUS: 'radius', /** * @property {String} RIGHT * @final */ RIGHT: 'right', /** * @property {String} LEFT * @final */ LEFT: 'left', /** * @property {String} CENTER * @final */ CENTER: 'center', /** * @property {String} TOP * @final */ TOP: 'top', /** * @property {String} BOTTOM * @final */ BOTTOM: 'bottom', /** * @property {String} BASELINE * @final * @default alphabetic */ BASELINE: 'alphabetic', /** * @property {Number} POINTS * @final * @default 0x0000 */ POINTS: 0x0000, /** * @property {Number} LINES * @final * @default 0x0001 */ LINES: 0x0001, /** * @property {Number} LINE_STRIP * @final * @default 0x0003 */ LINE_STRIP: 0x0003, /** * @property {Number} LINE_LOOP * @final * @default 0x0002 */ LINE_LOOP: 0x0002, /** * @property {Number} TRIANGLES * @final * @default 0x0004 */ TRIANGLES: 0x0004, /** * @property {Number} TRIANGLE_FAN * @final * @default 0x0006 */ TRIANGLE_FAN: 0x0006, /** * @property {Number} TRIANGLE_STRIP * @final * @default 0x0005 */ TRIANGLE_STRIP: 0x0005, /** * @property {String} QUADS * @final */ QUADS: 'quads', /** * @property {String} QUAD_STRIP * @final * @default quad_strip */ QUAD_STRIP: 'quad_strip', /** * @property {String} CLOSE * @final */ CLOSE: 'close', /** * @property {String} OPEN * @final */ OPEN: 'open', /** * @property {String} CHORD * @final */ CHORD: 'chord', /** * @property {String} PIE * @final */ PIE: 'pie', /** * @property {String} PROJECT * @final * @default square */ PROJECT: 'square', // PEND: careful this is counterintuitive /** * @property {String} SQUARE * @final * @default butt */ SQUARE: 'butt', /** * @property {String} ROUND * @final */ ROUND: 'round', /** * @property {String} BEVEL * @final */ BEVEL: 'bevel', /** * @property {String} MITER * @final */ MITER: 'miter', // COLOR /** * @property {String} RGB * @final */ RGB: 'rgb', /** * @property {String} HSB * @final */ HSB: 'hsb', /** * @property {String} HSL * @final */ HSL: 'hsl', // DOM EXTENSION AUTO: 'auto', // INPUT ALT: 18, BACKSPACE: 8, CONTROL: 17, DELETE: 46, DOWN_ARROW: 40, ENTER: 13, ESCAPE: 27, LEFT_ARROW: 37, OPTION: 18, RETURN: 13, RIGHT_ARROW: 39, SHIFT: 16, TAB: 9, UP_ARROW: 38, // RENDERING /** * @property {String} BLEND * @final * @default source-over */ BLEND: 'source-over', /** * @property {String} ADD * @final * @default lighter */ ADD: 'lighter', //ADD: 'add', // //SUBTRACT: 'subtract', // /** * @property {String} DARKEST * @final */ DARKEST: 'darken', /** * @property {String} LIGHTEST * @final * @default lighten */ LIGHTEST: 'lighten', /** * @property {String} DIFFERENCE * @final */ DIFFERENCE: 'difference', /** * @property {String} EXCLUSION * @final */ EXCLUSION: 'exclusion', /** * @property {String} MULTIPLY * @final */ MULTIPLY: 'multiply', /** * @property {String} SCREEN * @final */ SCREEN: 'screen', /** * @property {String} REPLACE * @final * @default copy */ REPLACE: 'copy', /** * @property {String} OVERLAY * @final */ OVERLAY: 'overlay', /** * @property {String} HARD_LIGHT * @final */ HARD_LIGHT: 'hard-light', /** * @property {String} SOFT_LIGHT * @final */ SOFT_LIGHT: 'soft-light', /** * @property {String} DODGE * @final * @default color-dodge */ DODGE: 'color-dodge', /** * @property {String} BURN * @final * @default color-burn */ BURN: 'color-burn', // FILTERS /** * @property {String} THRESHOLD * @final */ THRESHOLD: 'threshold', /** * @property {String} GRAY * @final */ GRAY: 'gray', /** * @property {String} OPAQUE * @final */ OPAQUE: 'opaque', /** * @property {String} INVERT * @final */ INVERT: 'invert', /** * @property {String} POSTERIZE * @final */ POSTERIZE: 'posterize', /** * @property {String} DILATE * @final */ DILATE: 'dilate', /** * @property {String} ERODE * @final */ ERODE: 'erode', /** * @property {String} BLUR * @final */ BLUR: 'blur', // TYPOGRAPHY /** * @property {String} NORMAL * @final */ NORMAL: 'normal', /** * @property {String} ITALIC * @final */ ITALIC: 'italic', /** * @property {String} BOLD * @final */ BOLD: 'bold', // TYPOGRAPHY-INTERNAL _DEFAULT_TEXT_FILL: '#000000', _DEFAULT_LEADMULT: 1.25, _CTX_MIDDLE: 'middle', // VERTICES LINEAR: 'linear', QUADRATIC: 'quadratic', BEZIER: 'bezier', CURVE: 'curve', // WEBGL DRAWMODES STROKE: 'stroke', FILL: 'fill', TEXTURE: 'texture', IMMEDIATE: 'immediate', // DEVICE-ORIENTATION /** * @property {String} LANDSCAPE * @final */ LANDSCAPE: 'landscape', /** * @property {String} PORTRAIT * @final */ PORTRAIT: 'portrait', // DEFAULTS _DEFAULT_STROKE: '#000000', _DEFAULT_FILL: '#FFFFFF' }; },{}],22:[function(_dereq_,module,exports){ /** * @module Structure * @submodule Structure * @for p5 * @requires constants */ 'use strict'; _dereq_('./shim'); // Core needs the PVariables object var constants = _dereq_('./constants'); /** * This is the p5 instance constructor. * * A p5 instance holds all the properties and methods related to * a p5 sketch. It expects an incoming sketch closure and it can also * take an optional node parameter for attaching the generated p5 canvas * to a node. The sketch closure takes the newly created p5 instance as * its sole argument and may optionally set preload(), setup(), and/or * draw() properties on it for running a sketch. * * A p5 sketch can run in "global" or "instance" mode: * "global" - all properties and methods are attached to the window * "instance" - all properties and methods are bound to this p5 object * * @class p5 * @constructor * @param {function} sketch a closure that can set optional preload(), * setup(), and/or draw() properties on the * given p5 instance * @param {HTMLElement|Boolean} [node] element to attach canvas to, if a * boolean is passed in use it as sync * @param {Boolean} [sync] start synchronously (optional) * @return {p5} a p5 instance */ var p5 = function(sketch, node, sync) { if (typeof node === 'boolean' && typeof sync === 'undefined') { sync = node; node = undefined; } ////////////////////////////////////////////// // PUBLIC p5 PROPERTIES AND METHODS ////////////////////////////////////////////// /** * Called directly before setup(), the preload() function is used to handle * asynchronous loading of external files in a blocking way. If a preload * function is defined, setup() will wait until any load calls within have * finished. Nothing besides load calls (loadImage, loadJSON, loadFont, * loadStrings, etc.) should be inside preload function. If asynchronous * loading is preferred, the load methods can instead be called in setup() * or anywhere else with the use of a callback parameter. *

* By default the text "loading..." will be displayed. To make your own * loading page, include an HTML element with id "p5_loading" in your * page. More information here. * * @method preload * @example *
* var img; * var c; * function preload() { // preload() runs once * img = loadImage('assets/laDefense.jpg'); * } * * function setup() { // setup() waits until preload() is done * img.loadPixels(); * // get color of middle pixel * c = img.get(img.width / 2, img.height / 2); * } * * function draw() { * background(c); * image(img, 25, 25, 50, 50); * } *
* * @alt * nothing displayed * */ /** * The setup() function is called once when the program starts. It's used to * define initial environment properties such as screen size and background * color and to load media such as images and fonts as the program starts. * There can only be one setup() function for each program and it shouldn't * be called again after its initial execution. *

* Note: Variables declared within setup() are not accessible within other * functions, including draw(). * * @method setup * @example *
* var a = 0; * * function setup() { * background(0); * noStroke(); * fill(102); * } * * function draw() { * rect(a++ % width, 10, 2, 80); * } *
* * @alt * nothing displayed * */ /** * Called directly after setup(), the draw() function continuously executes * the lines of code contained inside its block until the program is stopped * or noLoop() is called. Note if noLoop() is called in setup(), draw() will * still be executed once before stopping. draw() is called automatically and * should never be called explicitly. *

* It should always be controlled with noLoop(), redraw() and loop(). After * noLoop() stops the code in draw() from executing, redraw() causes the * code inside draw() to execute once, and loop() will cause the code * inside draw() to resume executing continuously. *

* The number of times draw() executes in each second may be controlled with * the frameRate() function. *

* There can only be one draw() function for each sketch, and draw() must * exist if you want the code to run continuously, or to process events such * as mousePressed(). Sometimes, you might have an empty call to draw() in * your program, as shown in the above example. *

* It is important to note that the drawing coordinate system will be reset * at the beginning of each draw() call. If any transformations are performed * within draw() (ex: scale, rotate, translate), their effects will be * undone at the beginning of draw(), so transformations will not accumulate * over time. On the other hand, styling applied (ex: fill, stroke, etc) will * remain in effect. * * @method draw * @example *
* var yPos = 0; * function setup() { // setup() runs once * frameRate(30); * } * function draw() { // draw() loops forever, until stopped * background(204); * yPos = yPos - 1; * if (yPos < 0) { * yPos = height; * } * line(0, yPos, width, yPos); * } *
* * @alt * nothing displayed * */ ////////////////////////////////////////////// // PRIVATE p5 PROPERTIES AND METHODS ////////////////////////////////////////////// this._setupDone = false; // for handling hidpi this._pixelDensity = Math.ceil(window.devicePixelRatio) || 1; this._userNode = node; this._curElement = null; this._elements = []; this._requestAnimId = 0; this._preloadCount = 0; this._isGlobal = false; this._loop = true; this._initializeInstanceVariables(); this._defaultCanvasSize = { width: 100, height: 100 }; this._events = { // keep track of user-events for unregistering later mousemove: null, mousedown: null, mouseup: null, dragend: null, dragover: null, click: null, dblclick: null, mouseover: null, mouseout: null, keydown: null, keyup: null, keypress: null, touchstart: null, touchmove: null, touchend: null, resize: null, blur: null }; this._events.wheel = null; this._loadingScreenId = 'p5_loading'; // Allows methods to be registered on an instance that // are instance-specific. this._registeredMethods = {}; var methods = Object.getOwnPropertyNames(p5.prototype._registeredMethods); for (var i = 0; i < methods.length; i++) { var prop = methods[i]; this._registeredMethods[prop] = p5.prototype._registeredMethods[ prop ].slice(); } if (window.DeviceOrientationEvent) { this._events.deviceorientation = null; } if (window.DeviceMotionEvent && !window._isNodeWebkit) { this._events.devicemotion = null; } this._start = function() { // Find node if id given if (this._userNode) { if (typeof this._userNode === 'string') { this._userNode = document.getElementById(this._userNode); } } var userPreload = this.preload || window.preload; // look for "preload" if (userPreload) { // Setup loading screen // Set loading screen into dom if not present // Otherwise displays and removes user provided loading screen var loadingScreen = document.getElementById(this._loadingScreenId); if (!loadingScreen) { loadingScreen = document.createElement('div'); loadingScreen.innerHTML = 'Loading...'; loadingScreen.style.position = 'absolute'; loadingScreen.id = this._loadingScreenId; var node = this._userNode || document.body; node.appendChild(loadingScreen); } // var methods = this._preloadMethods; for (var method in this._preloadMethods) { // default to p5 if no object defined this._preloadMethods[method] = this._preloadMethods[method] || p5; var obj = this._preloadMethods[method]; //it's p5, check if it's global or instance if (obj === p5.prototype || obj === p5) { if (this._isGlobal) { window[method] = this._wrapPreload(this, method); } obj = this; } this._registeredPreloadMethods[method] = obj[method]; obj[method] = this._wrapPreload(obj, method); } userPreload(); this._runIfPreloadsAreDone(); } else { this._setup(); this._runFrames(); this._draw(); } }.bind(this); this._runIfPreloadsAreDone = function() { var context = this._isGlobal ? window : this; if (context._preloadCount === 0) { var loadingScreen = document.getElementById(context._loadingScreenId); if (loadingScreen) { loadingScreen.parentNode.removeChild(loadingScreen); } context._setup(); context._runFrames(); context._draw(); } }; this._decrementPreload = function() { var context = this._isGlobal ? window : this; if (typeof context.preload === 'function') { context._setProperty('_preloadCount', context._preloadCount - 1); context._runIfPreloadsAreDone(); } }; this._wrapPreload = function(obj, fnName) { return function() { //increment counter this._incrementPreload(); //call original function return this._registeredPreloadMethods[fnName].apply(obj, arguments); }.bind(this); }; this._incrementPreload = function() { var context = this._isGlobal ? window : this; context._setProperty('_preloadCount', context._preloadCount + 1); }; this._setup = function() { // Always create a default canvas. // Later on if the user calls createCanvas, this default one // will be replaced this.createCanvas( this._defaultCanvasSize.width, this._defaultCanvasSize.height, 'p2d' ); // return preload functions to their normal vals if switched by preload var context = this._isGlobal ? window : this; if (typeof context.preload === 'function') { for (var f in this._preloadMethods) { context[f] = this._preloadMethods[f][f]; if (context[f] && this) { context[f] = context[f].bind(this); } } } // Short-circuit on this, in case someone used the library in "global" // mode earlier if (typeof context.setup === 'function') { context.setup(); } // unhide any hidden canvases that were created var canvases = document.getElementsByTagName('canvas'); for (var i = 0; i < canvases.length; i++) { var k = canvases[i]; if (k.dataset.hidden === 'true') { k.style.visibility = ''; delete k.dataset.hidden; } } this._setupDone = true; }.bind(this); this._draw = function() { var now = window.performance.now(); var time_since_last = now - this._lastFrameTime; var target_time_between_frames = 1000 / this._targetFrameRate; // only draw if we really need to; don't overextend the browser. // draw if we're within 5ms of when our next frame should paint // (this will prevent us from giving up opportunities to draw // again when it's really about time for us to do so). fixes an // issue where the frameRate is too low if our refresh loop isn't // in sync with the browser. note that we have to draw once even // if looping is off, so we bypass the time delay if that // is the case. var epsilon = 5; if ( !this._loop || time_since_last >= target_time_between_frames - epsilon ) { //mandatory update values(matrixs and stack) this.redraw(); this._frameRate = 1000.0 / (now - this._lastFrameTime); this._lastFrameTime = now; // If the user is actually using mouse module, then update // coordinates, otherwise skip. We can test this by simply // checking if any of the mouse functions are available or not. // NOTE : This reflects only in complete build or modular build. if (typeof this._updateMouseCoords !== 'undefined') { this._updateMouseCoords(); } } // get notified the next time the browser gives us // an opportunity to draw. if (this._loop) { this._requestAnimId = window.requestAnimationFrame(this._draw); } }.bind(this); this._runFrames = function() { if (this._updateInterval) { clearInterval(this._updateInterval); } }.bind(this); this._setProperty = function(prop, value) { this[prop] = value; if (this._isGlobal) { window[prop] = value; } }.bind(this); /** * Removes the entire p5 sketch. This will remove the canvas and any * elements created by p5.js. It will also stop the draw loop and unbind * any properties or methods from the window global scope. It will * leave a variable p5 in case you wanted to create a new p5 sketch. * If you like, you can set p5 = null to erase it. While all functions and * variables and objects created by the p5 library will be removed, any * other global variables created by your code will remain. * * @method remove * @example *
* function draw() { * ellipse(50, 50, 10, 10); * } * * function mousePressed() { * remove(); // remove whole sketch on mouse press * } *
* * @alt * nothing displayed * */ this.remove = function() { var loadingScreen = document.getElementById(this._loadingScreenId); if (loadingScreen) { loadingScreen.parentNode.removeChild(loadingScreen); // Add 1 to preload counter to prevent the sketch ever executing setup() this._incrementPreload(); } if (this._curElement) { // stop draw this._loop = false; if (this._requestAnimId) { window.cancelAnimationFrame(this._requestAnimId); } // unregister events sketch-wide for (var ev in this._events) { window.removeEventListener(ev, this._events[ev]); } // remove DOM elements created by p5, and listeners for (var i = 0; i < this._elements.length; i++) { var e = this._elements[i]; if (e.elt.parentNode) { e.elt.parentNode.removeChild(e.elt); } for (var elt_ev in e._events) { e.elt.removeEventListener(elt_ev, e._events[elt_ev]); } } // call any registered remove functions var self = this; this._registeredMethods.remove.forEach(function(f) { if (typeof f !== 'undefined') { f.call(self); } }); } // remove window bound properties and methods if (this._isGlobal) { for (var p in p5.prototype) { try { delete window[p]; } catch (x) { window[p] = undefined; } } for (var p2 in this) { if (this.hasOwnProperty(p2)) { try { delete window[p2]; } catch (x) { window[p2] = undefined; } } } p5.instance = null; } }.bind(this); // call any registered init functions this._registeredMethods.init.forEach(function(f) { if (typeof f !== 'undefined') { f.call(this); } }, this); var friendlyBindGlobal = this._createFriendlyGlobalFunctionBinder(); // If the user has created a global setup or draw function, // assume "global" mode and make everything global (i.e. on the window) if (!sketch) { this._isGlobal = true; p5.instance = this; // Loop through methods on the prototype and attach them to the window for (var p in p5.prototype) { if (typeof p5.prototype[p] === 'function') { var ev = p.substring(2); if (!this._events.hasOwnProperty(ev)) { if (Math.hasOwnProperty(p) && Math[p] === p5.prototype[p]) { // Multiple p5 methods are just native Math functions. These can be // called without any binding. friendlyBindGlobal(p, p5.prototype[p]); } else { friendlyBindGlobal(p, p5.prototype[p].bind(this)); } } } else { friendlyBindGlobal(p, p5.prototype[p]); } } // Attach its properties to the window for (var p2 in this) { if (this.hasOwnProperty(p2)) { friendlyBindGlobal(p2, this[p2]); } } } else { // Else, the user has passed in a sketch closure that may set // user-provided 'setup', 'draw', etc. properties on this instance of p5 sketch(this); } // Bind events to window (not using container div bc key events don't work) for (var e in this._events) { var f = this['_on' + e]; if (f) { var m = f.bind(this); window.addEventListener(e, m, { passive: false }); this._events[e] = m; } } var focusHandler = function() { this._setProperty('focused', true); }.bind(this); var blurHandler = function() { this._setProperty('focused', false); }.bind(this); window.addEventListener('focus', focusHandler); window.addEventListener('blur', blurHandler); this.registerMethod('remove', function() { window.removeEventListener('focus', focusHandler); window.removeEventListener('blur', blurHandler); }); if (sync) { this._start(); } else { if (document.readyState === 'complete') { this._start(); } else { window.addEventListener('load', this._start.bind(this), false); } } }; p5.prototype._initializeInstanceVariables = function() { this._styles = []; this._bezierDetail = 20; this._curveDetail = 20; this._colorMode = constants.RGB; this._colorMaxes = { rgb: [255, 255, 255, 255], hsb: [360, 100, 100, 1], hsl: [360, 100, 100, 1] }; }; // This is a pointer to our global mode p5 instance, if we're in // global mode. p5.instance = null; // Allows for the friendly error system to be turned off when creating a sketch, // which can give a significant boost to performance when needed. p5.disableFriendlyErrors = false; // attach constants to p5 prototype for (var k in constants) { p5.prototype[k] = constants[k]; } // functions that cause preload to wait // more can be added by using registerPreloadMethod(func) p5.prototype._preloadMethods = { loadJSON: p5.prototype, loadImage: p5.prototype, loadStrings: p5.prototype, loadXML: p5.prototype, loadBytes: p5.prototype, loadShape: p5.prototype, loadTable: p5.prototype, loadFont: p5.prototype, loadModel: p5.prototype, loadShader: p5.prototype }; p5.prototype._registeredMethods = { init: [], pre: [], post: [], remove: [] }; p5.prototype._registeredPreloadMethods = {}; p5.prototype.registerPreloadMethod = function(fnString, obj) { // obj = obj || p5.prototype; if (!p5.prototype._preloadMethods.hasOwnProperty(fnString)) { p5.prototype._preloadMethods[fnString] = obj; } }; p5.prototype.registerMethod = function(name, m) { var target = this || p5.prototype; if (!target._registeredMethods.hasOwnProperty(name)) { target._registeredMethods[name] = []; } target._registeredMethods[name].push(m); }; p5.prototype._createFriendlyGlobalFunctionBinder = function(options) { options = options || {}; var globalObject = options.globalObject || window; var log = options.log || console.log.bind(console); var propsToForciblyOverwrite = { // p5.print actually always overwrites an existing global function, // albeit one that is very unlikely to be used: // // https://developer.mozilla.org/en-US/docs/Web/API/Window/print print: true }; return function(prop, value) { if ( !p5.disableFriendlyErrors && typeof IS_MINIFIED === 'undefined' && typeof value === 'function' && !(prop in p5.prototype._preloadMethods) ) { try { // Because p5 has so many common function names, it's likely // that users may accidentally overwrite global p5 functions with // their own variables. Let's allow this but log a warning to // help users who may be doing this unintentionally. // // For more information, see: // // https://github.com/processing/p5.js/issues/1317 if (prop in globalObject && !(prop in propsToForciblyOverwrite)) { throw new Error('global "' + prop + '" already exists'); } // It's possible that this might throw an error because there // are a lot of edge-cases in which `Object.defineProperty` might // not succeed; since this functionality is only intended to // help beginners anyways, we'll just catch such an exception // if it occurs, and fall back to legacy behavior. Object.defineProperty(globalObject, prop, { configurable: true, enumerable: true, get: function() { return value; }, set: function(newValue) { Object.defineProperty(globalObject, prop, { configurable: true, enumerable: true, value: newValue, writable: true }); log( 'You just changed the value of "' + prop + '", which was ' + "a p5 function. This could cause problems later if you're " + 'not careful.' ); } }); } catch (e) { log( 'p5 had problems creating the global function "' + prop + '", ' + 'possibly because your code is already using that name as ' + 'a variable. You may want to rename your variable to something ' + 'else.' ); globalObject[prop] = value; } } else { globalObject[prop] = value; } }; }; module.exports = p5; },{"./constants":21,"./shim":32}],23:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Curves * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('./core'); _dereq_('./error_helpers'); /** * Draws a cubic Bezier curve on the screen. These curves are defined by a * series of anchor and control points. The first two parameters specify * the first anchor point and the last two parameters specify the other * anchor point, which become the first and last points on the curve. The * middle parameters specify the two control points which define the shape * of the curve. Approximately speaking, control points "pull" the curve * towards them.

Bezier curves were developed by French * automotive engineer Pierre Bezier, and are commonly used in computer * graphics to define gently sloping curves. See also curve(). * * @method bezier * @param {Number} x1 x-coordinate for the first anchor point * @param {Number} y1 y-coordinate for the first anchor point * @param {Number} x2 x-coordinate for the first control point * @param {Number} y2 y-coordinate for the first control point * @param {Number} x3 x-coordinate for the second control point * @param {Number} y3 y-coordinate for the second control point * @param {Number} x4 x-coordinate for the second anchor point * @param {Number} y4 y-coordinate for the second anchor point * @chainable * @example *
* * noFill(); * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * *
* *
* * background(0, 0, 0); * noFill(); * stroke(255); * bezier(250, 250, 0, 100, 100, 0, 100, 0, 0, 0, 100, 0); * *
* * @alt * stretched black s-shape in center with orange lines extending from end points. * stretched black s-shape with 10 5x5 white ellipses along the shape. * stretched black s-shape with 7 5x5 ellipses and orange lines along the shape. * stretched black s-shape with 17 small orange lines extending from under shape. * horseshoe shape with orange ends facing left and black curved center. * horseshoe shape with orange ends facing left and black curved center. * Line shaped like right-facing arrow,points move with mouse-x and warp shape. * horizontal line that hooks downward on the right and 13 5x5 ellipses along it. * right curving line mid-right of canvas with 7 short lines radiating from it. */ /** * @method bezier * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 z-coordinate for the first anchor point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 z-coordinate for the first control point * @param {Number} x3 * @param {Number} y3 * @param {Number} z3 z-coordinate for the second control point * @param {Number} x4 * @param {Number} y4 * @param {Number} z4 z-coordinate for the second anchor point * @chainable */ p5.prototype.bezier = function() { p5._validateParameters('bezier', arguments); if (this._renderer._doStroke || this._renderer._doFill) { this._renderer.bezier.apply(this._renderer, arguments); } return this; }; /** * Sets the resolution at which Beziers display. * * The default value is 20. * * This function is only useful when using the WEBGL renderer * as the default canvas renderer does not use this information. * * @method bezierDetail * @param {Number} detail resolution of the curves * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * noFill(); * * bezierDetail(5); * } * * function draw() { * background(200); * * // prettier-ignore * bezier(-40, -40, 0, * 90, -40, 0, * -90, 40, 0, * 40, 40, 0); * } * *
* * @alt * stretched black s-shape with a low level of bezier detail * */ p5.prototype.bezierDetail = function(d) { p5._validateParameters('bezierDetail', arguments); this._bezierDetail = d; return this; }; /** * Evaluates the Bezier at position t for points a, b, c, d. * The parameters a and d are the first and last points * on the curve, and b and c are the control points. * The final parameter t varies between 0 and 1. * This can be done once with the x coordinates and a second time * with the y coordinates to get the location of a bezier curve at t. * * @method bezierPoint * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the value of the Bezier at position t * @example *
* * noFill(); * var x1 = 85, x2 = 10, x3 = 90, x4 = 15; * var y1 = 20, y2 = 10, y3 = 90, y4 = 80; * bezier(x1, y1, x2, y2, x3, y3, x4, y4); * fill(255); * var steps = 10; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = bezierPoint(x1, x2, x3, x4, t); * var y = bezierPoint(y1, y2, y3, y4, t); * ellipse(x, y, 5, 5); * } * *
* * @alt * stretched black s-shape with 17 small orange lines extending from under shape. * */ p5.prototype.bezierPoint = function(a, b, c, d, t) { p5._validateParameters('bezierPoint', arguments); var adjustedT = 1 - t; return ( Math.pow(adjustedT, 3) * a + 3 * Math.pow(adjustedT, 2) * t * b + 3 * adjustedT * Math.pow(t, 2) * c + Math.pow(t, 3) * d ); }; /** * Evaluates the tangent to the Bezier at position t for points a, b, c, d. * The parameters a and d are the first and last points * on the curve, and b and c are the control points. * The final parameter t varies between 0 and 1. * * @method bezierTangent * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the tangent at position t * @example *
* * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * var steps = 6; * fill(255); * for (var i = 0; i <= steps; i++) { * var t = i / steps; * // Get the location of the point * var x = bezierPoint(85, 10, 90, 15, t); * var y = bezierPoint(20, 10, 90, 80, t); * // Get the tangent points * var tx = bezierTangent(85, 10, 90, 15, t); * var ty = bezierTangent(20, 10, 90, 80, t); * // Calculate an angle from the tangent points * var a = atan2(ty, tx); * a += PI; * stroke(255, 102, 0); * line(x, y, cos(a) * 30 + x, sin(a) * 30 + y); * // The following line of code makes a line * // inverse of the above line * //line(x, y, cos(a)*-30 + x, sin(a)*-30 + y); * stroke(0); * ellipse(x, y, 5, 5); * } * *
* *
* * noFill(); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * stroke(255, 102, 0); * var steps = 16; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = bezierPoint(85, 10, 90, 15, t); * var y = bezierPoint(20, 10, 90, 80, t); * var tx = bezierTangent(85, 10, 90, 15, t); * var ty = bezierTangent(20, 10, 90, 80, t); * var a = atan2(ty, tx); * a -= HALF_PI; * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y); * } * *
* * @alt * s-shaped line with 17 short orange lines extending from underside of shape * */ p5.prototype.bezierTangent = function(a, b, c, d, t) { p5._validateParameters('bezierTangent', arguments); var adjustedT = 1 - t; return ( 3 * d * Math.pow(t, 2) - 3 * c * Math.pow(t, 2) + 6 * c * adjustedT * t - 6 * b * adjustedT * t + 3 * b * Math.pow(adjustedT, 2) - 3 * a * Math.pow(adjustedT, 2) ); }; /** * Draws a curved line on the screen between two points, given as the * middle four parameters. The first two parameters are a control point, as * if the curve came from this point even though it's not drawn. The last * two parameters similarly describe the other control point.

* Longer curves can be created by putting a series of curve() functions * together or using curveVertex(). An additional function called * curveTightness() provides control for the visual quality of the curve. * The curve() function is an implementation of Catmull-Rom splines. * * @method curve * @param {Number} x1 x-coordinate for the beginning control point * @param {Number} y1 y-coordinate for the beginning control point * @param {Number} x2 x-coordinate for the first point * @param {Number} y2 y-coordinate for the first point * @param {Number} x3 x-coordinate for the second point * @param {Number} y3 y-coordinate for the second point * @param {Number} x4 x-coordinate for the ending control point * @param {Number} y4 y-coordinate for the ending control point * @chainable * @example *
* * noFill(); * stroke(255, 102, 0); * curve(5, 26, 5, 26, 73, 24, 73, 61); * stroke(0); * curve(5, 26, 73, 24, 73, 61, 15, 65); * stroke(255, 102, 0); * curve(73, 24, 73, 61, 15, 65, 15, 65); * *
*
* * // Define the curve points as JavaScript objects * var p1 = { x: 5, y: 26 }, p2 = { x: 73, y: 24 }; * var p3 = { x: 73, y: 61 }, p4 = { x: 15, y: 65 }; * noFill(); * stroke(255, 102, 0); * curve(p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y); * stroke(0); * curve(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y); * stroke(255, 102, 0); * curve(p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, p4.x, p4.y); * *
*
* * noFill(); * stroke(255, 102, 0); * curve(5, 26, 0, 5, 26, 0, 73, 24, 0, 73, 61, 0); * stroke(0); * curve(5, 26, 0, 73, 24, 0, 73, 61, 0, 15, 65, 0); * stroke(255, 102, 0); * curve(73, 24, 0, 73, 61, 0, 15, 65, 0, 15, 65, 0); * *
* * @alt * horseshoe shape with orange ends facing left and black curved center. * horseshoe shape with orange ends facing left and black curved center. * curving black and orange lines. */ /** * @method curve * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 z-coordinate for the beginning control point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 z-coordinate for the first point * @param {Number} x3 * @param {Number} y3 * @param {Number} z3 z-coordinate for the second point * @param {Number} x4 * @param {Number} y4 * @param {Number} z4 z-coordinate for the ending control point * @chainable */ p5.prototype.curve = function() { p5._validateParameters('curve', arguments); if (this._renderer._doStroke) { this._renderer.curve.apply(this._renderer, arguments); } return this; }; /** * Sets the resolution at which curves display. * * The default value is 20. * * This function is only useful when using the WEBGL renderer * as the default canvas renderer does not use this * information. * * @method curveDetail * @param {Number} resolution of the curves * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * * curveDetail(5); * } * function draw() { * background(200); * * // prettier-ignore * curve( 250, 600, 0, * -30, 40, 0, * 30, 30, 0, * -250, 600, 0); * } * *
* * @alt * white arch shape with a low level of curve detail. * */ p5.prototype.curveDetail = function(d) { p5._validateParameters('curveDetail', arguments); this._curveDetail = d; return this; }; /** * Modifies the quality of forms created with curve() and curveVertex(). * The parameter tightness determines how the curve fits to the vertex * points. The value 0.0 is the default value for tightness (this value * defines the curves to be Catmull-Rom splines) and the value 1.0 connects * all the points with straight lines. Values within the range -5.0 and 5.0 * will deform the curves but will leave them recognizable and as values * increase in magnitude, they will continue to deform. * * @method curveTightness * @param {Number} amount of deformation from the original vertices * @chainable * @example *
* * // Move the mouse left and right to see the curve change * * function setup() { * createCanvas(100, 100); * noFill(); * } * * function draw() { * background(204); * var t = map(mouseX, 0, width, -5, 5); * curveTightness(t); * beginShape(); * curveVertex(10, 26); * curveVertex(10, 26); * curveVertex(83, 24); * curveVertex(83, 61); * curveVertex(25, 65); * curveVertex(25, 65); * endShape(); * } * *
* * @alt * Line shaped like right-facing arrow,points move with mouse-x and warp shape. */ p5.prototype.curveTightness = function(t) { p5._validateParameters('curveTightness', arguments); this._renderer._curveTightness = t; }; /** * Evaluates the curve at position t for points a, b, c, d. * The parameter t varies between 0 and 1, a and d are points * on the curve, and b and c are the control points. * This can be done once with the x coordinates and a second time * with the y coordinates to get the location of a curve at t. * * @method curvePoint * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} bezier value at position t * @example *
* * noFill(); * curve(5, 26, 5, 26, 73, 24, 73, 61); * curve(5, 26, 73, 24, 73, 61, 15, 65); * fill(255); * ellipseMode(CENTER); * var steps = 6; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = curvePoint(5, 5, 73, 73, t); * var y = curvePoint(26, 26, 24, 61, t); * ellipse(x, y, 5, 5); * x = curvePoint(5, 73, 73, 15, t); * y = curvePoint(26, 24, 61, 65, t); * ellipse(x, y, 5, 5); * } * *
* *line hooking down to right-bottom with 13 5x5 white ellipse points */ p5.prototype.curvePoint = function(a, b, c, d, t) { p5._validateParameters('curvePoint', arguments); var t3 = t * t * t, t2 = t * t, f1 = -0.5 * t3 + t2 - 0.5 * t, f2 = 1.5 * t3 - 2.5 * t2 + 1.0, f3 = -1.5 * t3 + 2.0 * t2 + 0.5 * t, f4 = 0.5 * t3 - 0.5 * t2; return a * f1 + b * f2 + c * f3 + d * f4; }; /** * Evaluates the tangent to the curve at position t for points a, b, c, d. * The parameter t varies between 0 and 1, a and d are points on the curve, * and b and c are the control points. * * @method curveTangent * @param {Number} a coordinate of first point on the curve * @param {Number} b coordinate of first control point * @param {Number} c coordinate of second control point * @param {Number} d coordinate of second point on the curve * @param {Number} t value between 0 and 1 * @return {Number} the tangent at position t * @example *
* * noFill(); * curve(5, 26, 73, 24, 73, 61, 15, 65); * var steps = 6; * for (var i = 0; i <= steps; i++) { * var t = i / steps; * var x = curvePoint(5, 73, 73, 15, t); * var y = curvePoint(26, 24, 61, 65, t); * //ellipse(x, y, 5, 5); * var tx = curveTangent(5, 73, 73, 15, t); * var ty = curveTangent(26, 24, 61, 65, t); * var a = atan2(ty, tx); * a -= PI / 2.0; * line(x, y, cos(a) * 8 + x, sin(a) * 8 + y); * } * *
* * @alt *right curving line mid-right of canvas with 7 short lines radiating from it. */ p5.prototype.curveTangent = function(a, b, c, d, t) { p5._validateParameters('curveTangent', arguments); var t2 = t * t, f1 = -3 * t2 / 2 + 2 * t - 0.5, f2 = 9 * t2 / 2 - 5 * t, f3 = -9 * t2 / 2 + 4 * t + 0.5, f4 = 3 * t2 / 2 - t; return a * f1 + b * f2 + c * f3 + d * f4; }; module.exports = p5; },{"./core":22,"./error_helpers":25}],24:[function(_dereq_,module,exports){ /** * @module Environment * @submodule Environment * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var C = _dereq_('./constants'); var standardCursors = [C.ARROW, C.CROSS, C.HAND, C.MOVE, C.TEXT, C.WAIT]; p5.prototype._frameRate = 0; p5.prototype._lastFrameTime = window.performance.now(); p5.prototype._targetFrameRate = 60; var _windowPrint = window.print; /** * The print() function writes to the console area of your browser. * This function is often helpful for looking at the data a program is * producing. This function creates a new line of text for each call to * the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+). * * @method print * @param {Any} contents any combination of Number, String, Object, Boolean, * Array to print * @example *
* var x = 10; * print('The value of x is ' + x); * // prints "The value of x is 10" *
* @alt * default grey canvas */ p5.prototype.print = function() { if (!arguments.length) { _windowPrint(); } else { console.log.apply(console, arguments); } }; /** * The system variable frameCount contains the number of frames that have * been displayed since the program started. Inside setup() the value is 0, * after the first iteration of draw it is 1, etc. * * @property {Integer} frameCount * @readOnly * @example *
* function setup() { * frameRate(30); * textSize(20); * textSize(30); * textAlign(CENTER); * } * * function draw() { * background(200); * text(frameCount, width / 2, height / 2); * }
* * @alt * numbers rapidly counting upward with frame count set to 30. * */ p5.prototype.frameCount = 0; /** * Confirms if the window a p5.js program is in is "focused," meaning that * the sketch will accept mouse or keyboard input. This variable is * "true" if the window is focused and "false" if not. * * @property {Boolean} focused * @readOnly * @example *
* // To demonstrate, put two windows side by side. * // Click on the window that the p5 sketch isn't in! * function draw() { * background(200); * noStroke(); * fill(0, 200, 0); * ellipse(25, 25, 50, 50); * * if (!focused) { // or "if (focused === false)" * stroke(200, 0, 0); * line(0, 0, 100, 100); * line(100, 0, 0, 100); * } * } *
* * @alt * green 50x50 ellipse at top left. Red X covers canvas when page focus changes * */ p5.prototype.focused = document.hasFocus(); /** * Sets the cursor to a predefined symbol or an image, or makes it visible * if already hidden. If you are trying to set an image as the cursor, the * recommended size is 16x16 or 32x32 pixels. It is not possible to load an * image as the cursor if you are exporting your program for the Web, and not * all MODES work with all browsers. The values for parameters x and y must * be less than the dimensions of the image. * * @method cursor * @param {String|Constant} type either ARROW, CROSS, HAND, MOVE, TEXT, or * WAIT, or path for image * @param {Number} [x] the horizontal active spot of the cursor * @param {Number} [y] the vertical active spot of the cursor * @example *
* // Move the mouse left and right across the image * // to see the cursor change from a cross to a hand * function draw() { * line(width / 2, 0, width / 2, height); * if (mouseX < 50) { * cursor(CROSS); * } else { * cursor(HAND); * } * } *
* * @alt * horizontal line divides canvas. cursor on left is a cross, right is hand. * */ p5.prototype.cursor = function(type, x, y) { var cursor = 'auto'; var canvas = this._curElement.elt; if (standardCursors.indexOf(type) > -1) { // Standard css cursor cursor = type; } else if (typeof type === 'string') { var coords = ''; if (x && y && (typeof x === 'number' && typeof y === 'number')) { // Note that x and y values must be unit-less positive integers < 32 // https://developer.mozilla.org/en-US/docs/Web/CSS/cursor coords = x + ' ' + y; } if ( type.substring(0, 7) === 'http://' || type.substring(0, 8) === 'https://' ) { // Image (absolute url) cursor = 'url(' + type + ') ' + coords + ', auto'; } else if (/\.(cur|jpg|jpeg|gif|png|CUR|JPG|JPEG|GIF|PNG)$/.test(type)) { // Image file (relative path) - Separated for performance reasons cursor = 'url(' + type + ') ' + coords + ', auto'; } else { // Any valid string for the css cursor property cursor = type; } } canvas.style.cursor = cursor; }; /** * Specifies the number of frames to be displayed every second. For example, * the function call frameRate(30) will attempt to refresh 30 times a second. * If the processor is not fast enough to maintain the specified rate, the * frame rate will not be achieved. Setting the frame rate within setup() is * recommended. The default rate is 60 frames per second. This is the same as * setFrameRate(val). *

* Calling frameRate() with no arguments returns the current framerate. The * draw function must run at least once before it will return a value. This * is the same as getFrameRate(). *

* Calling frameRate() with arguments that are not of the type numbers * or are non positive also returns current framerate. * * @method frameRate * @param {Number} fps number of frames to be displayed every second * @chainable * * @example * *
* var rectX = 0; * var fr = 30; //starting FPS * var clr; * * function setup() { * background(200); * frameRate(fr); // Attempt to refresh at starting FPS * clr = color(255, 0, 0); * } * * function draw() { * background(200); * rectX = rectX += 1; // Move Rectangle * * if (rectX >= width) { // If you go off screen. * if (fr === 30) { * clr = color(0, 0, 255); * fr = 10; * frameRate(fr); // make frameRate 10 FPS * } else { * clr = color(255, 0, 0); * fr = 30; * frameRate(fr); // make frameRate 30 FPS * } * rectX = 0; * } * fill(clr); * rect(rectX, 40, 20, 20); * } *
* * @alt * blue rect moves left to right, followed by red rect moving faster. Loops. * */ /** * @method frameRate * @return {Number} current frameRate */ p5.prototype.frameRate = function(fps) { p5._validateParameters('frameRate', arguments); if (typeof fps !== 'number' || fps < 0) { return this._frameRate; } else { this._setProperty('_targetFrameRate', fps); this._runFrames(); return this; } }; /** * Returns the current framerate. * * @private * @return {Number} current frameRate */ p5.prototype.getFrameRate = function() { return this.frameRate(); }; /** * Specifies the number of frames to be displayed every second. For example, * the function call frameRate(30) will attempt to refresh 30 times a second. * If the processor is not fast enough to maintain the specified rate, the * frame rate will not be achieved. Setting the frame rate within setup() is * recommended. The default rate is 60 frames per second. * * Calling frameRate() with no arguments returns the current framerate. * * @private * @param {Number} [fps] number of frames to be displayed every second */ p5.prototype.setFrameRate = function(fps) { return this.frameRate(fps); }; /** * Hides the cursor from view. * * @method noCursor * @example *
* function setup() { * noCursor(); * } * * function draw() { * background(200); * ellipse(mouseX, mouseY, 10, 10); * } *
* * * @alt * cursor becomes 10x 10 white ellipse the moves with mouse x and y. * */ p5.prototype.noCursor = function() { this._curElement.elt.style.cursor = 'none'; }; /** * System variable that stores the width of the entire screen display. This * is used to run a full-screen program on any display size. * * @property {Number} displayWidth * @readOnly * @example *
* createCanvas(displayWidth, displayHeight); *
* * @alt * cursor becomes 10x 10 white ellipse the moves with mouse x and y. * */ p5.prototype.displayWidth = screen.width; /** * System variable that stores the height of the entire screen display. This * is used to run a full-screen program on any display size. * * @property {Number} displayHeight * @readOnly * @example *
* createCanvas(displayWidth, displayHeight); *
* * @alt * no display. * */ p5.prototype.displayHeight = screen.height; /** * System variable that stores the width of the inner window, it maps to * window.innerWidth. * * @property {Number} windowWidth * @readOnly * @example *
* createCanvas(windowWidth, windowHeight); *
* * @alt * no display. * */ p5.prototype.windowWidth = getWindowWidth(); /** * System variable that stores the height of the inner window, it maps to * window.innerHeight. * * @property {Number} windowHeight * @readOnly * @example *
* createCanvas(windowWidth, windowHeight); *
*@alt * no display. * */ p5.prototype.windowHeight = getWindowHeight(); /** * The windowResized() function is called once every time the browser window * is resized. This is a good place to resize the canvas or do any other * adjustments to accommodate the new window size. * * @method windowResized * @example *
* function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { * background(0, 100, 200); * } * * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } *
* @alt * no display. */ p5.prototype._onresize = function(e) { this._setProperty('windowWidth', getWindowWidth()); this._setProperty('windowHeight', getWindowHeight()); var context = this._isGlobal ? window : this; var executeDefault; if (typeof context.windowResized === 'function') { executeDefault = context.windowResized(e); if (executeDefault !== undefined && !executeDefault) { e.preventDefault(); } } }; function getWindowWidth() { return ( window.innerWidth || (document.documentElement && document.documentElement.clientWidth) || (document.body && document.body.clientWidth) || 0 ); } function getWindowHeight() { return ( window.innerHeight || (document.documentElement && document.documentElement.clientHeight) || (document.body && document.body.clientHeight) || 0 ); } /** * System variable that stores the width of the drawing canvas. This value * is set by the first parameter of the createCanvas() function. * For example, the function call createCanvas(320, 240) sets the width * variable to the value 320. The value of width defaults to 100 if * createCanvas() is not used in a program. * * @property {Number} width * @readOnly */ p5.prototype.width = 0; /** * System variable that stores the height of the drawing canvas. This value * is set by the second parameter of the createCanvas() function. For * example, the function call createCanvas(320, 240) sets the height * variable to the value 240. The value of height defaults to 100 if * createCanvas() is not used in a program. * * @property {Number} height * @readOnly */ p5.prototype.height = 0; /** * If argument is given, sets the sketch to fullscreen or not based on the * value of the argument. If no argument is given, returns the current * fullscreen state. Note that due to browser restrictions this can only * be called on user input, for example, on mouse press like the example * below. * * @method fullscreen * @param {Boolean} [val] whether the sketch should be in fullscreen mode * or not * @return {Boolean} current fullscreen state * @example *
* * // Clicking in the box toggles fullscreen on and off. * function setup() { * background(200); * } * function mousePressed() { * if (mouseX > 0 && mouseX < 100 && mouseY > 0 && mouseY < 100) { * var fs = fullscreen(); * fullscreen(!fs); * } * } * *
* * @alt * no display. * */ p5.prototype.fullscreen = function(val) { p5._validateParameters('fullscreen', arguments); // no arguments, return fullscreen or not if (typeof val === 'undefined') { return ( document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement ); } else { // otherwise set to fullscreen or not if (val) { launchFullscreen(document.documentElement); } else { exitFullscreen(); } } }; /** * Sets the pixel scaling for high pixel density displays. By default * pixel density is set to match display density, call pixelDensity(1) * to turn this off. Calling pixelDensity() with no arguments returns * the current pixel density of the sketch. * * * @method pixelDensity * @param {Number} [val] whether or how much the sketch should scale * @returns {Number} current pixel density of the sketch * @example *
* * function setup() { * pixelDensity(1); * createCanvas(100, 100); * background(200); * ellipse(width / 2, height / 2, 50, 50); * } * *
*
* * function setup() { * pixelDensity(3.0); * createCanvas(100, 100); * background(200); * ellipse(width / 2, height / 2, 50, 50); * } * *
* * @alt * fuzzy 50x50 white ellipse with black outline in center of canvas. * sharp 50x50 white ellipse with black outline in center of canvas. */ p5.prototype.pixelDensity = function(val) { p5._validateParameters('pixelDensity', arguments); if (typeof val === 'number') { this._pixelDensity = val; } else { return this._pixelDensity; } this.resizeCanvas(this.width, this.height, true); }; /** * Returns the pixel density of the current display the sketch is running on. * * @method displayDensity * @returns {Number} current pixel density of the display * @example *
* * function setup() { * var density = displayDensity(); * pixelDensity(density); * createCanvas(100, 100); * background(200); * ellipse(width / 2, height / 2, 50, 50); * } * *
* * @alt * 50x50 white ellipse with black outline in center of canvas. */ p5.prototype.displayDensity = function() { return window.devicePixelRatio; }; function launchFullscreen(element) { var enabled = document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled; if (!enabled) { throw new Error('Fullscreen not enabled in this browser.'); } if (element.requestFullscreen) { element.requestFullscreen(); } else if (element.mozRequestFullScreen) { element.mozRequestFullScreen(); } else if (element.webkitRequestFullscreen) { element.webkitRequestFullscreen(); } else if (element.msRequestFullscreen) { element.msRequestFullscreen(); } } function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } /** * Gets the current URL. * @method getURL * @return {String} url * @example *
* * var url; * var x = 100; * * function setup() { * fill(0); * noStroke(); * url = getURL(); * } * * function draw() { * background(200); * text(url, x, height / 2); * x--; * } * *
* * @alt * current url (http://p5js.org/reference/#/p5/getURL) moves right to left. * */ p5.prototype.getURL = function() { return location.href; }; /** * Gets the current URL path as an array. * @method getURLPath * @return {String[]} path components * @example *
* function setup() { * var urlPath = getURLPath(); * for (var i = 0; i < urlPath.length; i++) { * text(urlPath[i], 10, i * 20 + 20); * } * } *
* * @alt *no display * */ p5.prototype.getURLPath = function() { return location.pathname.split('/').filter(function(v) { return v !== ''; }); }; /** * Gets the current URL params as an Object. * @method getURLParams * @return {Object} URL params * @example *
* * // Example: http://p5js.org?year=2014&month=May&day=15 * * function setup() { * var params = getURLParams(); * text(params.day, 10, 20); * text(params.month, 10, 40); * text(params.year, 10, 60); * } * *
* @alt * no display. * */ p5.prototype.getURLParams = function() { var re = /[?&]([^&=]+)(?:[&=])([^&=]+)/gim; var m; var v = {}; while ((m = re.exec(location.search)) != null) { if (m.index === re.lastIndex) { re.lastIndex++; } v[m[1]] = m[2]; } return v; }; module.exports = p5; },{"./constants":21,"./core":22}],25:[function(_dereq_,module,exports){ /** * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); if (typeof IS_MINIFIED !== 'undefined') { p5._validateParameters = p5._friendlyFileLoadError = function() {}; } else { var doFriendlyWelcome = false; // TEMP until we get it all working LM // for parameter validation var dataDoc = _dereq_('../../docs/reference/data.json'); var arrDoc = JSON.parse(JSON.stringify(dataDoc)); // -- Borrowed from jQuery 1.11.3 -- var class2type = {}; var toString = class2type.toString; var names = [ 'Boolean', 'Number', 'String', 'Function', 'Array', 'Date', 'RegExp', 'Object', 'Error' ]; for (var n = 0; n < names.length; n++) { class2type['[object ' + names[n] + ']'] = names[n].toLowerCase(); } var getType = function(obj) { if (obj == null) { return obj + ''; } return typeof obj === 'object' || typeof obj === 'function' ? class2type[toString.call(obj)] || 'object' : typeof obj; }; // -- End borrow -- var friendlyWelcome = function() { // p5.js brand - magenta: #ED225D //var astrixBgColor = 'transparent'; //var astrixTxtColor = '#ED225D'; //var welcomeBgColor = '#ED225D'; //var welcomeTextColor = 'white'; console.log( ' _ \n' + ' /\\| |/\\ \n' + " \\ ` ' / \n" + ' / , . \\ \n' + ' \\/|_|\\/ ' + '\n\n> p5.js says: Welcome! ' + 'This is your friendly debugger. ' + 'To turn me off switch to using “p5.min.js”.' ); }; /** * Prints out a fancy, colorful message to the console log * * @private * @param {String} message the words to be said * @param {String} func the name of the function to link * @param {Number|String} color CSS color string or error type * * @return console logs */ // Wrong number of params, undefined param, wrong type var FILE_LOAD = 3; var ERR_PARAMS = 3; // p5.js blue, p5.js orange, auto dark green; fallback p5.js darkened magenta // See testColors below for all the color codes and names var typeColors = ['#2D7BB6', '#EE9900', '#4DB200', '#C83C00']; var report = function(message, func, color) { if (doFriendlyWelcome) { friendlyWelcome(); doFriendlyWelcome = false; } if ('undefined' === getType(color)) { color = '#B40033'; // dark magenta } else if (getType(color) === 'number') { // Type to color color = typeColors[color]; } if (func.substring(0, 4) === 'load') { console.log( '> p5.js says: ' + message + '[https://github.com/processing/p5.js/wiki/Local-server]' ); } else { console.log( '> p5.js says: ' + message + ' [http://p5js.org/reference/#p5/' + func + ']' ); } }; var errorCases = { '0': { fileType: 'image', method: 'loadImage', message: ' hosting the image online,' }, '1': { fileType: 'XML file', method: 'loadXML' }, '2': { fileType: 'table file', method: 'loadTable' }, '3': { fileType: 'text file', method: 'loadStrings' }, '4': { fileType: 'font', method: 'loadFont', message: ' hosting the font online,' } }; p5._friendlyFileLoadError = function(errorType, filePath) { var errorInfo = errorCases[errorType]; var message = 'It looks like there was a problem' + ' loading your ' + errorInfo.fileType + '.' + ' Try checking if the file path [' + filePath + '] is correct,' + (errorInfo.message || '') + ' or running a local server.'; report(message, errorInfo.method, FILE_LOAD); }; var docCache = {}; var builtinTypes = [ 'number', 'string', 'boolean', 'constant', 'function', 'any', 'integer' ]; // validateParameters() helper functions: // lookupParamDoc() for querying data.json var lookupParamDoc = function(func) { var queryResult = arrDoc.classitems.filter(function(x) { return x.name === func; }); // different JSON structure for funct with multi-format var overloads = []; if (queryResult[0].hasOwnProperty('overloads')) { for (var i = 0; i < queryResult[0].overloads.length; i++) { overloads.push(queryResult[0].overloads[i].params); } } else { overloads.push(queryResult[0].params || []); } var mapConstants = {}; var maxParams = 0; overloads.forEach(function(formats) { if (maxParams < formats.length) { maxParams = formats.length; } formats.forEach(function(format) { format.types = format.type.split('|').map(function ct(type) { // array if (type.substr(type.length - 2, 2) === '[]') { return { name: type, array: ct(type.substr(0, type.length - 2)) }; } var lowerType = type.toLowerCase(); // contant if (lowerType === 'constant') { var constant; if (mapConstants.hasOwnProperty(format.name)) { constant = mapConstants[format.name]; } else { // parse possible constant values from description var myRe = /either\s+(?:[A-Z0-9_]+\s*,?\s*(?:or)?\s*)+/g; var values = {}; var names = []; constant = mapConstants[format.name] = { values: values, names: names }; var myArray = myRe.exec(format.description); if (func === 'endShape' && format.name === 'mode') { values[constants.CLOSE] = true; names.push('CLOSE'); } else { var match = myArray[0]; var reConst = /[A-Z0-9_]+/g; var matchConst; while ((matchConst = reConst.exec(match)) !== null) { var name = matchConst[0]; if (constants.hasOwnProperty(name)) { values[constants[name]] = true; names.push(name); } } } } return { name: type, builtin: lowerType, names: constant.names, values: constant.values }; } // function if (lowerType.substr(0, 'function'.length) === 'function') { lowerType = 'function'; } // builtin if (builtinTypes.indexOf(lowerType) >= 0) { return { name: type, builtin: lowerType }; } // find type's prototype var t = window; var typeParts = type.split('.'); // special-case 'p5' since it may be non-global if (typeParts[0] === 'p5') { t = p5; typeParts.shift(); } typeParts.forEach(function(p) { t = t && t[p]; }); if (t) { return { name: type, prototype: t }; } return { name: type, type: lowerType }; }); }); }); return { overloads: overloads, maxParams: maxParams }; }; var testParamType = function(param, type) { var isArray = param instanceof Array; if (type.array && isArray) { for (var i = 0; i < param.length; i++) { if (!testParamType(param[i], type.array)) { return false; } } return true; } else if (type.prototype) { return param instanceof type.prototype; } else if (type.builtin) { switch (type.builtin) { case 'number': return typeof param === 'number' || (!!param && !isNaN(param)); case 'integer': return ( (typeof param === 'number' || (!!param && !isNaN(param))) && Number(param) === Math.floor(param) ); case 'boolean': case 'any': return true; case 'array': return isArray; case 'string': return typeof param === 'number' || typeof param === 'string'; case 'constant': return type.values.hasOwnProperty(param); case 'function': return param instanceof Function; } } return typeof param === type.t; }; // testType() for non-object type parameter validation // Returns true if PASS, false if FAIL var testParamTypes = function(param, types) { for (var i = 0; i < types.length; i++) { if (testParamType(param, types[i])) { return true; } } return false; }; var testParamFormat = function(args, formats) { var errorArray = []; for (var p = 0; p < formats.length; p++) { var arg = args[p]; var format = formats[p]; var argType = typeof arg; if ('undefined' === argType || null === arg) { if (format.optional !== true) { errorArray.push({ type: 'EMPTY_VAR', position: p, format: format }); } } else if (!testParamTypes(arg, format.types)) { errorArray.push({ type: 'WRONG_TYPE', position: p, format: format, arg: arg }); } } return errorArray; }; // function for generating console.log() msg p5._friendlyParamError = function(errorObj, func) { var message; function formatType() { var format = errorObj.format; return format.types .map(function(type) { return type.names ? type.names.join('|') : type.name; }) .join('|'); } switch (errorObj.type) { case 'EMPTY_VAR': message = func + '() was expecting ' + formatType() + ' for parameter #' + errorObj.position + ' (zero-based index), received an empty variable instead.' + ' If not intentional, this is often a problem with scope:' + ' [https://p5js.org/examples/data-variable-scope.html]'; break; case 'WRONG_TYPE': var arg = errorObj.arg; var argType = arg instanceof Array ? 'array' : arg.name || typeof arg; message = func + '() was expecting ' + formatType() + ' for parameter #' + errorObj.position + ' (zero-based index), received ' + argType + ' instead'; break; case 'WRONG_ARGUMENT_COUNT': message = func + '() was expecting ' + errorObj.maxParams + ' arguments, but received ' + errorObj.argCount; break; } if (message) { try { var re = /Function\.validateParameters.*[\r\n].*[\r\n].*\(([^)]*)/; var location = re.exec(new Error().stack)[1]; if (location) { message += ' at ' + location; } } catch (err) {} report(message + '.', func, ERR_PARAMS); } }; /** * Validates parameters * param {String} func the name of the function * param {Array} args user input arguments * * example: * var a; * ellipse(10,10,a,5); * console ouput: * "It looks like ellipse received an empty variable in spot #2." * * example: * ellipse(10,"foo",5,5); * console output: * "ellipse was expecting a number for parameter #1, * received "foo" instead." */ p5._validateParameters = function validateParameters(func, args) { if (p5.disableFriendlyErrors) { return; // skip FES } var docs = docCache[func] || (docCache[func] = lookupParamDoc(func)); var errorArray = []; var minErrCount = 999999; var overloads = docs.overloads; for (var i = 0; i < overloads.length; i++) { var arrError = testParamFormat(args, overloads[i]); // see if this is the format with min number of err if (minErrCount > arrError.length) { minErrCount = arrError.length; errorArray = arrError; } if (arrError.length === 0) { break; // no error } } if (!errorArray.length && args.length > docs.maxParams) { errorArray.push({ type: 'WRONG_ARGUMENT_COUNT', argCount: args.length, maxParams: docs.maxParams }); } // generate err msg for (var n = 0; n < errorArray.length; n++) { p5._friendlyParamError(errorArray[n], func); } }; /** * Prints out all the colors in the color pallete with white text. * For color blindness testing. */ /* function testColors() { var str = 'A box of biscuits, a box of mixed biscuits and a biscuit mixer'; report(str, 'print', '#ED225D'); // p5.js magenta report(str, 'print', '#2D7BB6'); // p5.js blue report(str, 'print', '#EE9900'); // p5.js orange report(str, 'print', '#A67F59'); // p5.js light brown report(str, 'print', '#704F21'); // p5.js gold report(str, 'print', '#1CC581'); // auto cyan report(str, 'print', '#FF6625'); // auto orange report(str, 'print', '#79EB22'); // auto green report(str, 'print', '#B40033'); // p5.js darkened magenta report(str, 'print', '#084B7F'); // p5.js darkened blue report(str, 'print', '#945F00'); // p5.js darkened orange report(str, 'print', '#6B441D'); // p5.js darkened brown report(str, 'print', '#2E1B00'); // p5.js darkened gold report(str, 'print', '#008851'); // auto dark cyan report(str, 'print', '#C83C00'); // auto dark orange report(str, 'print', '#4DB200'); // auto dark green } */ p5.prototype._validateParameters = p5.validateParameters; } // This is a lazily-defined list of p5 symbols that may be // misused by beginners at top-level code, outside of setup/draw. We'd like // to detect these errors and help the user by suggesting they move them // into setup/draw. // // For more details, see https://github.com/processing/p5.js/issues/1121. var misusedAtTopLevelCode = null; var FAQ_URL = 'https://github.com/processing/p5.js/wiki/' + 'Frequently-Asked-Questions' + '#why-cant-i-assign-variables-using-p5-functions-and-' + 'variables-before-setup'; var defineMisusedAtTopLevelCode = function() { var uniqueNamesFound = {}; var getSymbols = function(obj) { return Object.getOwnPropertyNames(obj) .filter(function(name) { if (name[0] === '_') { return false; } if (name in uniqueNamesFound) { return false; } uniqueNamesFound[name] = true; return true; }) .map(function(name) { var type; if (typeof obj[name] === 'function') { type = 'function'; } else if (name === name.toUpperCase()) { type = 'constant'; } else { type = 'variable'; } return { name: name, type: type }; }); }; misusedAtTopLevelCode = [].concat( getSymbols(p5.prototype), // At present, p5 only adds its constants to p5.prototype during // construction, which may not have happened at the time a // ReferenceError is thrown, so we'll manually add them to our list. getSymbols(_dereq_('./constants')) ); // This will ultimately ensure that we report the most specific error // possible to the user, e.g. advising them about HALF_PI instead of PI // when their code misuses the former. misusedAtTopLevelCode.sort(function(a, b) { return b.name.length - a.name.length; }); }; var helpForMisusedAtTopLevelCode = function(e, log) { if (!log) { log = console.log.bind(console); } if (!misusedAtTopLevelCode) { defineMisusedAtTopLevelCode(); } // If we find that we're logging lots of false positives, we can // uncomment the following code to avoid displaying anything if the // user's code isn't likely to be using p5's global mode. (Note that // setup/draw are more likely to be defined due to JS function hoisting.) // //if (!('setup' in window || 'draw' in window)) { // return; //} misusedAtTopLevelCode.some(function(symbol) { // Note that while just checking for the occurrence of the // symbol name in the error message could result in false positives, // a more rigorous test is difficult because different browsers // log different messages, and the format of those messages may // change over time. // // For example, if the user uses 'PI' in their code, it may result // in any one of the following messages: // // * 'PI' is undefined (Microsoft Edge) // * ReferenceError: PI is undefined (Firefox) // * Uncaught ReferenceError: PI is not defined (Chrome) if (e.message && e.message.match('\\W?' + symbol.name + '\\W') !== null) { log( "Did you just try to use p5.js's " + symbol.name + (symbol.type === 'function' ? '() ' : ' ') + symbol.type + '? If so, you may want to ' + "move it into your sketch's setup() function.\n\n" + 'For more details, see: ' + FAQ_URL ); return true; } }); }; // Exposing this primarily for unit testing. p5.prototype._helpForMisusedAtTopLevelCode = helpForMisusedAtTopLevelCode; if (document.readyState !== 'complete') { window.addEventListener('error', helpForMisusedAtTopLevelCode, false); // Our job is only to catch ReferenceErrors that are thrown when // global (non-instance mode) p5 APIs are used at the top-level // scope of a file, so we'll unbind our error listener now to make // sure we don't log false positives later. window.addEventListener('load', function() { window.removeEventListener('error', helpForMisusedAtTopLevelCode, false); }); } module.exports = p5; },{"../../docs/reference/data.json":1,"./constants":21,"./core":22}],26:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/core'); /** * _globalInit * * TODO: ??? * if sketch is on window * assume "global" mode * and instantiate p5 automatically * otherwise do nothing * * @private * @return {Undefined} */ var _globalInit = function() { if (!window.PHANTOMJS && !window.mocha) { // If there is a setup or draw function on the window // then instantiate p5 in "global" mode if ( ((window.setup && typeof window.setup === 'function') || (window.draw && typeof window.draw === 'function')) && !p5.instance ) { new p5(); } } }; // TODO: ??? if (document.readyState === 'complete') { _globalInit(); } else { window.addEventListener('load', _globalInit, false); } },{"../core/core":22}],27:[function(_dereq_,module,exports){ /** * @module DOM * @submodule DOM * @for p5.Element */ 'use strict'; var p5 = _dereq_('./core'); /** * Base class for all elements added to a sketch, including canvas, * graphics buffers, and other HTML elements. Methods in blue are * included in the core functionality, methods in brown are added * with the p5.dom * library. * It is not called directly, but p5.Element * objects are created by calling createCanvas, createGraphics, * or in the p5.dom library, createDiv, createImg, createInput, etc. * * @class p5.Element * @param {String} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance */ p5.Element = function(elt, pInst) { /** * Underlying HTML element. All normal HTML methods can be called on this. * @example *
* * createCanvas(300, 500); * background(0, 0, 0, 0); * var input = createInput(); * input.position(20, 225); * var inputElem = new p5.Element(input.elt); * inputElem.style('width:450px;'); * inputElem.value('some string'); * *
* * @property elt * @readOnly */ this.elt = elt; this._pInst = pInst; this._events = {}; this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; }; /** * * Attaches the element to the parent specified. A way of setting * the container for the element. Accepts either a string ID, DOM * node, or p5.Element. If no arguments given, parent node is returned. * For more ways to position the canvas, see the * * positioning the canvas wiki page. * * @method parent * @param {String|p5.Element|Object} parent the ID, DOM node, or p5.Element * of desired parent element * @chainable * * @example *
* // in the html file: * // <div id="myContainer"></div> * * // in the js file: * var cnv = createCanvas(100, 100); * cnv.parent('myContainer'); *
*
* var div0 = createDiv('this is the parent'); * var div1 = createDiv('this is the child'); * div1.parent(div0); // use p5.Element *
*
* var div0 = createDiv('this is the parent'); * div0.id('apples'); * var div1 = createDiv('this is the child'); * div1.parent('apples'); // use id *
*
* var elt = document.getElementById('myParentDiv'); * var div1 = createDiv('this is the child'); * div1.parent(elt); // use element from page *
* * @alt * no display. */ /** * @method parent * @return {p5.Element} * */ p5.Element.prototype.parent = function(p) { if (typeof p === 'undefined') { return this.elt.parentNode; } if (typeof p === 'string') { if (p[0] === '#') { p = p.substring(1); } p = document.getElementById(p); } else if (p instanceof p5.Element) { p = p.elt; } p.appendChild(this.elt); return this; }; /** * * Sets the ID of the element. If no ID argument is passed in, it instead * returns the current ID of the element. * * @method id * @param {String} id ID of the element * @chainable * * @example *
* function setup() { * var cnv = createCanvas(100, 100); * // Assigns a CSS selector ID to * // the canvas element. * cnv.id('mycanvas'); * } *
* * @alt * no display. */ /** * @method id * @return {String} the id of the element */ p5.Element.prototype.id = function(id) { if (typeof id === 'undefined') { return this.elt.id; } this.elt.id = id; this.width = this.elt.offsetWidth; this.height = this.elt.offsetHeight; return this; }; /** * * Adds given class to the element. If no class argument is passed in, it * instead returns a string containing the current class(es) of the element. * * @method class * @param {String} class class to add * @chainable * * @example *
* function setup() { * var cnv = createCanvas(100, 100); * // Assigns a CSS selector class 'small' * // to the canvas element. * cnv.class('small'); * } *
* * @alt * no display. */ /** * @method class * @return {String} the class of the element */ p5.Element.prototype.class = function(c) { if (typeof c === 'undefined') { return this.elt.className; } this.elt.className = c; return this; }; /** * The .mousePressed() function is called once after every time a * mouse button is pressed over the element. This can be used to * attach element specific event listeners. * * @method mousePressed * @param {Function|Boolean} fxn function to be fired when mouse is * pressed over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mousePressed(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any click anywhere * function mousePressed() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.mousePressed = function(fxn) { adjustListener('mousedown', fxn, this); adjustListener('touchstart', fxn, this); return this; }; /** * The .doubleClicked() function is called once after every time a * mouse button is pressed twice over the element. This can be used to * attach element and action specific event listeners. * * @method doubleClicked * @param {Function|Boolean} fxn function to be fired when mouse is * double clicked over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @return {p5.Element} * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.doubleClicked(changeGray); // attach listener for * // canvas double click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any double click anywhere * function doubleClicked() { * d = d + 10; * } * * // this function fires only when cnv is double clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.doubleClicked = function(fxn) { adjustListener('dblclick', fxn, this); return this; }; /** * The .mouseWheel() function is called once after every time a * mouse wheel is scrolled over the element. This can be used to * attach element specific event listeners. *

* The function accepts a callback function as argument which will be executed * when the `wheel` event is triggered on the element, the callback function is * passed one argument `event`. The `event.deltaY` property returns negative * values if the mouse wheel is rotated up or away from the user and positive * in the other direction. The `event.deltaX` does the same as `event.deltaY` * except it reads the horizontal wheel scroll of the mouse wheel. *

* On OS X with "natural" scrolling enabled, the `event.deltaY` values are * reversed. * * @method mouseWheel * @param {Function|Boolean} fxn function to be fired when mouse is * scrolled over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseWheel(changeSize); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with mousewheel movement * // anywhere on screen * function mouseWheel() { * g = g + 10; * } * * // this function fires with mousewheel movement * // over canvas only * function changeSize(event) { * if (event.deltaY > 0) { * d = d + 10; * } else { * d = d - 10; * } * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseWheel = function(fxn) { adjustListener('wheel', fxn, this); return this; }; /** * The .mouseReleased() function is called once after every time a * mouse button is released over the element. This can be used to * attach element specific event listeners. * * @method mouseReleased * @param {Function|Boolean} fxn function to be fired when mouse is * released over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseReleased(changeGray); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires after the mouse has been * // released * function mouseReleased() { * d = d + 10; * } * * // this function fires after the mouse has been * // released while on canvas * function changeGray() { * g = random(0, 255); * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseReleased = function(fxn) { adjustListener('mouseup', fxn, this); adjustListener('touchend', fxn, this); return this; }; /** * The .mouseClicked() function is called once after a mouse button is * pressed and released over the element. This can be used to * attach element specific event listeners. * * @method mouseClicked * @param {Function|Boolean} fxn function to be fired when mouse is * clicked over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* * var cnv; * var d; * var g; * * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseClicked(changeGray); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires after the mouse has been * // clicked anywhere * function mouseClicked() { * d = d + 10; * } * * // this function fires after the mouse has been * // clicked on canvas * function changeGray() { * g = random(0, 255); * } * *
* * @alt * no display. * */ p5.Element.prototype.mouseClicked = function(fxn) { adjustListener('click', fxn, this); return this; }; /** * The .mouseMoved() function is called once every time a * mouse moves over the element. This can be used to attach an * element specific event listener. * * @method mouseMoved * @param {Function|Boolean} fxn function to be fired when a mouse moves * over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d = 30; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseMoved(changeSize); // attach listener for * // activity on canvas only * d = 10; * g = 100; * } * * function draw() { * background(g); * fill(200); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires when mouse moves anywhere on * // page * function mouseMoved() { * g = g + 5; * if (g > 255) { * g = 0; * } * } * * // this function fires when mouse moves over canvas * function changeSize() { * d = d + 2; * if (d > 100) { * d = 0; * } * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseMoved = function(fxn) { adjustListener('mousemove', fxn, this); adjustListener('touchmove', fxn, this); return this; }; /** * The .mouseOver() function is called once after every time a * mouse moves onto the element. This can be used to attach an * element specific event listener. * * @method mouseOver * @param {Function|Boolean} fxn function to be fired when a mouse moves * onto the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOver(changeGray); * d = 10; * } * * function draw() { * ellipse(width / 2, height / 2, d, d); * } * * function changeGray() { * d = d + 10; * if (d > 100) { * d = 0; * } * } *
* * * @alt * no display. * */ p5.Element.prototype.mouseOver = function(fxn) { adjustListener('mouseover', fxn, this); return this; }; /** * The .changed() function is called when the value of an * element changes. * This can be used to attach an element specific event listener. * * @method changed * @param {Function|Boolean} fxn function to be fired when the value of * an element changes. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var sel; * * function setup() { * textAlign(CENTER); * background(200); * sel = createSelect(); * sel.position(10, 10); * sel.option('pear'); * sel.option('kiwi'); * sel.option('grape'); * sel.changed(mySelectEvent); * } * * function mySelectEvent() { * var item = sel.value(); * background(200); * text("it's a " + item + '!', 50, 50); * } *
*
* var checkbox; * var cnv; * * function setup() { * checkbox = createCheckbox(' fill'); * checkbox.changed(changeFill); * cnv = createCanvas(100, 100); * cnv.position(0, 30); * noFill(); * } * * function draw() { * background(200); * ellipse(50, 50, 50, 50); * } * * function changeFill() { * if (checkbox.checked()) { * fill(0); * } else { * noFill(); * } * } *
* * @alt * dropdown: pear, kiwi, grape. When selected text "its a" + selection shown. * */ p5.Element.prototype.changed = function(fxn) { adjustListener('change', fxn, this); return this; }; /** * The .input() function is called when any user input is * detected with an element. The input event is often used * to detect keystrokes in a input element, or changes on a * slider element. This can be used to attach an element specific * event listener. * * @method input * @param {Function|Boolean} fxn function to be fired when any user input is * detected within the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* // Open your console to see the output * function setup() { * var inp = createInput(''); * inp.input(myInputEvent); * } * * function myInputEvent() { * console.log('you are typing: ', this.value()); * } *
* * @alt * no display. * */ p5.Element.prototype.input = function(fxn) { adjustListener('input', fxn, this); return this; }; /** * The .mouseOut() function is called once after every time a * mouse moves off the element. This can be used to attach an * element specific event listener. * * @method mouseOut * @param {Function|Boolean} fxn function to be fired when a mouse * moves off of an element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * function setup() { * cnv = createCanvas(100, 100); * cnv.mouseOut(changeGray); * d = 10; * } * * function draw() { * ellipse(width / 2, height / 2, d, d); * } * * function changeGray() { * d = d + 10; * if (d > 100) { * d = 0; * } * } *
* * @alt * no display. * */ p5.Element.prototype.mouseOut = function(fxn) { adjustListener('mouseout', fxn, this); return this; }; /** * The .touchStarted() function is called once after every time a touch is * registered. This can be used to attach element specific event listeners. * * @method touchStarted * @param {Function|Boolean} fxn function to be fired when a touch * starts over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchStarted(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any touch anywhere * function touchStarted() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.touchStarted = function(fxn) { adjustListener('touchstart', fxn, this); adjustListener('mousedown', fxn, this); return this; }; /** * The .touchMoved() function is called once after every time a touch move is * registered. This can be used to attach element specific event listeners. * * @method touchMoved * @param {Function|Boolean} fxn function to be fired when a touch moves over * the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchMoved(changeGray); // attach listener for * // canvas click only * g = 100; * } * * function draw() { * background(g); * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * @alt * no display. * */ p5.Element.prototype.touchMoved = function(fxn) { adjustListener('touchmove', fxn, this); adjustListener('mousemove', fxn, this); return this; }; /** * The .touchEnded() function is called once after every time a touch is * registered. This can be used to attach element specific event listeners. * * @method touchEnded * @param {Function|Boolean} fxn function to be fired when a touch ends * over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* var cnv; * var d; * var g; * function setup() { * cnv = createCanvas(100, 100); * cnv.touchEnded(changeGray); // attach listener for * // canvas click only * d = 10; * g = 100; * } * * function draw() { * background(g); * ellipse(width / 2, height / 2, d, d); * } * * // this function fires with any touch anywhere * function touchEnded() { * d = d + 10; * } * * // this function fires only when cnv is clicked * function changeGray() { * g = random(0, 255); * } *
* * * @alt * no display. * */ p5.Element.prototype.touchEnded = function(fxn) { adjustListener('touchend', fxn, this); adjustListener('mouseup', fxn, this); return this; }; /** * The .dragOver() function is called once after every time a * file is dragged over the element. This can be used to attach an * element specific event listener. * * @method dragOver * @param {Function|Boolean} fxn function to be fired when a file is * dragged over the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* // To test this sketch, simply drag a * // file over the canvas * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width / 2, height / 2); * c.dragOver(dragOverCallback); * } * * // This function will be called whenever * // a file is dragged over the canvas * function dragOverCallback() { * background(240); * text('Dragged over', width / 2, height / 2); * } *
* @alt * nothing displayed */ p5.Element.prototype.dragOver = function(fxn) { adjustListener('dragover', fxn, this); return this; }; /** * The .dragLeave() function is called once after every time a * dragged file leaves the element area. This can be used to attach an * element specific event listener. * * @method dragLeave * @param {Function|Boolean} fxn function to be fired when a file is * dragged off the element. * if `false` is passed instead, the previously * firing function will no longer fire. * @chainable * @example *
* // To test this sketch, simply drag a file * // over and then out of the canvas area * function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('Drag file', width / 2, height / 2); * c.dragLeave(dragLeaveCallback); * } * * // This function will be called whenever * // a file is dragged out of the canvas * function dragLeaveCallback() { * background(240); * text('Dragged off', width / 2, height / 2); * } *
* @alt * nothing displayed */ p5.Element.prototype.dragLeave = function(fxn) { adjustListener('dragleave', fxn, this); return this; }; /** * The .drop() function is called for each file dropped on the element. * It requires a callback that is passed a p5.File object. You can * optionally pass two callbacks, the first one (required) is triggered * for each file dropped when the file is loaded. The second (optional) * is triggered just once when a file (or files) are dropped. * * @method drop * @param {Function} callback callback triggered when files are dropped. * @param {Function} [fxn] callback to receive loaded file. * @chainable * @example *
* function setup() { * var c = createCanvas(100, 100); * background(200); * textAlign(CENTER); * text('drop image', width / 2, height / 2); * c.drop(gotFile); * } * * function gotFile(file) { * var img = createImg(file.data).hide(); * // Draw the image onto the canvas * image(img, 0, 0, width, height); * } *
* * @alt * Canvas turns into whatever image is dragged/dropped onto it. * */ p5.Element.prototype.drop = function(callback, fxn) { // Make a file loader callback and trigger user's callback function makeLoader(theFile) { // Making a p5.File object var p5file = new p5.File(theFile); return function(e) { p5file.data = e.target.result; callback(p5file); }; } // Is the file stuff supported? if (window.File && window.FileReader && window.FileList && window.Blob) { // If you want to be able to drop you've got to turn off // a lot of default behavior attachListener( 'dragover', function(evt) { evt.stopPropagation(); evt.preventDefault(); }, this ); // If this is a drag area we need to turn off the default behavior attachListener( 'dragleave', function(evt) { evt.stopPropagation(); evt.preventDefault(); }, this ); // If just one argument it's the callback for the files if (typeof fxn !== 'undefined') { attachListener('drop', fxn, this); } // Deal with the files attachListener( 'drop', function(evt) { evt.stopPropagation(); evt.preventDefault(); // A FileList var files = evt.dataTransfer.files; // Load each one and trigger the callback for (var i = 0; i < files.length; i++) { var f = files[i]; var reader = new FileReader(); reader.onload = makeLoader(f); // Text or data? // This should likely be improved if (f.type.indexOf('text') > -1) { reader.readAsText(f); } else { reader.readAsDataURL(f); } } }, this ); } else { console.log('The File APIs are not fully supported in this browser.'); } return this; }; // General handler for event attaching and detaching function adjustListener(ev, fxn, ctx) { if (fxn === false) { detachListener(ev, ctx); } else { attachListener(ev, fxn, ctx); } return this; } function attachListener(ev, fxn, ctx) { // LM removing, not sure why we had this? // var _this = ctx; // var f = function (e) { fxn(e, _this); }; // detach the old listener if there was one if (ctx._events[ev]) { detachListener(ev, ctx); } var f = fxn.bind(ctx); ctx.elt.addEventListener(ev, f, false); ctx._events[ev] = f; } function detachListener(ev, ctx) { var f = ctx._events[ev]; ctx.elt.removeEventListener(ev, f, false); ctx._events[ev] = null; } /** * Helper fxn for sharing pixel methods * */ p5.Element.prototype._setProperty = function(prop, value) { this[prop] = value; }; module.exports = p5.Element; },{"./core":22}],28:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering * @for p5 */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); /** * Thin wrapper around a renderer, to be used for creating a * graphics buffer object. Use this class if you need * to draw into an off-screen graphics buffer. The two parameters define the * width and height in pixels. The fields and methods for this class are * extensive, but mirror the normal drawing API for p5. * * @class p5.Graphics * @extends p5.Element * @param {Number} w width * @param {Number} h height * @param {Constant} renderer the renderer to use, either P2D or WEBGL * @param {p5} [pInst] pointer to p5 instance */ p5.Graphics = function(w, h, renderer, pInst) { var r = renderer || constants.P2D; this.canvas = document.createElement('canvas'); var node = pInst._userNode || document.body; node.appendChild(this.canvas); p5.Element.call(this, this.canvas, pInst, false); // bind methods and props of p5 to the new object for (var p in p5.prototype) { if (!this[p]) { if (typeof p5.prototype[p] === 'function') { this[p] = p5.prototype[p].bind(this); } else { this[p] = p5.prototype[p]; } } } p5.prototype._initializeInstanceVariables.apply(this); this.width = w; this.height = h; this._pixelDensity = pInst._pixelDensity; if (r === constants.WEBGL) { this._renderer = new p5.RendererGL(this.canvas, this, false); } else { this._renderer = new p5.Renderer2D(this.canvas, this, false); } pInst._elements.push(this); this._renderer.resize(w, h); this._renderer._applyDefaults(); return this; }; p5.Graphics.prototype = Object.create(p5.Element.prototype); /** * Removes a Graphics object from the page and frees any resources * associated with it. * * @method remove * * @example *
* var bg; * function setup() { * bg = createCanvas(100, 100); * bg.background(0); * image(bg, 0, 0); * bg.remove(); * } *
* *
* var bg; * function setup() { * pixelDensity(1); * createCanvas(100, 100); * stroke(255); * fill(0); * * // create and draw the background image * bg = createGraphics(100, 100); * bg.background(200); * bg.ellipse(50, 50, 80, 80); * } * function draw() { * var t = millis() / 1000; * // draw the background * if (bg) { * image(bg, frameCount % 100, 0); * image(bg, frameCount % 100 - 100, 0); * } * // draw the foreground * var p = p5.Vector.fromAngle(t, 35).add(50, 50); * ellipse(p.x, p.y, 30); * } * function mouseClicked() { * // remove the background * if (bg) { * bg.remove(); * bg = null; * } * } *
* * @alt * no image * a multi-colored circle moving back and forth over a scrolling background. * */ p5.Graphics.prototype.remove = function() { if (this.elt.parentNode) { this.elt.parentNode.removeChild(this.elt); } var idx = this._pInst._elements.indexOf(this); if (idx !== -1) { this._pInst._elements.splice(idx, 1); } for (var elt_ev in this._events) { this.elt.removeEventListener(elt_ev, this._events[elt_ev]); } }; module.exports = p5.Graphics; },{"./constants":21,"./core":22}],29:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering * @for p5 */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('../core/constants'); /** * Main graphics and rendering context, as well as the base API * implementation for p5.js "core". To be used as the superclass for * Renderer2D and Renderer3D classes, respecitvely. * * @class p5.Renderer * @constructor * @extends p5.Element * @param {String} elt DOM node that is wrapped * @param {p5} [pInst] pointer to p5 instance * @param {Boolean} [isMainCanvas] whether we're using it as main canvas */ p5.Renderer = function(elt, pInst, isMainCanvas) { p5.Element.call(this, elt, pInst); this.canvas = elt; this._pInst = pInst; if (isMainCanvas) { this._isMainCanvas = true; // for pixel method sharing with pimage this._pInst._setProperty('_curElement', this); this._pInst._setProperty('canvas', this.canvas); this._pInst._setProperty('width', this.width); this._pInst._setProperty('height', this.height); } else { // hide if offscreen buffer by default this.canvas.style.display = 'none'; this._styles = []; // non-main elt styles stored in p5.Renderer } this._textSize = 12; this._textLeading = 15; this._textFont = 'sans-serif'; this._textStyle = constants.NORMAL; this._textAscent = null; this._textDescent = null; this._rectMode = constants.CORNER; this._ellipseMode = constants.CENTER; this._curveTightness = 0; this._imageMode = constants.CORNER; this._tint = null; this._doStroke = true; this._doFill = true; this._strokeSet = false; this._fillSet = false; }; p5.Renderer.prototype = Object.create(p5.Element.prototype); // the renderer should return a 'style' object that it wishes to // store on the push stack. p5.Renderer.prototype.push = function() { return { properties: { _doStroke: this._doStroke, _strokeSet: this._strokeSet, _doFill: this._doFill, _fillSet: this._fillSet, _tint: this._tint, _imageMode: this._imageMode, _rectMode: this._rectMode, _ellipseMode: this._ellipseMode, _textFont: this._textFont, _textLeading: this._textLeading, _textSize: this._textSize, _textStyle: this._textStyle } }; }; // this is implementation of Object.assign() which is unavailable in // IE11 and (non-Chrome) Android browsers. // The assign() method is used to copy the values of all enumerable // own properties from one or more source objects to a target object. // It will return the target object. function assign(to, firstSource) { for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) { continue; } for (var nextKey in nextSource) if (nextSource.hasOwnProperty(nextKey)) { to[nextKey] = nextSource[nextKey]; } } return to; } // a pop() operation is in progress // the renderer is passed the 'style' object that it returned // from its push() method. p5.Renderer.prototype.pop = function(style) { if (style.properties) { // copy the style properties back into the renderer assign(this, style.properties); } }; /** * Resize our canvas element. */ p5.Renderer.prototype.resize = function(w, h) { this.width = w; this.height = h; this.elt.width = w * this._pInst._pixelDensity; this.elt.height = h * this._pInst._pixelDensity; this.elt.style.width = w + 'px'; this.elt.style.height = h + 'px'; if (this._isMainCanvas) { this._pInst._setProperty('width', this.width); this._pInst._setProperty('height', this.height); } }; p5.Renderer.prototype.textLeading = function(l) { if (typeof l === 'number') { this._setProperty('_textLeading', l); return this; } return this._textLeading; }; p5.Renderer.prototype.textSize = function(s) { if (typeof s === 'number') { this._setProperty('_textSize', s); this._setProperty('_textLeading', s * constants._DEFAULT_LEADMULT); return this._applyTextProperties(); } return this._textSize; }; p5.Renderer.prototype.textStyle = function(s) { if (s) { if ( s === constants.NORMAL || s === constants.ITALIC || s === constants.BOLD ) { this._setProperty('_textStyle', s); } return this._applyTextProperties(); } return this._textStyle; }; p5.Renderer.prototype.textAscent = function() { if (this._textAscent === null) { this._updateTextMetrics(); } return this._textAscent; }; p5.Renderer.prototype.textDescent = function() { if (this._textDescent === null) { this._updateTextMetrics(); } return this._textDescent; }; p5.Renderer.prototype._applyDefaults = function() { return this; }; /** * Helper fxn to check font type (system or otf) */ p5.Renderer.prototype._isOpenType = function(f) { f = f || this._textFont; return typeof f === 'object' && f.font && f.font.supported; }; p5.Renderer.prototype._updateTextMetrics = function() { if (this._isOpenType()) { this._setProperty('_textAscent', this._textFont._textAscent()); this._setProperty('_textDescent', this._textFont._textDescent()); return this; } // Adapted from http://stackoverflow.com/a/25355178 var text = document.createElement('span'); text.style.fontFamily = this._textFont; text.style.fontSize = this._textSize + 'px'; text.innerHTML = 'ABCjgq|'; var block = document.createElement('div'); block.style.display = 'inline-block'; block.style.width = '1px'; block.style.height = '0px'; var container = document.createElement('div'); container.appendChild(text); container.appendChild(block); container.style.height = '0px'; container.style.overflow = 'hidden'; document.body.appendChild(container); block.style.verticalAlign = 'baseline'; var blockOffset = calculateOffset(block); var textOffset = calculateOffset(text); var ascent = blockOffset[1] - textOffset[1]; block.style.verticalAlign = 'bottom'; blockOffset = calculateOffset(block); textOffset = calculateOffset(text); var height = blockOffset[1] - textOffset[1]; var descent = height - ascent; document.body.removeChild(container); this._setProperty('_textAscent', ascent); this._setProperty('_textDescent', descent); return this; }; /** * Helper fxn to measure ascent and descent. * Adapted from http://stackoverflow.com/a/25355178 */ function calculateOffset(object) { var currentLeft = 0, currentTop = 0; if (object.offsetParent) { do { currentLeft += object.offsetLeft; currentTop += object.offsetTop; } while ((object = object.offsetParent)); } else { currentLeft += object.offsetLeft; currentTop += object.offsetTop; } return [currentLeft, currentTop]; } module.exports = p5.Renderer; },{"../core/constants":21,"./core":22}],30:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('./core'); var canvas = _dereq_('./canvas'); var constants = _dereq_('./constants'); var filters = _dereq_('../image/filters'); _dereq_('./p5.Renderer'); /** * p5.Renderer2D * The 2D graphics canvas renderer class. * extends p5.Renderer */ var styleEmpty = 'rgba(0,0,0,0)'; // var alphaThreshold = 0.00125; // minimum visible p5.Renderer2D = function(elt, pInst, isMainCanvas) { p5.Renderer.call(this, elt, pInst, isMainCanvas); this.drawingContext = this.canvas.getContext('2d'); this._pInst._setProperty('drawingContext', this.drawingContext); return this; }; p5.Renderer2D.prototype = Object.create(p5.Renderer.prototype); p5.Renderer2D.prototype._applyDefaults = function() { this._cachedFillStyle = this._cachedStrokeStyle = undefined; this._setFill(constants._DEFAULT_FILL); this._setStroke(constants._DEFAULT_STROKE); this.drawingContext.lineCap = constants.ROUND; this.drawingContext.font = 'normal 12px sans-serif'; }; p5.Renderer2D.prototype.resize = function(w, h) { p5.Renderer.prototype.resize.call(this, w, h); this.drawingContext.scale( this._pInst._pixelDensity, this._pInst._pixelDensity ); }; ////////////////////////////////////////////// // COLOR | Setting ////////////////////////////////////////////// p5.Renderer2D.prototype.background = function() { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale( this._pInst._pixelDensity, this._pInst._pixelDensity ); if (arguments[0] instanceof p5.Image) { this._pInst.image(arguments[0], 0, 0, this.width, this.height); } else { var curFill = this._getFill(); // create background rect var color = this._pInst.color.apply(this._pInst, arguments); var newFill = color.toString(); this._setFill(newFill); this.drawingContext.fillRect(0, 0, this.width, this.height); // reset fill this._setFill(curFill); } this.drawingContext.restore(); }; p5.Renderer2D.prototype.clear = function() { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.clearRect(0, 0, this.width, this.height); this.drawingContext.restore(); }; p5.Renderer2D.prototype.fill = function() { var color = this._pInst.color.apply(this._pInst, arguments); this._setFill(color.toString()); }; p5.Renderer2D.prototype.stroke = function() { var color = this._pInst.color.apply(this._pInst, arguments); this._setStroke(color.toString()); }; ////////////////////////////////////////////// // IMAGE | Loading & Displaying ////////////////////////////////////////////// p5.Renderer2D.prototype.image = function( img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight ) { var cnv; try { if (this._tint) { if (p5.MediaElement && img instanceof p5.MediaElement) { img.loadPixels(); } if (img.canvas) { cnv = this._getTintedImageCanvas(img); } } if (!cnv) { cnv = img.canvas || img.elt; } this.drawingContext.drawImage( cnv, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight ); } catch (e) { if (e.name !== 'NS_ERROR_NOT_AVAILABLE') { throw e; } } }; p5.Renderer2D.prototype._getTintedImageCanvas = function(img) { if (!img.canvas) { return img; } var pixels = filters._toPixels(img.canvas); var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = img.canvas.width; tmpCanvas.height = img.canvas.height; var tmpCtx = tmpCanvas.getContext('2d'); var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); var newPixels = id.data; for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; var a = pixels[i + 3]; newPixels[i] = r * this._tint[0] / 255; newPixels[i + 1] = g * this._tint[1] / 255; newPixels[i + 2] = b * this._tint[2] / 255; newPixels[i + 3] = a * this._tint[3] / 255; } tmpCtx.putImageData(id, 0, 0); return tmpCanvas; }; ////////////////////////////////////////////// // IMAGE | Pixels ////////////////////////////////////////////// p5.Renderer2D.prototype.blendMode = function(mode) { this.drawingContext.globalCompositeOperation = mode; }; p5.Renderer2D.prototype.blend = function() { var currBlend = this.drawingContext.globalCompositeOperation; var blendMode = arguments[arguments.length - 1]; var copyArgs = Array.prototype.slice.call(arguments, 0, arguments.length - 1); this.drawingContext.globalCompositeOperation = blendMode; if (this._pInst) { this._pInst.copy.apply(this._pInst, copyArgs); } else { this.copy.apply(this, copyArgs); } this.drawingContext.globalCompositeOperation = currBlend; }; p5.Renderer2D.prototype.copy = function() { var srcImage, sx, sy, sw, sh, dx, dy, dw, dh; if (arguments.length === 9) { srcImage = arguments[0]; sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else if (arguments.length === 8) { srcImage = this._pInst; sx = arguments[0]; sy = arguments[1]; sw = arguments[2]; sh = arguments[3]; dx = arguments[4]; dy = arguments[5]; dw = arguments[6]; dh = arguments[7]; } else { throw new Error('Signature not supported'); } p5.Renderer2D._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh); }; p5.Renderer2D._copyHelper = function( dstImage, srcImage, sx, sy, sw, sh, dx, dy, dw, dh ) { srcImage.loadPixels(); var s = srcImage.canvas.width / srcImage.width; dstImage.drawingContext.drawImage( srcImage.canvas, s * sx, s * sy, s * sw, s * sh, dx, dy, dw, dh ); }; p5.Renderer2D.prototype.get = function(x, y, w, h) { if ( x === undefined && y === undefined && w === undefined && h === undefined ) { x = 0; y = 0; w = this.width; h = this.height; } else if (w === undefined && h === undefined) { w = 1; h = 1; } // if the section does not overlap the canvas if (x + w < 0 || y + h < 0 || x > this.width || y > this.height) { return [0, 0, 0, 255]; } var ctx = this._pInst || this; ctx.loadPixels(); var pd = ctx._pixelDensity; // round down to get integer numbers x = Math.floor(x); y = Math.floor(y); w = Math.floor(w); h = Math.floor(h); var sx = x * pd; var sy = y * pd; if (w === 1 && h === 1 && !(this instanceof p5.RendererGL)) { var imageData = this.drawingContext.getImageData(sx, sy, 1, 1).data; //imageData = [0,0,0,0]; return [imageData[0], imageData[1], imageData[2], imageData[3]]; } else { //auto constrain the width and height to //dimensions of the source image var dw = Math.min(w, ctx.width); var dh = Math.min(h, ctx.height); var sw = dw * pd; var sh = dh * pd; var region = new p5.Image(dw, dh); region.canvas .getContext('2d') .drawImage(this.canvas, sx, sy, sw, sh, 0, 0, dw, dh); return region; } }; p5.Renderer2D.prototype.loadPixels = function() { var ctx = this._pInst || this; // if called by p5.Image var pd = ctx._pixelDensity; var w = this.width * pd; var h = this.height * pd; var imageData = this.drawingContext.getImageData(0, 0, w, h); // @todo this should actually set pixels per object, so diff buffers can // have diff pixel arrays. ctx._setProperty('imageData', imageData); ctx._setProperty('pixels', imageData.data); }; p5.Renderer2D.prototype.set = function(x, y, imgOrCol) { // round down to get integer numbers x = Math.floor(x); y = Math.floor(y); var ctx = this._pInst || this; if (imgOrCol instanceof p5.Image) { this.drawingContext.save(); this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale(ctx._pixelDensity, ctx._pixelDensity); this.drawingContext.drawImage(imgOrCol.canvas, x, y); this.loadPixels.call(ctx); this.drawingContext.restore(); } else { var r = 0, g = 0, b = 0, a = 0; var idx = 4 * (y * ctx._pixelDensity * (this.width * ctx._pixelDensity) + x * ctx._pixelDensity); if (!ctx.imageData) { ctx.loadPixels.call(ctx); } if (typeof imgOrCol === 'number') { if (idx < ctx.pixels.length) { r = imgOrCol; g = imgOrCol; b = imgOrCol; a = 255; //this.updatePixels.call(this); } } else if (imgOrCol instanceof Array) { if (imgOrCol.length < 4) { throw new Error('pixel array must be of the form [R, G, B, A]'); } if (idx < ctx.pixels.length) { r = imgOrCol[0]; g = imgOrCol[1]; b = imgOrCol[2]; a = imgOrCol[3]; //this.updatePixels.call(this); } } else if (imgOrCol instanceof p5.Color) { if (idx < ctx.pixels.length) { r = imgOrCol.levels[0]; g = imgOrCol.levels[1]; b = imgOrCol.levels[2]; a = imgOrCol.levels[3]; //this.updatePixels.call(this); } } // loop over pixelDensity * pixelDensity for (var i = 0; i < ctx._pixelDensity; i++) { for (var j = 0; j < ctx._pixelDensity; j++) { // loop over idx = 4 * ((y * ctx._pixelDensity + j) * this.width * ctx._pixelDensity + (x * ctx._pixelDensity + i)); ctx.pixels[idx] = r; ctx.pixels[idx + 1] = g; ctx.pixels[idx + 2] = b; ctx.pixels[idx + 3] = a; } } } }; p5.Renderer2D.prototype.updatePixels = function(x, y, w, h) { var ctx = this._pInst || this; var pd = ctx._pixelDensity; if ( x === undefined && y === undefined && w === undefined && h === undefined ) { x = 0; y = 0; w = this.width; h = this.height; } w *= pd; h *= pd; this.drawingContext.putImageData(ctx.imageData, x, y, 0, 0, w, h); }; ////////////////////////////////////////////// // SHAPE | 2D Primitives ////////////////////////////////////////////// /** * Generate a cubic Bezier representing an arc on the unit circle of total * angle `size` radians, beginning `start` radians above the x-axis. Up to * four of these curves are combined to make a full arc. * * See www.joecridge.me/bezier.pdf for an explanation of the method. */ p5.Renderer2D.prototype._acuteArcToBezier = function _acuteArcToBezier( start, size ) { // Evauate constants. var alpha = size / 2.0, cos_alpha = Math.cos(alpha), sin_alpha = Math.sin(alpha), cot_alpha = 1.0 / Math.tan(alpha), phi = start + alpha, // This is how far the arc needs to be rotated. cos_phi = Math.cos(phi), sin_phi = Math.sin(phi), lambda = (4.0 - cos_alpha) / 3.0, mu = sin_alpha + (cos_alpha - lambda) * cot_alpha; // Return rotated waypoints. return { ax: Math.cos(start), ay: Math.sin(start), bx: lambda * cos_phi + mu * sin_phi, by: lambda * sin_phi - mu * cos_phi, cx: lambda * cos_phi - mu * sin_phi, cy: lambda * sin_phi + mu * cos_phi, dx: Math.cos(start + size), dy: Math.sin(start + size) }; }; p5.Renderer2D.prototype.arc = function(x, y, w, h, start, stop, mode) { var ctx = this.drawingContext; var vals = canvas.arcModeAdjust(x, y, w, h, this._ellipseMode); var rx = vals.w / 2.0; var ry = vals.h / 2.0; var epsilon = 0.00001; // Smallest visible angle on displays up to 4K. var arcToDraw = 0; var curves = []; // Create curves while (stop - start > epsilon) { arcToDraw = Math.min(stop - start, constants.HALF_PI); curves.push(this._acuteArcToBezier(start, arcToDraw)); start += arcToDraw; } // Fill curves if (this._doFill) { ctx.beginPath(); curves.forEach(function(curve, index) { if (index === 0) { ctx.moveTo(vals.x + curve.ax * rx, vals.y + curve.ay * ry); } // prettier-ignore ctx.bezierCurveTo(vals.x + curve.bx * rx, vals.y + curve.by * ry, vals.x + curve.cx * rx, vals.y + curve.cy * ry, vals.x + curve.dx * rx, vals.y + curve.dy * ry); }); if (mode === constants.PIE || mode == null) { ctx.lineTo(vals.x, vals.y); } ctx.closePath(); ctx.fill(); } // Stroke curves if (this._doStroke) { ctx.beginPath(); curves.forEach(function(curve, index) { if (index === 0) { ctx.moveTo(vals.x + curve.ax * rx, vals.y + curve.ay * ry); } // prettier-ignore ctx.bezierCurveTo(vals.x + curve.bx * rx, vals.y + curve.by * ry, vals.x + curve.cx * rx, vals.y + curve.cy * ry, vals.x + curve.dx * rx, vals.y + curve.dy * ry); }); if (mode === constants.PIE) { ctx.lineTo(vals.x, vals.y); ctx.closePath(); } else if (mode === constants.CHORD) { ctx.closePath(); } ctx.stroke(); } return this; }; p5.Renderer2D.prototype.ellipse = function(args) { var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; var x = args[0], y = args[1], w = args[2], h = args[3]; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if (this._getStroke() === styleEmpty) { return this; } } var kappa = 0.5522847498, ox = w / 2 * kappa, // control point offset horizontal oy = h / 2 * kappa, // control point offset vertical xe = x + w, // x-end ye = y + h, // y-end xm = x + w / 2, // x-middle ym = y + h / 2; // y-middle ctx.beginPath(); ctx.moveTo(x, ym); ctx.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y); ctx.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym); ctx.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye); ctx.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym); ctx.closePath(); if (doFill) { ctx.fill(); } if (doStroke) { ctx.stroke(); } }; p5.Renderer2D.prototype.line = function(x1, y1, x2, y2) { var ctx = this.drawingContext; if (!this._doStroke) { return this; } else if (this._getStroke() === styleEmpty) { return this; } // Translate the line by (0.5, 0.5) to draw it crisp if (ctx.lineWidth % 2 === 1) { ctx.translate(0.5, 0.5); } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); if (ctx.lineWidth % 2 === 1) { ctx.translate(-0.5, -0.5); } return this; }; p5.Renderer2D.prototype.point = function(x, y) { var ctx = this.drawingContext; if (!this._doStroke) { return this; } else if (this._getStroke() === styleEmpty) { return this; } var s = this._getStroke(); var f = this._getFill(); x = Math.round(x); y = Math.round(y); // swapping fill color to stroke and back after for correct point rendering this._setFill(s); if (ctx.lineWidth > 1) { ctx.beginPath(); ctx.arc(x, y, ctx.lineWidth / 2, 0, constants.TWO_PI, false); ctx.fill(); } else { ctx.fillRect(x, y, 1, 1); } this._setFill(f); }; p5.Renderer2D.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if (this._getStroke() === styleEmpty) { return this; } } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.lineTo(x4, y4); ctx.closePath(); if (doFill) { ctx.fill(); } if (doStroke) { ctx.stroke(); } return this; }; p5.Renderer2D.prototype.rect = function(args) { var x = args[0], y = args[1], w = args[2], h = args[3], tl = args[4], tr = args[5], br = args[6], bl = args[7]; var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if (this._getStroke() === styleEmpty) { return this; } } // Translate the line by (0.5, 0.5) to draw a crisp rectangle border if (this._doStroke && ctx.lineWidth % 2 === 1) { ctx.translate(0.5, 0.5); } ctx.beginPath(); if (typeof tl === 'undefined') { // No rounded corners ctx.rect(x, y, w, h); } else { // At least one rounded corner // Set defaults when not specified if (typeof tr === 'undefined') { tr = tl; } if (typeof br === 'undefined') { br = tr; } if (typeof bl === 'undefined') { bl = br; } var hw = w / 2; var hh = h / 2; // Clip radii if (w < 2 * tl) { tl = hw; } if (h < 2 * tl) { tl = hh; } if (w < 2 * tr) { tr = hw; } if (h < 2 * tr) { tr = hh; } if (w < 2 * br) { br = hw; } if (h < 2 * br) { br = hh; } if (w < 2 * bl) { bl = hw; } if (h < 2 * bl) { bl = hh; } // Draw shape ctx.beginPath(); ctx.moveTo(x + tl, y); ctx.arcTo(x + w, y, x + w, y + h, tr); ctx.arcTo(x + w, y + h, x, y + h, br); ctx.arcTo(x, y + h, x, y, bl); ctx.arcTo(x, y, x + w, y, tl); ctx.closePath(); } if (this._doFill) { ctx.fill(); } if (this._doStroke) { ctx.stroke(); } if (this._doStroke && ctx.lineWidth % 2 === 1) { ctx.translate(-0.5, -0.5); } return this; }; p5.Renderer2D.prototype.triangle = function(args) { var ctx = this.drawingContext; var doFill = this._doFill, doStroke = this._doStroke; var x1 = args[0], y1 = args[1]; var x2 = args[2], y2 = args[3]; var x3 = args[4], y3 = args[5]; if (doFill && !doStroke) { if (this._getFill() === styleEmpty) { return this; } } else if (!doFill && doStroke) { if (this._getStroke() === styleEmpty) { return this; } } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.lineTo(x3, y3); ctx.closePath(); if (doFill) { ctx.fill(); } if (doStroke) { ctx.stroke(); } }; p5.Renderer2D.prototype.endShape = function( mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind ) { if (vertices.length === 0) { return this; } if (!this._doStroke && !this._doFill) { return this; } var closeShape = mode === constants.CLOSE; var v; if (closeShape && !isContour) { vertices.push(vertices[0]); } var i, j; var numVerts = vertices.length; if (isCurve && (shapeKind === constants.POLYGON || shapeKind === null)) { if (numVerts > 3) { var b = [], s = 1 - this._curveTightness; this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[1][0], vertices[1][1]); for (i = 1; i + 2 < numVerts; i++) { v = vertices[i]; b[0] = [v[0], v[1]]; b[1] = [ v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6, v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6 ]; b[2] = [ vertices[i + 1][0] + (s * vertices[i][0] - s * vertices[i + 2][0]) / 6, vertices[i + 1][1] + (s * vertices[i][1] - s * vertices[i + 2][1]) / 6 ]; b[3] = [vertices[i + 1][0], vertices[i + 1][1]]; this.drawingContext.bezierCurveTo( b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1] ); } if (closeShape) { this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); } this._doFillStrokeClose(); } } else if ( isBezier && (shapeKind === constants.POLYGON || shapeKind === null) ) { this.drawingContext.beginPath(); for (i = 0; i < numVerts; i++) { if (vertices[i].isVert) { if (vertices[i].moveTo) { this.drawingContext.moveTo(vertices[i][0], vertices[i][1]); } else { this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); } } else { this.drawingContext.bezierCurveTo( vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3], vertices[i][4], vertices[i][5] ); } } this._doFillStrokeClose(); } else if ( isQuadratic && (shapeKind === constants.POLYGON || shapeKind === null) ) { this.drawingContext.beginPath(); for (i = 0; i < numVerts; i++) { if (vertices[i].isVert) { if (vertices[i].moveTo) { this.drawingContext.moveTo([0], vertices[i][1]); } else { this.drawingContext.lineTo(vertices[i][0], vertices[i][1]); } } else { this.drawingContext.quadraticCurveTo( vertices[i][0], vertices[i][1], vertices[i][2], vertices[i][3] ); } } this._doFillStrokeClose(); } else { if (shapeKind === constants.POINTS) { for (i = 0; i < numVerts; i++) { v = vertices[i]; if (this._doStroke) { this._pInst.stroke(v[6]); } this._pInst.point(v[0], v[1]); } } else if (shapeKind === constants.LINES) { for (i = 0; i + 1 < numVerts; i += 2) { v = vertices[i]; if (this._doStroke) { this._pInst.stroke(vertices[i + 1][6]); } this._pInst.line(v[0], v[1], vertices[i + 1][0], vertices[i + 1][1]); } } else if (shapeKind === constants.TRIANGLES) { for (i = 0; i + 2 < numVerts; i += 3) { v = vertices[i]; this.drawingContext.beginPath(); this.drawingContext.moveTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); this.drawingContext.lineTo(v[0], v[1]); if (this._doFill) { this._pInst.fill(vertices[i + 2][5]); this.drawingContext.fill(); } if (this._doStroke) { this._pInst.stroke(vertices[i + 2][6]); this.drawingContext.stroke(); } this.drawingContext.closePath(); } } else if (shapeKind === constants.TRIANGLE_STRIP) { for (i = 0; i + 1 < numVerts; i++) { v = vertices[i]; this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[i + 1][0], vertices[i + 1][1]); this.drawingContext.lineTo(v[0], v[1]); if (this._doStroke) { this._pInst.stroke(vertices[i + 1][6]); } if (this._doFill) { this._pInst.fill(vertices[i + 1][5]); } if (i + 2 < numVerts) { this.drawingContext.lineTo(vertices[i + 2][0], vertices[i + 2][1]); if (this._doStroke) { this._pInst.stroke(vertices[i + 2][6]); } if (this._doFill) { this._pInst.fill(vertices[i + 2][5]); } } this._doFillStrokeClose(); } } else if (shapeKind === constants.TRIANGLE_FAN) { if (numVerts > 2) { // For performance reasons, try to batch as many of the // fill and stroke calls as possible. this.drawingContext.beginPath(); for (i = 2; i < numVerts; i++) { v = vertices[i]; this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); this.drawingContext.lineTo(vertices[i - 1][0], vertices[i - 1][1]); this.drawingContext.lineTo(v[0], v[1]); this.drawingContext.lineTo(vertices[0][0], vertices[0][1]); // If the next colour is going to be different, stroke / fill now if (i < numVerts - 1) { if ( (this._doFill && v[5] !== vertices[i + 1][5]) || (this._doStroke && v[6] !== vertices[i + 1][6]) ) { if (this._doFill) { this._pInst.fill(v[5]); this.drawingContext.fill(); this._pInst.fill(vertices[i + 1][5]); } if (this._doStroke) { this._pInst.stroke(v[6]); this.drawingContext.stroke(); this._pInst.stroke(vertices[i + 1][6]); } this.drawingContext.closePath(); this.drawingContext.beginPath(); // Begin the next one } } } this._doFillStrokeClose(); } } else if (shapeKind === constants.QUADS) { for (i = 0; i + 3 < numVerts; i += 4) { v = vertices[i]; this.drawingContext.beginPath(); this.drawingContext.moveTo(v[0], v[1]); for (j = 1; j < 4; j++) { this.drawingContext.lineTo(vertices[i + j][0], vertices[i + j][1]); } this.drawingContext.lineTo(v[0], v[1]); if (this._doFill) { this._pInst.fill(vertices[i + 3][5]); } if (this._doStroke) { this._pInst.stroke(vertices[i + 3][6]); } this._doFillStrokeClose(); } } else if (shapeKind === constants.QUAD_STRIP) { if (numVerts > 3) { for (i = 0; i + 1 < numVerts; i += 2) { v = vertices[i]; this.drawingContext.beginPath(); if (i + 3 < numVerts) { this.drawingContext.moveTo(vertices[i + 2][0], vertices[i + 2][1]); this.drawingContext.lineTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); this.drawingContext.lineTo(vertices[i + 3][0], vertices[i + 3][1]); if (this._doFill) { this._pInst.fill(vertices[i + 3][5]); } if (this._doStroke) { this._pInst.stroke(vertices[i + 3][6]); } } else { this.drawingContext.moveTo(v[0], v[1]); this.drawingContext.lineTo(vertices[i + 1][0], vertices[i + 1][1]); } this._doFillStrokeClose(); } } } else { this.drawingContext.beginPath(); this.drawingContext.moveTo(vertices[0][0], vertices[0][1]); for (i = 1; i < numVerts; i++) { v = vertices[i]; if (v.isVert) { if (v.moveTo) { this.drawingContext.moveTo(v[0], v[1]); } else { this.drawingContext.lineTo(v[0], v[1]); } } } this._doFillStrokeClose(); } } isCurve = false; isBezier = false; isQuadratic = false; isContour = false; if (closeShape) { vertices.pop(); } return this; }; ////////////////////////////////////////////// // SHAPE | Attributes ////////////////////////////////////////////// p5.Renderer2D.prototype.noSmooth = function() { if ('imageSmoothingEnabled' in this.drawingContext) { this.drawingContext.imageSmoothingEnabled = false; } return this; }; p5.Renderer2D.prototype.smooth = function() { if ('imageSmoothingEnabled' in this.drawingContext) { this.drawingContext.imageSmoothingEnabled = true; } return this; }; p5.Renderer2D.prototype.strokeCap = function(cap) { if ( cap === constants.ROUND || cap === constants.SQUARE || cap === constants.PROJECT ) { this.drawingContext.lineCap = cap; } return this; }; p5.Renderer2D.prototype.strokeJoin = function(join) { if ( join === constants.ROUND || join === constants.BEVEL || join === constants.MITER ) { this.drawingContext.lineJoin = join; } return this; }; p5.Renderer2D.prototype.strokeWeight = function(w) { if (typeof w === 'undefined' || w === 0) { // hack because lineWidth 0 doesn't work this.drawingContext.lineWidth = 0.0001; } else { this.drawingContext.lineWidth = w; } return this; }; p5.Renderer2D.prototype._getFill = function() { if (!this._cachedFillStyle) { this._cachedFillStyle = this.drawingContext.fillStyle; } return this._cachedFillStyle; }; p5.Renderer2D.prototype._setFill = function(fillStyle) { if (fillStyle !== this._cachedFillStyle) { this.drawingContext.fillStyle = fillStyle; this._cachedFillStyle = fillStyle; } }; p5.Renderer2D.prototype._getStroke = function() { if (!this._cachedStrokeStyle) { this._cachedStrokeStyle = this.drawingContext.strokeStyle; } return this._cachedStrokeStyle; }; p5.Renderer2D.prototype._setStroke = function(strokeStyle) { if (strokeStyle !== this._cachedStrokeStyle) { this.drawingContext.strokeStyle = strokeStyle; this._cachedStrokeStyle = strokeStyle; } }; ////////////////////////////////////////////// // SHAPE | Curves ////////////////////////////////////////////// p5.Renderer2D.prototype.bezier = function(x1, y1, x2, y2, x3, y3, x4, y4) { this._pInst.beginShape(); this._pInst.vertex(x1, y1); this._pInst.bezierVertex(x2, y2, x3, y3, x4, y4); this._pInst.endShape(); return this; }; p5.Renderer2D.prototype.curve = function(x1, y1, x2, y2, x3, y3, x4, y4) { this._pInst.beginShape(); this._pInst.curveVertex(x1, y1); this._pInst.curveVertex(x2, y2); this._pInst.curveVertex(x3, y3); this._pInst.curveVertex(x4, y4); this._pInst.endShape(); return this; }; ////////////////////////////////////////////// // SHAPE | Vertex ////////////////////////////////////////////// p5.Renderer2D.prototype._doFillStrokeClose = function() { if (this._doFill) { this.drawingContext.fill(); } if (this._doStroke) { this.drawingContext.stroke(); } this.drawingContext.closePath(); }; ////////////////////////////////////////////// // TRANSFORM ////////////////////////////////////////////// p5.Renderer2D.prototype.applyMatrix = function(a, b, c, d, e, f) { this.drawingContext.transform(a, b, c, d, e, f); }; p5.Renderer2D.prototype.resetMatrix = function() { this.drawingContext.setTransform(1, 0, 0, 1, 0, 0); this.drawingContext.scale( this._pInst._pixelDensity, this._pInst._pixelDensity ); return this; }; p5.Renderer2D.prototype.rotate = function(rad) { this.drawingContext.rotate(rad); }; p5.Renderer2D.prototype.scale = function(x, y) { this.drawingContext.scale(x, y); return this; }; p5.Renderer2D.prototype.shearX = function(rad) { this.drawingContext.transform(1, 0, Math.tan(rad), 1, 0, 0); return this; }; p5.Renderer2D.prototype.shearY = function(rad) { this.drawingContext.transform(1, Math.tan(rad), 0, 1, 0, 0); return this; }; p5.Renderer2D.prototype.translate = function(x, y) { // support passing a vector as the 1st parameter if (x instanceof p5.Vector) { y = x.y; x = x.x; } this.drawingContext.translate(x, y); return this; }; ////////////////////////////////////////////// // TYPOGRAPHY // ////////////////////////////////////////////// p5.Renderer2D.prototype.text = function(str, x, y, maxWidth, maxHeight) { var p = this._pInst, cars, n, ii, jj, line, testLine, testWidth, words, totalHeight, baselineHacked, finalMaxHeight = Number.MAX_VALUE; // baselineHacked: (HACK) // A temporary fix to conform to Processing's implementation // of BASELINE vertical alignment in a bounding box if (!(this._doFill || this._doStroke)) { return; } if (typeof str === 'undefined') { return; } else if (typeof str !== 'string') { str = str.toString(); } str = str.replace(/(\t)/g, ' '); cars = str.split('\n'); if (typeof maxWidth !== 'undefined') { totalHeight = 0; for (ii = 0; ii < cars.length; ii++) { line = ''; words = cars[ii].split(' '); for (n = 0; n < words.length; n++) { testLine = line + words[n] + ' '; testWidth = this.textWidth(testLine); if (testWidth > maxWidth) { line = words[n] + ' '; totalHeight += p.textLeading(); } else { line = testLine; } } } if (this._rectMode === constants.CENTER) { x -= maxWidth / 2; y -= maxHeight / 2; } switch (this.drawingContext.textAlign) { case constants.CENTER: x += maxWidth / 2; break; case constants.RIGHT: x += maxWidth; break; } if (typeof maxHeight !== 'undefined') { switch (this.drawingContext.textBaseline) { case constants.BOTTOM: y += maxHeight - totalHeight; break; case constants._CTX_MIDDLE: // CENTER? y += (maxHeight - totalHeight) / 2; break; case constants.BASELINE: baselineHacked = true; this.drawingContext.textBaseline = constants.TOP; break; } // remember the max-allowed y-position for any line (fix to #928) finalMaxHeight = y + maxHeight - p.textAscent(); } for (ii = 0; ii < cars.length; ii++) { line = ''; words = cars[ii].split(' '); for (n = 0; n < words.length; n++) { testLine = line + words[n] + ' '; testWidth = this.textWidth(testLine); if (testWidth > maxWidth && line.length > 0) { this._renderText(p, line, x, y, finalMaxHeight); line = words[n] + ' '; y += p.textLeading(); } else { line = testLine; } } this._renderText(p, line, x, y, finalMaxHeight); y += p.textLeading(); } } else { // Offset to account for vertically centering multiple lines of text - no // need to adjust anything for vertical align top or baseline var offset = 0, vAlign = p.textAlign().vertical; if (vAlign === constants.CENTER) { offset = (cars.length - 1) * p.textLeading() / 2; } else if (vAlign === constants.BOTTOM) { offset = (cars.length - 1) * p.textLeading(); } for (jj = 0; jj < cars.length; jj++) { this._renderText(p, cars[jj], x, y - offset, finalMaxHeight); y += p.textLeading(); } } if (baselineHacked) { this.drawingContext.textBaseline = constants.BASELINE; } return p; }; p5.Renderer2D.prototype._renderText = function(p, line, x, y, maxY) { if (y >= maxY) { return; // don't render lines beyond our maxY position } p.push(); // fix to #803 if (!this._isOpenType()) { // a system/browser font // no stroke unless specified by user if (this._doStroke && this._strokeSet) { this.drawingContext.strokeText(line, x, y); } if (this._doFill) { // if fill hasn't been set by user, use default text fill if (!this._fillSet) { this._setFill(constants._DEFAULT_TEXT_FILL); } this.drawingContext.fillText(line, x, y); } } else { // an opentype font, let it handle the rendering this._textFont._renderPath(line, x, y, { renderer: this }); } p.pop(); return p; }; p5.Renderer2D.prototype.textWidth = function(s) { if (this._isOpenType()) { return this._textFont._textWidth(s, this._textSize); } return this.drawingContext.measureText(s).width; }; p5.Renderer2D.prototype.textAlign = function(h, v) { if (typeof h !== 'undefined') { if ( h === constants.LEFT || h === constants.RIGHT || h === constants.CENTER ) { this.drawingContext.textAlign = h; } if ( v === constants.TOP || v === constants.BOTTOM || v === constants.CENTER || v === constants.BASELINE ) { if (v === constants.CENTER) { this.drawingContext.textBaseline = constants._CTX_MIDDLE; } else { this.drawingContext.textBaseline = v; } } return this._pInst; } else { var valign = this.drawingContext.textBaseline; if (valign === constants._CTX_MIDDLE) { valign = constants.CENTER; } return { horizontal: this.drawingContext.textAlign, vertical: valign }; } }; p5.Renderer2D.prototype._applyTextProperties = function() { var font, p = this._pInst; this._setProperty('_textAscent', null); this._setProperty('_textDescent', null); font = this._textFont; if (this._isOpenType()) { font = this._textFont.font.familyName; this._setProperty('_textStyle', this._textFont.font.styleName); } this.drawingContext.font = (this._textStyle || 'normal') + ' ' + (this._textSize || 12) + 'px ' + (font || 'sans-serif'); return p; }; ////////////////////////////////////////////// // STRUCTURE ////////////////////////////////////////////// // a push() operation is in progress. // the renderer should return a 'style' object that it wishes to // store on the push stack. // derived renderers should call the base class' push() method // to fetch the base style object. p5.Renderer2D.prototype.push = function() { this.drawingContext.save(); // get the base renderer style return p5.Renderer.prototype.push.apply(this); }; // a pop() operation is in progress // the renderer is passed the 'style' object that it returned // from its push() method. // derived renderers should pass this object to their base // class' pop method p5.Renderer2D.prototype.pop = function(style) { this.drawingContext.restore(); // Re-cache the fill / stroke state this._cachedFillStyle = this.drawingContext.fillStyle; this._cachedStrokeStyle = this.drawingContext.strokeStyle; p5.Renderer.prototype.pop.call(this, style); }; module.exports = p5.Renderer2D; },{"../image/filters":41,"./canvas":20,"./constants":21,"./core":22,"./p5.Renderer":29}],31:[function(_dereq_,module,exports){ /** * @module Rendering * @submodule Rendering * @for p5 */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); _dereq_('./p5.Graphics'); _dereq_('./p5.Renderer2D'); _dereq_('../webgl/p5.RendererGL'); var defaultId = 'defaultCanvas0'; // this gets set again in createCanvas var defaultClass = 'p5Canvas'; /** * Creates a canvas element in the document, and sets the dimensions of it * in pixels. This method should be called only once at the start of setup. * Calling createCanvas more than once in a sketch will result in very * unpredictable behavior. If you want more than one drawing canvas * you could use createGraphics (hidden by default but it can be shown). *

* The system variables width and height are set by the parameters passed * to this function. If createCanvas() is not used, the window will be * given a default size of 100x100 pixels. *

* For more ways to position the canvas, see the * * positioning the canvas wiki page. * * @method createCanvas * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Constant} [renderer] either P2D or WEBGL * @return {p5.Renderer} * @example *
* * function setup() { * createCanvas(100, 50); * background(153); * line(0, 0, width, height); * } * *
* * @alt * Black line extending from top-left of canvas to bottom right. * */ p5.prototype.createCanvas = function(w, h, renderer) { p5._validateParameters('createCanvas', arguments); //optional: renderer, otherwise defaults to p2d var r = renderer || constants.P2D; var c; if (r === constants.WEBGL) { c = document.getElementById(defaultId); if (c) { //if defaultCanvas already exists c.parentNode.removeChild(c); //replace the existing defaultCanvas var thisRenderer = this._renderer; this._elements = this._elements.filter(function(e) { return e !== thisRenderer; }); } c = document.createElement('canvas'); c.id = defaultId; c.classList.add(defaultClass); } else { if (!this._defaultGraphicsCreated) { c = document.createElement('canvas'); var i = 0; while (document.getElementById('defaultCanvas' + i)) { i++; } defaultId = 'defaultCanvas' + i; c.id = defaultId; c.classList.add(defaultClass); } else { // resize the default canvas if new one is created c = this.canvas; } } // set to invisible if still in setup (to prevent flashing with manipulate) if (!this._setupDone) { c.dataset.hidden = true; // tag to show later c.style.visibility = 'hidden'; } if (this._userNode) { // user input node case this._userNode.appendChild(c); } else { document.body.appendChild(c); } // Init our graphics renderer //webgl mode if (r === constants.WEBGL) { this._setProperty('_renderer', new p5.RendererGL(c, this, true)); this._elements.push(this._renderer); } else { //P2D mode if (!this._defaultGraphicsCreated) { this._setProperty('_renderer', new p5.Renderer2D(c, this, true)); this._defaultGraphicsCreated = true; this._elements.push(this._renderer); } } this._renderer.resize(w, h); this._renderer._applyDefaults(); return this._renderer; }; /** * Resizes the canvas to given width and height. The canvas will be cleared * and draw will be called immediately, allowing the sketch to re-render itself * in the resized canvas. * @method resizeCanvas * @param {Number} w width of the canvas * @param {Number} h height of the canvas * @param {Boolean} [noRedraw] don't redraw the canvas immediately * @example *
* function setup() { * createCanvas(windowWidth, windowHeight); * } * * function draw() { * background(0, 100, 200); * } * * function windowResized() { * resizeCanvas(windowWidth, windowHeight); * } *
* * @alt * No image displayed. * */ p5.prototype.resizeCanvas = function(w, h, noRedraw) { p5._validateParameters('resizeCanvas', arguments); if (this._renderer) { // save canvas properties var props = {}; for (var key in this.drawingContext) { var val = this.drawingContext[key]; if (typeof val !== 'object' && typeof val !== 'function') { props[key] = val; } } this._renderer.resize(w, h); // reset canvas properties for (var savedKey in props) { try { this.drawingContext[savedKey] = props[savedKey]; } catch (err) { // ignore read-only property errors } } if (!noRedraw) { this.redraw(); } } }; /** * Removes the default canvas for a p5 sketch that doesn't * require a canvas * @method noCanvas * @example *
* * function setup() { * noCanvas(); * } * *
* * @alt * no image displayed * */ p5.prototype.noCanvas = function() { if (this.canvas) { this.canvas.parentNode.removeChild(this.canvas); } }; /** * Creates and returns a new p5.Renderer object. Use this class if you need * to draw into an off-screen graphics buffer. The two parameters define the * width and height in pixels. * * @method createGraphics * @param {Number} w width of the offscreen graphics buffer * @param {Number} h height of the offscreen graphics buffer * @param {Constant} [renderer] either P2D or WEBGL * undefined defaults to p2d * @return {p5.Graphics} offscreen graphics buffer * @example *
* * var pg; * function setup() { * createCanvas(100, 100); * pg = createGraphics(100, 100); * } * function draw() { * background(200); * pg.background(100); * pg.noStroke(); * pg.ellipse(pg.width / 2, pg.height / 2, 50, 50); * image(pg, 50, 50); * image(pg, 0, 0, 50, 50); * } * *
* * @alt * 4 grey squares alternating light and dark grey. White quarter circle mid-left. * */ p5.prototype.createGraphics = function(w, h, renderer) { p5._validateParameters('createGraphics', arguments); return new p5.Graphics(w, h, renderer, this); }; /** * Blends the pixels in the display window according to the defined mode. * There is a choice of the following modes to blend the source pixels (A) * with the ones of pixels already in the display window (B): *
    *
  • BLEND - linear interpolation of colours: C = * A\*factor + B. This is the default blending mode.
  • *
  • ADD - sum of A and B
  • *
  • DARKEST - only the darkest colour succeeds: C = * min(A\*factor, B).
  • *
  • LIGHTEST - only the lightest colour succeeds: C = * max(A\*factor, B).
  • *
  • DIFFERENCE - subtract colors from underlying image.
  • *
  • EXCLUSION - similar to DIFFERENCE, but less * extreme.
  • *
  • MULTIPLY - multiply the colors, result will always be * darker.
  • *
  • SCREEN - opposite multiply, uses inverse values of the * colors.
  • *
  • REPLACE - the pixels entirely replace the others and * don't utilize alpha (transparency) values.
  • *
  • OVERLAY - mix of MULTIPLY and SCREEN * . Multiplies dark values, and screens light values.
  • *
  • HARD_LIGHT - SCREEN when greater than 50% * gray, MULTIPLY when lower.
  • *
  • SOFT_LIGHT - mix of DARKEST and * LIGHTEST. Works like OVERLAY, but not as harsh. *
  • *
  • DODGE - lightens light tones and increases contrast, * ignores darks.
  • *
  • BURN - darker areas are applied, increasing contrast, * ignores lights.
  • *
* * @method blendMode * @param {Constant} mode blend mode to set for canvas. * either BLEND, DARKEST, LIGHTEST, DIFFERENCE, MULTIPLY, * EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL * @example *
* * blendMode(LIGHTEST); * strokeWeight(30); * stroke(80, 150, 255); * line(25, 25, 75, 75); * stroke(255, 50, 50); * line(75, 25, 25, 75); * *
*
* * blendMode(MULTIPLY); * strokeWeight(30); * stroke(80, 150, 255); * line(25, 25, 75, 75); * stroke(255, 50, 50); * line(75, 25, 25, 75); * *
* @alt * translucent image thick red & blue diagonal rounded lines intersecting center * Thick red & blue diagonal rounded lines intersecting center. dark at overlap * */ p5.prototype.blendMode = function(mode) { p5._validateParameters('blendMode', arguments); if ( mode === constants.BLEND || mode === constants.DARKEST || mode === constants.LIGHTEST || mode === constants.DIFFERENCE || mode === constants.MULTIPLY || mode === constants.EXCLUSION || mode === constants.SCREEN || mode === constants.REPLACE || mode === constants.OVERLAY || mode === constants.HARD_LIGHT || mode === constants.SOFT_LIGHT || mode === constants.DODGE || mode === constants.BURN || mode === constants.ADD || mode === constants.NORMAL ) { this._renderer.blendMode(mode); } else { throw new Error('Mode ' + mode + ' not recognized.'); } }; module.exports = p5; },{"../webgl/p5.RendererGL":72,"./constants":21,"./core":22,"./p5.Graphics":28,"./p5.Renderer2D":30}],32:[function(_dereq_,module,exports){ 'use strict'; // requestAnim shim layer by Paul Irish window.requestAnimationFrame = (function() { return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { // should '60' here be framerate? window.setTimeout(callback, 1000 / 60); } ); })(); // use window.performance() to get max fast and accurate time in milliseconds window.performance = window.performance || {}; window.performance.now = (function() { var load_date = Date.now(); return ( window.performance.now || window.performance.mozNow || window.performance.msNow || window.performance.oNow || window.performance.webkitNow || function() { return Date.now() - load_date; } ); })(); /* // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/ // requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller // fixes from Paul Irish and Tino Zijdel (function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }()); */ /** * shim for Uint8ClampedArray.slice * (allows arrayCopy to work with pixels[]) * with thanks to http://halfpapstudios.com/blog/tag/html5-canvas/ * Enumerable set to false to protect for...in from * Uint8ClampedArray.prototype pollution. */ (function() { 'use strict'; if ( typeof Uint8ClampedArray !== 'undefined' && !Uint8ClampedArray.prototype.slice ) { Object.defineProperty(Uint8ClampedArray.prototype, 'slice', { value: Array.prototype.slice, writable: true, configurable: true, enumerable: false }); } })(); },{}],33:[function(_dereq_,module,exports){ /** * @module Structure * @submodule Structure * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('./core'); p5.prototype.exit = function() { throw 'exit() not implemented, see remove()'; }; /** * Stops p5.js from continuously executing the code within draw(). * If loop() is called, the code in draw() begins to run continuously again. * If using noLoop() in setup(), it should be the last line inside the block. *

* When noLoop() is used, it's not possible to manipulate or access the * screen inside event handling functions such as mousePressed() or * keyPressed(). Instead, use those functions to call redraw() or loop(), * which will run draw(), which can update the screen properly. This means * that when noLoop() has been called, no drawing can happen, and functions * like saveFrame() or loadPixels() may not be used. *

* Note that if the sketch is resized, redraw() will be called to update * the sketch, even after noLoop() has been specified. Otherwise, the sketch * would enter an odd state until loop() was called. * * @method noLoop * @example *
* function setup() { * createCanvas(100, 100); * background(200); * noLoop(); * } * function draw() { * line(10, 10, 90, 90); * } *
* *
* var x = 0; * function setup() { * createCanvas(100, 100); * } * * function draw() { * background(204); * x = x + 0.1; * if (x > width) { * x = 0; * } * line(x, 0, x, height); * } * * function mousePressed() { * noLoop(); * } * * function mouseReleased() { * loop(); * } *
* * @alt * 113 pixel long line extending from top-left to bottom right of canvas. * horizontal line moves slowly from left. Loops but stops on mouse press. * */ p5.prototype.noLoop = function() { this._loop = false; }; /** * By default, p5.js loops through draw() continuously, executing the code * within it. However, the draw() loop may be stopped by calling noLoop(). * In that case, the draw() loop can be resumed with loop(). * * @method loop * @example *
* var x = 0; * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * x = x + 0.1; * if (x > width) { * x = 0; * } * line(x, 0, x, height); * } * * function mousePressed() { * loop(); * } * * function mouseReleased() { * noLoop(); * } *
* * @alt * horizontal line moves slowly from left. Loops but stops on mouse press. * */ p5.prototype.loop = function() { this._loop = true; this._draw(); }; function assign(dest, varArgs) { for (var index = 1; index < arguments.length; index++) { var src = arguments[index]; if (src != null) { for (var key in src) { if (src.hasOwnProperty(key)) { dest[key] = src[key]; } } } } } /** * The push() function saves the current drawing style settings and * transformations, while pop() restores these settings. Note that these * functions are always used together. They allow you to change the style * and transformation settings and later return to what you had. When a new * state is started with push(), it builds on the current style and transform * information. The push() and pop() functions can be embedded to provide * more control. (See the second example for a demonstration.) *

* push() stores information related to the current transformation state * and style settings controlled by the following functions: fill(), * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), * textFont(), textMode(), textSize(), textLeading(). * * @method push * @example *
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * translate(50, 0); * ellipse(0, 50, 33, 33); // Middle circle * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
*
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * ellipse(33, 50, 33, 33); // Left-middle circle * * push(); // Start another new drawing state * stroke(0, 102, 153); * ellipse(66, 50, 33, 33); // Right-middle circle * pop(); // Restore previous state * * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
* * @alt * Gold ellipse + thick black outline @center 2 white ellipses on left and right. * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right. * */ p5.prototype.push = function() { this._styles.push({ props: { _colorMode: this._colorMode }, renderer: this._renderer.push() }); }; /** * The push() function saves the current drawing style settings and * transformations, while pop() restores these settings. Note that these * functions are always used together. They allow you to change the style * and transformation settings and later return to what you had. When a new * state is started with push(), it builds on the current style and transform * information. The push() and pop() functions can be embedded to provide * more control. (See the second example for a demonstration.) *

* push() stores information related to the current transformation state * and style settings controlled by the following functions: fill(), * stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), colorMode(), textAlign(), * textFont(), textMode(), textSize(), textLeading(). * * @method pop * @example *
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * translate(50, 0); * strokeWeight(10); * fill(204, 153, 0); * ellipse(0, 50, 33, 33); // Middle circle * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
*
* * ellipse(0, 50, 33, 33); // Left circle * * push(); // Start a new drawing state * strokeWeight(10); * fill(204, 153, 0); * ellipse(33, 50, 33, 33); // Left-middle circle * * push(); // Start another new drawing state * stroke(0, 102, 153); * ellipse(66, 50, 33, 33); // Right-middle circle * pop(); // Restore previous state * * pop(); // Restore original state * * ellipse(100, 50, 33, 33); // Right circle * *
* * @alt * Gold ellipse + thick black outline @center 2 white ellipses on left and right. * 2 Gold ellipses left black right blue stroke. 2 white ellipses on left+right. * */ p5.prototype.pop = function() { var style = this._styles.pop(); if (style) { this._renderer.pop(style.renderer); assign(this, style.props); } else { console.warn('pop() was called without matching push()'); } }; p5.prototype.pushStyle = function() { throw new Error('pushStyle() not used, see push()'); }; p5.prototype.popStyle = function() { throw new Error('popStyle() not used, see pop()'); }; /** * * Executes the code within draw() one time. This functions allows the * program to update the display window only when necessary, for example * when an event registered by mousePressed() or keyPressed() occurs. *

* In structuring a program, it only makes sense to call redraw() within * events such as mousePressed(). This is because redraw() does not run * draw() immediately (it only sets a flag that indicates an update is * needed). *

* The redraw() function does not work properly when called inside draw(). * To enable/disable animations, use loop() and noLoop(). *

* In addition you can set the number of redraws per method call. Just * add an integer as single parameter for the number of redraws. * * @method redraw * @param {Integer} [n] Redraw for n-times. The default value is 1. * @example *
* var x = 0; * * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * line(x, 0, x, height); * } * * function mousePressed() { * x += 1; * redraw(); * } *
* *
* var x = 0; * * function setup() { * createCanvas(100, 100); * noLoop(); * } * * function draw() { * background(204); * x += 1; * line(x, 0, x, height); * } * * function mousePressed() { * redraw(5); * } *
* * @alt * black line on far left of canvas * black line on far left of canvas * */ p5.prototype.redraw = function(n) { this.resetMatrix(); if (this._renderer.isP3D) { this._renderer._update(); } var numberOfRedraws = parseInt(n); if (isNaN(numberOfRedraws) || numberOfRedraws < 1) { numberOfRedraws = 1; } var userSetup = this.setup || window.setup; var userDraw = this.draw || window.draw; if (typeof userDraw === 'function') { if (typeof userSetup === 'undefined') { this.scale(this._pixelDensity, this._pixelDensity); } var self = this; var callMethod = function(f) { f.call(self); }; for (var idxRedraw = 0; idxRedraw < numberOfRedraws; idxRedraw++) { this._setProperty('frameCount', this.frameCount + 1); this._registeredMethods.pre.forEach(callMethod); userDraw(); this._registeredMethods.post.forEach(callMethod); } } }; p5.prototype.size = function() { var s = 'size() is not a valid p5 function, to set the size of the '; s += 'drawing canvas, please use createCanvas() instead'; throw s; }; module.exports = p5; },{"./core":22}],34:[function(_dereq_,module,exports){ /** * @module Transform * @submodule Transform * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); /** * Multiplies the current matrix by the one specified through the parameters. * This is a powerful operation that can perform the equivalent of translate, * scale, shear and rotate all at once. You can learn more about transformation * matrices on * Wikipedia. * * The naming of the arguments here follows the naming of the * WHATWG specification and corresponds to a * transformation matrix of the * form: * * > The transformation matrix used when applyMatrix is called * * @method applyMatrix * @param {Number} a numbers which define the 2x3 matrix to be multiplied * @param {Number} b numbers which define the 2x3 matrix to be multiplied * @param {Number} c numbers which define the 2x3 matrix to be multiplied * @param {Number} d numbers which define the 2x3 matrix to be multiplied * @param {Number} e numbers which define the 2x3 matrix to be multiplied * @param {Number} f numbers which define the 2x3 matrix to be multiplied * @chainable * @example *
* * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * background(200); * // Equivalent to translate(x, y); * applyMatrix(1, 0, 0, 1, 40 + step, 50); * rect(0, 0, 50, 50); * } * *
*
* * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * background(200); * translate(50, 50); * // Equivalent to scale(x, y); * applyMatrix(1 / step, 0, 0, 1 / step, 0, 0); * rect(0, 0, 50, 50); * } * *
*
* * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * var angle = map(step, 0, 20, 0, TWO_PI); * var cos_a = cos(angle); * var sin_a = sin(angle); * background(200); * translate(50, 50); * // Equivalent to rotate(angle); * applyMatrix(cos_a, sin_a, -sin_a, cos_a, 0, 0); * rect(0, 0, 50, 50); * } * *
*
* * function setup() { * frameRate(10); * rectMode(CENTER); * } * * function draw() { * var step = frameCount % 20; * var angle = map(step, 0, 20, -PI / 4, PI / 4); * background(200); * translate(50, 50); * // equivalent to shearX(angle); * var shear_factor = 1 / tan(PI / 2 - angle); * applyMatrix(1, 0, shear_factor, 1, 0, 0); * rect(0, 0, 50, 50); * } * *
* * @alt * A rectangle translating to the right * A rectangle shrinking to the center * A rectangle rotating clockwise about the center * A rectangle shearing * */ p5.prototype.applyMatrix = function(a, b, c, d, e, f) { this._renderer.applyMatrix(a, b, c, d, e, f); return this; }; p5.prototype.popMatrix = function() { throw new Error('popMatrix() not used, see pop()'); }; p5.prototype.printMatrix = function() { throw new Error('printMatrix() not implemented'); }; p5.prototype.pushMatrix = function() { throw new Error('pushMatrix() not used, see push()'); }; /** * Replaces the current matrix with the identity matrix. * * @method resetMatrix * @chainable * @example *
* * translate(50, 50); * applyMatrix(0.5, 0.5, -0.5, 0.5, 0, 0); * rect(0, 0, 20, 20); * // Note that the translate is also reset. * resetMatrix(); * rect(0, 0, 20, 20); * *
* * @alt * A rotated retangle in the center with another at the top left corner * */ p5.prototype.resetMatrix = function() { this._renderer.resetMatrix(); return this; }; /** * Rotates a shape the amount specified by the angle parameter. This * function accounts for angleMode, so angles can be entered in either * RADIANS or DEGREES. *

* Objects are always rotated around their relative position to the * origin and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * rotate(HALF_PI) and then rotate(HALF_PI) is the same as rotate(PI). * All tranformations are reset when draw() begins again. *

* Technically, rotate() multiplies the current transformation matrix * by a rotation matrix. This function can be further controlled by * the push() and pop(). * * @method rotate * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @param {p5.Vector|Number[]} [axis] (in 3d) the axis to rotate around * @chainable * @example *
* * translate(width / 2, height / 2); * rotate(PI / 3.0); * rect(-26, -26, 52, 52); * *
* * @alt * white 52x52 rect with black outline at center rotated counter 45 degrees * */ p5.prototype.rotate = function(angle, axis) { p5._validateParameters('rotate', arguments); this._renderer.rotate(this._toRadians(angle), axis); return this; }; /** * Rotates around X axis. * @method rotateX * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(255); * rotateX(millis() / 1000); * box(); * } * *
* * @alt * 3d box rotating around the x axis. */ p5.prototype.rotateX = function(angle) { this._assert3d('rotateX'); p5._validateParameters('rotateX', arguments); this._renderer.rotateX(this._toRadians(angle)); return this; }; /** * Rotates around Y axis. * @method rotateY * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(255); * rotateY(millis() / 1000); * box(); * } * *
* * @alt * 3d box rotating around the y axis. */ p5.prototype.rotateY = function(angle) { this._assert3d('rotateY'); p5._validateParameters('rotateY', arguments); this._renderer.rotateY(this._toRadians(angle)); return this; }; /** * Rotates around Z axis. Webgl mode only. * @method rotateZ * @param {Number} angle the angle of rotation, specified in radians * or degrees, depending on current angleMode * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(255); * rotateZ(millis() / 1000); * box(); * } * *
* * @alt * 3d box rotating around the z axis. */ p5.prototype.rotateZ = function(angle) { this._assert3d('rotateZ'); p5._validateParameters('rotateZ', arguments); this._renderer.rotateZ(this._toRadians(angle)); return this; }; /** * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call scale(2.0) increases the dimension of a * shape by 200%. *

* Transformations apply to everything that happens after and subsequent * calls to the function multiply the effect. For example, calling scale(2.0) * and then scale(1.5) is the same as scale(3.0). If scale() is called * within draw(), the transformation is reset when the loop begins again. *

* Using this function with the z parameter is only available in WEBGL mode. * This function can be further controlled with push() and pop(). * * @method scale * @param {Number|p5.Vector|Number[]} s * percent to scale the object, or percentage to * scale the object in the x-axis if multiple arguments * are given * @param {Number} [y] percent to scale the object in the y-axis * @param {Number} [z] percent to scale the object in the z-axis (webgl only) * @chainable * @example *
* * translate(width / 2, height / 2); * rotate(PI / 3.0); * rect(-26, -26, 52, 52); * *
* *
* * rect(30, 20, 50, 50); * scale(0.5, 1.3); * rect(30, 20, 50, 50); * *
* * @alt * white 52x52 rect with black outline at center rotated counter 45 degrees * 2 white rects with black outline- 1 50x50 at center. other 25x65 bottom left * */ /** * @method scale * @param {p5.Vector|Number[]} scales per-axis percents to scale the object * @chainable */ p5.prototype.scale = function(x, y, z) { p5._validateParameters('scale', arguments); // Only check for Vector argument type if Vector is available if (x instanceof p5.Vector) { var v = x; x = v.x; y = v.y; z = v.z; } else if (x instanceof Array) { var rg = x; x = rg[0]; y = rg[1]; z = rg[2] || 1; } if (isNaN(y)) { y = z = x; } else if (isNaN(z)) { z = 1; } this._renderer.scale.call(this._renderer, x, y, z); return this; }; /** * Shears a shape around the x-axis the amount specified by the angle * parameter. Angles should be specified in the current angleMode. * Objects are always sheared around their relative position to the origin * and positive numbers shear objects in a clockwise direction. *

* Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * shearX(PI/2) and then shearX(PI/2) is the same as shearX(PI). * If shearX() is called within the draw(), the transformation is reset when * the loop begins again. *

* Technically, shearX() multiplies the current transformation matrix by a * rotation matrix. This function can be further controlled by the * push() and pop() functions. * * @method shearX * @param {Number} angle angle of shear specified in radians or degrees, * depending on current angleMode * @chainable * @example *
* * translate(width / 4, height / 4); * shearX(PI / 4.0); * rect(0, 0, 30, 30); * *
* * @alt * white irregular quadrilateral with black outline at top middle. * */ p5.prototype.shearX = function(angle) { p5._validateParameters('shearX', arguments); this._renderer.shearX(this._toRadians(angle)); return this; }; /** * Shears a shape around the y-axis the amount specified by the angle * parameter. Angles should be specified in the current angleMode. Objects * are always sheared around their relative position to the origin and * positive numbers shear objects in a clockwise direction. *

* Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * shearY(PI/2) and then shearY(PI/2) is the same as shearY(PI). If * shearY() is called within the draw(), the transformation is reset when * the loop begins again. *

* Technically, shearY() multiplies the current transformation matrix by a * rotation matrix. This function can be further controlled by the * push() and pop() functions. * * @method shearY * @param {Number} angle angle of shear specified in radians or degrees, * depending on current angleMode * @chainable * @example *
* * translate(width / 4, height / 4); * shearY(PI / 4.0); * rect(0, 0, 30, 30); * *
* * @alt * white irregular quadrilateral with black outline at middle bottom. * */ p5.prototype.shearY = function(angle) { p5._validateParameters('shearY', arguments); this._renderer.shearY(this._toRadians(angle)); return this; }; /** * Specifies an amount to displace objects within the display window. * The x parameter specifies left/right translation, the y parameter * specifies up/down translation. *

* Transformations are cumulative and apply to everything that happens after * and subsequent calls to the function accumulates the effect. For example, * calling translate(50, 0) and then translate(20, 0) is the same as * translate(70, 0). If translate() is called within draw(), the * transformation is reset when the loop begins again. This function can be * further controlled by using push() and pop(). * * @method translate * @param {Number} x left/right translation * @param {Number} y up/down translation * @param {Number} [z] forward/backward translation (webgl only) * @chainable * @example *
* * translate(30, 20); * rect(0, 0, 55, 55); * *
* *
* * rect(0, 0, 55, 55); // Draw rect at original 0,0 * translate(30, 20); * rect(0, 0, 55, 55); // Draw rect at new 0,0 * translate(14, 14); * rect(0, 0, 55, 55); // Draw rect at new 0,0 * *
* *
* * function draw() { * background(200); * rectMode(CENTER); * translate(width / 2, height / 2); * translate(p5.Vector.fromAngle(millis() / 1000, 40)); * rect(0, 0, 20, 20); * } * *
* * @alt * white 55x55 rect with black outline at center right. * 3 white 55x55 rects with black outlines at top-l, center-r and bottom-r. * a 20x20 white rect moving in a circle around the canvas * */ /** * @method translate * @param {p5.Vector} vector the vector to translate by * @chainable */ p5.prototype.translate = function(x, y, z) { p5._validateParameters('translate', arguments); if (this._renderer.isP3D) { this._renderer.translate(x, y, z); } else { this._renderer.translate(x, y); } return this; }; module.exports = p5; },{"./core":22}],35:[function(_dereq_,module,exports){ /** * @module Shape * @submodule Vertex * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('./core'); var constants = _dereq_('./constants'); var shapeKind = null; var vertices = []; var contourVertices = []; var isBezier = false; var isCurve = false; var isQuadratic = false; var isContour = false; var isFirstContour = true; /** * Use the beginContour() and endContour() functions to create negative * shapes within shapes such as the center of the letter 'O'. beginContour() * begins recording vertices for the shape and endContour() stops recording. * The vertices that define a negative shape must "wind" in the opposite * direction from the exterior shape. First draw vertices for the exterior * clockwise order, then for internal shapes, draw vertices * shape in counter-clockwise. *

* These functions can only be used within a beginShape()/endShape() pair and * transformations such as translate(), rotate(), and scale() do not work * within a beginContour()/endContour() pair. It is also not possible to use * other shapes, such as ellipse() or rect() within. * * @method beginContour * @chainable * @example *
* * translate(50, 50); * stroke(255, 0, 0); * beginShape(); * // Exterior part of shape, clockwise winding * vertex(-40, -40); * vertex(40, -40); * vertex(40, 40); * vertex(-40, 40); * // Interior part of shape, counter-clockwise winding * beginContour(); * vertex(-20, -20); * vertex(-20, 20); * vertex(20, 20); * vertex(20, -20); * endContour(); * endShape(CLOSE); * *
* * @alt * white rect and smaller grey rect with red outlines in center of canvas. * */ p5.prototype.beginContour = function() { contourVertices = []; isContour = true; return this; }; /** * Using the beginShape() and endShape() functions allow creating more * complex forms. beginShape() begins recording vertices for a shape and * endShape() stops recording. The value of the kind parameter tells it which * types of shapes to create from the provided vertices. With no mode * specified, the shape can be any irregular polygon. *

* The parameters available for beginShape() are POINTS, LINES, TRIANGLES, * TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. After calling the * beginShape() function, a series of vertex() commands must follow. To stop * drawing the shape, call endShape(). Each shape will be outlined with the * current stroke color and filled with the fill color. *

* Transformations such as translate(), rotate(), and scale() do not work * within beginShape(). It is also not possible to use other shapes, such as * ellipse() or rect() within beginShape(). * * @method beginShape * @param {Constant} [kind] either POINTS, LINES, TRIANGLES, TRIANGLE_FAN * TRIANGLE_STRIP, QUADS, or QUAD_STRIP * @chainable * @example *
* * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(CLOSE); * *
* *
* * beginShape(POINTS); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* *
* * beginShape(LINES); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* *
* * noFill(); * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* *
* * noFill(); * beginShape(); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(CLOSE); * *
* *
* * beginShape(TRIANGLES); * vertex(30, 75); * vertex(40, 20); * vertex(50, 75); * vertex(60, 20); * vertex(70, 75); * vertex(80, 20); * endShape(); * *
* *
* * beginShape(TRIANGLE_STRIP); * vertex(30, 75); * vertex(40, 20); * vertex(50, 75); * vertex(60, 20); * vertex(70, 75); * vertex(80, 20); * vertex(90, 75); * endShape(); * *
* *
* * beginShape(TRIANGLE_FAN); * vertex(57.5, 50); * vertex(57.5, 15); * vertex(92, 50); * vertex(57.5, 85); * vertex(22, 50); * vertex(57.5, 15); * endShape(); * *
* *
* * beginShape(QUADS); * vertex(30, 20); * vertex(30, 75); * vertex(50, 75); * vertex(50, 20); * vertex(65, 20); * vertex(65, 75); * vertex(85, 75); * vertex(85, 20); * endShape(); * *
* *
* * beginShape(QUAD_STRIP); * vertex(30, 20); * vertex(30, 75); * vertex(50, 20); * vertex(50, 75); * vertex(65, 20); * vertex(65, 75); * vertex(85, 20); * vertex(85, 75); * endShape(); * *
* *
* * beginShape(); * vertex(20, 20); * vertex(40, 20); * vertex(40, 40); * vertex(60, 40); * vertex(60, 60); * vertex(20, 60); * endShape(CLOSE); * *
* @alt * white square-shape with black outline in middle-right of canvas. * 4 black points in a square shape in middle-right of canvas. * 2 horizontal black lines. In the top-right and bottom-right of canvas. * 3 line shape with horizontal on top, vertical in middle and horizontal bottom. * square line shape in middle-right of canvas. * 2 white triangle shapes mid-right canvas. left one pointing up and right down. * 5 horizontal interlocking and alternating white triangles in mid-right canvas. * 4 interlocking white triangles in 45 degree rotated square-shape. * 2 white rectangle shapes in mid-right canvas. Both 20x55. * 3 side-by-side white rectangles center rect is smaller in mid-right canvas. * Thick white l-shape with black outline mid-top-left of canvas. * */ p5.prototype.beginShape = function(kind) { p5._validateParameters('beginShape', arguments); if (this._renderer.isP3D) { this._renderer.beginShape.apply(this._renderer, arguments); } else { if ( kind === constants.POINTS || kind === constants.LINES || kind === constants.TRIANGLES || kind === constants.TRIANGLE_FAN || kind === constants.TRIANGLE_STRIP || kind === constants.QUADS || kind === constants.QUAD_STRIP ) { shapeKind = kind; } else { shapeKind = null; } vertices = []; contourVertices = []; } return this; }; /** * Specifies vertex coordinates for Bezier curves. Each call to * bezierVertex() defines the position of two control points and * one anchor point of a Bezier curve, adding a new segment to a * line or shape. *

* The first time bezierVertex() is used within a * beginShape() call, it must be prefaced with a call to vertex() * to set the first anchor point. This function must be used between * beginShape() and endShape() and only when there is no MODE * parameter specified to beginShape(). * * @method bezierVertex * @param {Number} x2 x-coordinate for the first control point * @param {Number} y2 y-coordinate for the first control point * @param {Number} x3 x-coordinate for the second control point * @param {Number} y3 y-coordinate for the second control point * @param {Number} x4 x-coordinate for the anchor point * @param {Number} y4 y-coordinate for the anchor point * @chainable * @example *
* * strokeWeight(5); * point(30, 20); * point(80, 20); * point(80, 75); * point(30, 75); * * strokeWeight(1); * noFill(); * beginShape(); * vertex(30, 20); * bezierVertex(80, 20, 80, 75, 30, 75); * endShape(); * *
* *
* * strokeWeight(5); * point(30, 20); * point(80, 20); * point(80, 75); * point(30, 75); * * stroke(244, 122, 158); * point(50, 80); * point(60, 25); * point(30, 20); * * stroke(0); * strokeWeight(1); * beginShape(); * vertex(30, 20); * bezierVertex(80, 20, 80, 75, 30, 75); * bezierVertex(50, 80, 60, 25, 30, 20); * endShape(); * *
* * @alt * crescent-shaped line in middle of canvas. Points facing left. * white crescent shape in middle of canvas. Points facing left. * */ p5.prototype.bezierVertex = function(x2, y2, x3, y3, x4, y4) { p5._validateParameters('bezierVertex', arguments); if (vertices.length === 0) { throw 'vertex() must be used once before calling bezierVertex()'; } else { isBezier = true; var vert = []; for (var i = 0; i < arguments.length; i++) { vert[i] = arguments[i]; } vert.isVert = false; if (isContour) { contourVertices.push(vert); } else { vertices.push(vert); } } return this; }; /** * Specifies vertex coordinates for curves. This function may only * be used between beginShape() and endShape() and only when there * is no MODE parameter specified to beginShape(). *

* The first and last points in a series of curveVertex() lines will be used to * guide the beginning and end of a the curve. A minimum of four * points is required to draw a tiny curve between the second and * third points. Adding a fifth point with curveVertex() will draw * the curve between the second, third, and fourth points. The * curveVertex() function is an implementation of Catmull-Rom * splines. * * @method curveVertex * @param {Number} x x-coordinate of the vertex * @param {Number} y y-coordinate of the vertex * @chainable * @example *
* * strokeWeight(5); * point(84, 91); * point(68, 19); * point(21, 17); * point(32, 91); * strokeWeight(1); * * noFill(); * beginShape(); * curveVertex(84, 91); * curveVertex(84, 91); * curveVertex(68, 19); * curveVertex(21, 17); * curveVertex(32, 91); * curveVertex(32, 91); * endShape(); * *
* * * @alt * Upside-down u-shape line, mid canvas. left point extends beyond canvas view. * */ p5.prototype.curveVertex = function(x, y) { p5._validateParameters('curveVertex', arguments); isCurve = true; this.vertex(x, y); return this; }; /** * Use the beginContour() and endContour() functions to create negative * shapes within shapes such as the center of the letter 'O'. beginContour() * begins recording vertices for the shape and endContour() stops recording. * The vertices that define a negative shape must "wind" in the opposite * direction from the exterior shape. First draw vertices for the exterior * clockwise order, then for internal shapes, draw vertices * shape in counter-clockwise. *

* These functions can only be used within a beginShape()/endShape() pair and * transformations such as translate(), rotate(), and scale() do not work * within a beginContour()/endContour() pair. It is also not possible to use * other shapes, such as ellipse() or rect() within. * * @method endContour * @chainable * @example *
* * translate(50, 50); * stroke(255, 0, 0); * beginShape(); * // Exterior part of shape, clockwise winding * vertex(-40, -40); * vertex(40, -40); * vertex(40, 40); * vertex(-40, 40); * // Interior part of shape, counter-clockwise winding * beginContour(); * vertex(-20, -20); * vertex(-20, 20); * vertex(20, 20); * vertex(20, -20); * endContour(); * endShape(CLOSE); * *
* * @alt * white rect and smaller grey rect with red outlines in center of canvas. * */ p5.prototype.endContour = function() { var vert = contourVertices[0].slice(); // copy all data vert.isVert = contourVertices[0].isVert; vert.moveTo = false; contourVertices.push(vert); // prevent stray lines with multiple contours if (isFirstContour) { vertices.push(vertices[0]); isFirstContour = false; } for (var i = 0; i < contourVertices.length; i++) { vertices.push(contourVertices[i]); } return this; }; /** * The endShape() function is the companion to beginShape() and may only be * called after beginShape(). When endshape() is called, all of image data * defined since the previous call to beginShape() is written into the image * buffer. The constant CLOSE as the value for the MODE parameter to close * the shape (to connect the beginning and the end). * * @method endShape * @param {Constant} [mode] use CLOSE to close the shape * @chainable * @example *
* * noFill(); * * beginShape(); * vertex(20, 20); * vertex(45, 20); * vertex(45, 80); * endShape(CLOSE); * * beginShape(); * vertex(50, 20); * vertex(75, 20); * vertex(75, 80); * endShape(); * *
* * @alt * Triangle line shape with smallest interior angle on bottom and upside-down L. * */ p5.prototype.endShape = function(mode) { p5._validateParameters('endShape', arguments); if (this._renderer.isP3D) { this._renderer.endShape( mode, isCurve, isBezier, isQuadratic, isContour, shapeKind ); } else { if (vertices.length === 0) { return this; } if (!this._renderer._doStroke && !this._renderer._doFill) { return this; } var closeShape = mode === constants.CLOSE; // if the shape is closed, the first element is also the last element if (closeShape && !isContour) { vertices.push(vertices[0]); } this._renderer.endShape( mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind ); // Reset some settings isCurve = false; isBezier = false; isQuadratic = false; isContour = false; isFirstContour = true; // If the shape is closed, the first element was added as last element. // We must remove it again to prevent the list of vertices from growing // over successive calls to endShape(CLOSE) if (closeShape) { vertices.pop(); } } return this; }; /** * Specifies vertex coordinates for quadratic Bezier curves. Each call to * quadraticVertex() defines the position of one control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time quadraticVertex() is used within a beginShape() call, it * must be prefaced with a call to vertex() to set the first anchor point. * This function must be used between beginShape() and endShape() and only * when there is no MODE parameter specified to beginShape(). * * @method quadraticVertex * @param {Number} cx x-coordinate for the control point * @param {Number} cy y-coordinate for the control point * @param {Number} x3 x-coordinate for the anchor point * @param {Number} y3 y-coordinate for the anchor point * @chainable * @example *
* * strokeWeight(5); * point(20, 20); * point(80, 20); * point(50, 50); * * noFill(); * strokeWeight(1); * beginShape(); * vertex(20, 20); * quadraticVertex(80, 20, 50, 50); * endShape(); * *
* *
* * strokeWeight(5); * point(20, 20); * point(80, 20); * point(50, 50); * * point(20, 80); * point(80, 80); * point(80, 60); * * noFill(); * strokeWeight(1); * beginShape(); * vertex(20, 20); * quadraticVertex(80, 20, 50, 50); * quadraticVertex(20, 80, 80, 80); * vertex(80, 60); * endShape(); * *
* * @alt * arched-shaped black line with 4 pixel thick stroke weight. * backwards s-shaped black line with 4 pixel thick stroke weight. * */ p5.prototype.quadraticVertex = function(cx, cy, x3, y3) { p5._validateParameters('quadraticVertex', arguments); //if we're drawing a contour, put the points into an // array for inside drawing if (this._contourInited) { var pt = {}; pt.x = cx; pt.y = cy; pt.x3 = x3; pt.y3 = y3; pt.type = constants.QUADRATIC; this._contourVertices.push(pt); return this; } if (vertices.length > 0) { isQuadratic = true; var vert = []; for (var i = 0; i < arguments.length; i++) { vert[i] = arguments[i]; } vert.isVert = false; if (isContour) { contourVertices.push(vert); } else { vertices.push(vert); } } else { throw 'vertex() must be used once before calling quadraticVertex()'; } return this; }; /** * All shapes are constructed by connecting a series of vertices. vertex() * is used to specify the vertex coordinates for points, lines, triangles, * quads, and polygons. It is used exclusively within the beginShape() and * endShape() functions. * * @method vertex * @param {Number} x x-coordinate of the vertex * @param {Number} y y-coordinate of the vertex * @chainable * @example *
* * strokeWeight(3); * beginShape(POINTS); * vertex(30, 20); * vertex(85, 20); * vertex(85, 75); * vertex(30, 75); * endShape(); * *
* * @alt * 4 black points in a square shape in middle-right of canvas. * *
* * createCanvas(100, 100, WEBGL); * background(240, 240, 240); * fill(237, 34, 93); * noStroke(); * beginShape(); * vertex(0, 35); * vertex(35, 0); * vertex(0, -35); * vertex(-35, 0); * endShape(); * *
* * @alt * 4 points making a diamond shape * *
* * createCanvas(100, 100, WEBGL); * background(240, 240, 240); * fill(237, 34, 93); * noStroke(); * beginShape(); * vertex(-10, 10); * vertex(0, 35); * vertex(10, 10); * vertex(35, 0); * vertex(10, -8); * vertex(0, -35); * vertex(-10, -8); * vertex(-35, 0); * endShape(); * *
* * @alt * 8 points making a star * *
* * strokeWeight(3); * stroke(237, 34, 93); * beginShape(LINES); * vertex(10, 35); * vertex(90, 35); * vertex(10, 65); * vertex(90, 65); * vertex(35, 10); * vertex(35, 90); * vertex(65, 10); * vertex(65, 90); * endShape(); * *
* * @alt * 8 points making 4 lines * */ /** * @method vertex * @param {Number} x * @param {Number} y * @param {Number} [z] z-coordinate of the vertex * @param {Number} [u] the vertex's texture u-coordinate * @param {Number} [v] the vertex's texture v-coordinate */ p5.prototype.vertex = function(x, y, moveTo, u, v) { if (this._renderer.isP3D) { this._renderer.vertex.apply(this._renderer, arguments); } else { var vert = []; vert.isVert = true; vert[0] = x; vert[1] = y; vert[2] = 0; vert[3] = 0; vert[4] = 0; vert[5] = this._renderer._getFill(); vert[6] = this._renderer._getStroke(); if (moveTo) { vert.moveTo = moveTo; } if (isContour) { if (contourVertices.length === 0) { vert.moveTo = true; } contourVertices.push(vert); } else { vertices.push(vert); } } return this; }; module.exports = p5; },{"./constants":21,"./core":22}],36:[function(_dereq_,module,exports){ /** * @module Data * @submodule Dictionary * @for p5.TypedDict * @requires core * * This module defines the p5 methods for the p5 Dictionary classes * these classes StringDict and NumberDict are for storing and working * with key, value pairs */ 'use strict'; var p5 = _dereq_('../core/core'); /** * * Creates a new instance of p5.StringDict using the key, value pair * or object you provide. * * @method createStringDict * @for p5 * @param {String} key * @param {String} value * @return {p5.StringDict} * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // logs true to console * } *
*/ /** * @method createStringDict * @param {Object} object object * @return {p5.StringDict} */ p5.prototype.createStringDict = function(key, value) { p5._validateParameters('createStringDict', arguments); return new p5.StringDict(key, value); }; /** * * Creates a new instance of p5.NumberDict using the key, value pair * or object you provide. * * @method createNumberDict * @for p5 * @param {Number} key * @param {Number} value * @return {p5.NumberDict} * * @example *
* * function setup() { * var myDictionary = createNumberDict(100, 42); * print(myDictionary.hasKey(100)); // logs true to console * } *
*/ /** * @method createNumberDict * @param {Object} object object * @return {p5.NumberDict} */ p5.prototype.createNumberDict = function(key, value) { p5._validateParameters('createNumberDict', arguments); return new p5.NumberDict(key, value); }; /** * * Base class for all p5.Dictionary types. More specifically * typed Dictionary objects inherit from this * * @class p5.TypedDict * */ p5.TypedDict = function(key, value) { if (key instanceof Object) { this.data = key; } else { this.data = {}; this.data[key] = value; } return this; }; /** * Returns the number of key-value pairs currently in Dictionary object * * @method size * @return {Integer} the number of key-value pairs in Dictionary object * * @example *
* * function setup() { * var myDictionary = createNumberDict(1, 10); * myDictionary.create(2, 20); * myDictionary.create(3, 30); * print(myDictionary.size()); // value of amt is 3 * } *
* */ p5.TypedDict.prototype.size = function() { return Object.keys(this.data).length; }; /** * Returns true if key exists in Dictionary * otherwise returns false * * @method hasKey * @param {Number|String} key that you want to access * @return {Boolean} whether that key exists in Dictionary * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // logs true to console * } *
* */ p5.TypedDict.prototype.hasKey = function(key) { return this.data.hasOwnProperty(key); }; /** * Returns value stored at supplied key. * * @method get * @param {Number|String} key that you want to access * @return {Number|String} the value stored at that key * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * var myValue = myDictionary.get('p5'); * print(myValue === 'js'); // logs true to console * } *
* */ p5.TypedDict.prototype.get = function(key) { if (this.data.hasOwnProperty(key)) { return this.data[key]; } else { console.log(key + ' does not exist in this Dictionary'); } }; /** * Changes the value of key if in it already exists in * in the Dictionary otherwise makes a new key-value pair * * @method set * @param {Number|String} key * @param {Number|String} value * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.set('p5', 'JS'); * myDictionary.print(); * // above logs "key: p5 - value: JS" to console * } *
* */ p5.TypedDict.prototype.set = function(key, value) { if (this._validate(value)) { this.data[key] = value; } else { console.log('Those values dont work for this dictionary type.'); } }; /** * private helper function to handle the user passing objects in * during construction or calls to create() */ p5.TypedDict.prototype._addObj = function(obj) { for (var key in obj) { this.set(key, obj[key]); } }; /** * Creates a key-value pair in the Dictionary * * @method create * @param {Number|String} key * @param {Number|String} value * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console * } *
*/ /** * @method create * @param {Object} obj key/value pair */ p5.TypedDict.prototype.create = function(key, value) { if (key instanceof Object && typeof value === 'undefined') { this._addObj(key); } else if (typeof key !== 'undefined') { this.set(key, value); } else { console.log( 'In order to create a new Dictionary entry you must pass ' + 'an object or a key, value pair' ); } }; /** * Empties Dictionary of all key-value pairs * @method clear * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * print(myDictionary.hasKey('p5')); // prints 'true' * myDictionary.clear(); * print(myDictionary.hasKey('p5')); // prints 'false' * } * *
*/ p5.TypedDict.prototype.clear = function() { this.data = {}; }; /** * Removes a key-value pair in the Dictionary * * @method remove * @param {Number|String} key for the pair to remove * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console * myDictionary.remove('p5'); * myDictionary.print(); * // above logs "key: happy value: coding" to console * } *
* */ p5.TypedDict.prototype.remove = function(key) { if (this.data.hasOwnProperty(key)) { delete this.data[key]; } else { throw key + ' does not exist in this Dictionary'; } }; /** * Logs the list of items currently in the Dictionary to the console * * @method print * * @example *
* * function setup() { * var myDictionary = createStringDict('p5', 'js'); * myDictionary.create('happy', 'coding'); * myDictionary.print(); * // above logs "key: p5 - value: js, key: happy - value: coding" to console * } * *
*/ p5.TypedDict.prototype.print = function() { for (var item in this.data) { console.log('key:' + item + ' value:' + this.data[item]); } }; /** * Converts the Dictionary into a CSV file for local * storage. * * @method saveTable * @example *
* * createButton('save') * .position(10, 10) * .mousePressed(function() { * createStringDict({ * john: 1940, paul: 1942, george: 1943, ringo: 1940 * }).saveTable('beatles'); * }); * *
*/ p5.TypedDict.prototype.saveTable = function(filename) { var output = ''; for (var key in this.data) { output += key + ',' + this.data[key] + '\n'; } var blob = new Blob([output], { type: 'text/csv' }); p5.prototype.downloadFile(blob, filename || 'mycsv', 'csv'); }; /** * Converts the Dictionary into a JSON file for local * storage. * * @method saveJSON * @example *
* * createButton('save') * .position(10, 10) * .mousePressed(function() { * createStringDict({ * john: 1940, paul: 1942, george: 1943, ringo: 1940 * }).saveJSON('beatles'); * }); * *
*/ p5.TypedDict.prototype.saveJSON = function(filename, opt) { p5.prototype.saveJSON(this.data, filename, opt); }; /** * private helper function to ensure that the user passed in valid * values for the Dictionary type */ p5.TypedDict.prototype._validate = function(value) { return true; }; /** * * A Dictionary class for Strings. * * * @class p5.StringDict * @extends p5.TypedDict * */ p5.StringDict = function() { p5.TypedDict.apply(this, arguments); }; p5.StringDict.prototype = Object.create(p5.TypedDict.prototype); p5.StringDict.prototype._validate = function(value) { return typeof value === 'string'; }; /** * * A simple Dictionary class for Numbers. * * * @class p5.NumberDict * @extends p5.TypedDict * */ p5.NumberDict = function() { p5.TypedDict.apply(this, arguments); }; p5.NumberDict.prototype = Object.create(p5.TypedDict.prototype); /** * private helper function to ensure that the user passed in valid * values for the Dictionary type */ p5.NumberDict.prototype._validate = function(value) { return typeof value === 'number'; }; /** * Add to a value stored at a certain key * The sum is stored in that location in the Dictionary. * * @method add * @param {Number} Key for value you wish to add to * @param {Number} Amount to add to the value * @example *
* * function setup() { * var myDictionary = createNumberDict(2, 5); * myDictionary.add(2, 2); * console.log(myDictionary.get(2)); // logs 7 to console. * } *
* * */ p5.NumberDict.prototype.add = function(key, amount) { if (this.data.hasOwnProperty(key)) { this.data[key] += amount; } else { console.log('The key - ' + key + ' does not exist in this dictionary.'); } }; /** * Subtract from a value stored at a certain key * The difference is stored in that location in the Dictionary. * * @method sub * @param {Number} Key for value you wish to subtract from * @param {Number} Amount to subtract from the value * @example *
* * function setup() { * var myDictionary = createNumberDict(2, 5); * myDictionary.sub(2, 2); * console.log(myDictionary.get(2)); // logs 3 to console. * } *
* * */ p5.NumberDict.prototype.sub = function(key, amount) { this.add(key, -amount); }; /** * Multiply a value stored at a certain key * The product is stored in that location in the Dictionary. * * @method mult * @param {Number} Key for value you wish to multiply * @param {Number} Amount to multiply the value by * @example *
* * function setup() { * var myDictionary = createNumberDict(2, 4); * myDictionary.mult(2, 2); * console.log(myDictionary.get(2)); // logs 8 to console. * } *
* * */ p5.NumberDict.prototype.mult = function(key, amount) { if (this.data.hasOwnProperty(key)) { this.data[key] *= amount; } else { console.log('The key - ' + key + ' does not exist in this dictionary.'); } }; /** * Divide a value stored at a certain key * The quotient is stored in that location in the Dictionary. * * @method div * @param {Number} Key for value you wish to divide * @param {Number} Amount to divide the value by * @example *
* * function setup() { * var myDictionary = createNumberDict(2, 8); * myDictionary.div(2, 2); * console.log(myDictionary.get(2)); // logs 4 to console. * } *
* * */ p5.NumberDict.prototype.div = function(key, amount) { if (this.data.hasOwnProperty(key)) { this.data[key] /= amount; } else { console.log('The key - ' + key + ' does not exist in this dictionary.'); } }; /** * private helper function for finding lowest or highest value * the argument 'flip' is used to flip the comparison arrow * from 'less than' to 'greater than' * */ p5.NumberDict.prototype._valueTest = function(flip) { if (Object.keys(this.data).length === 0) { throw 'Unable to search for a minimum or maximum value on an empty NumberDict'; } else if (Object.keys(this.data).length === 1) { return this.data[Object.keys(this.data)[0]]; } else { var result = this.data[Object.keys(this.data)[0]]; for (var key in this.data) { if (this.data[key] * flip < result * flip) { result = this.data[key]; } } return result; } }; /** * Return the lowest value. * * @method minValue * @return {Number} * @example *
* * function setup() { * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); * var lowestValue = myDictionary.minValue(); // value is -10 * print(lowestValue); * } *
* */ p5.NumberDict.prototype.minValue = function() { return this._valueTest(1); }; /** * Return the highest value. * * @method maxValue * @return {Number} * @example *
* * function setup() { * var myDictionary = createNumberDict({ 2: -10, 4: 0.65, 1.2: 3 }); * var highestValue = myDictionary.maxValue(); // value is 3 * print(highestValue); * } *
* */ p5.NumberDict.prototype.maxValue = function() { return this._valueTest(-1); }; /** * private helper function for finding lowest or highest key * the argument 'flip' is used to flip the comparison arrow * from 'less than' to 'greater than' * */ p5.NumberDict.prototype._keyTest = function(flip) { if (Object.keys(this.data).length === 0) { throw 'Unable to use minValue on an empty NumberDict'; } else if (Object.keys(this.data).length === 1) { return Object.keys(this.data)[0]; } else { var result = Object.keys(this.data)[0]; for (var i = 1; i < Object.keys(this.data).length; i++) { if (Object.keys(this.data)[i] * flip < result * flip) { result = Object.keys(this.data)[i]; } } return result; } }; /** * Return the lowest key. * * @method minKey * @return {Number} * @example *
* * function setup() { * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); * var lowestKey = myDictionary.minKey(); // value is 1.2 * print(lowestKey); * } *
* */ p5.NumberDict.prototype.minKey = function() { return this._keyTest(1); }; /** * Return the highest key. * * @method maxKey * @return {Number} * @example *
* * function setup() { * var myDictionary = createNumberDict({ 2: 4, 4: 6, 1.2: 3 }); * var highestKey = myDictionary.maxKey(); // value is 4 * print(highestKey); * } *
* */ p5.NumberDict.prototype.maxKey = function() { return this._keyTest(-1); }; module.exports = p5.TypedDict; },{"../core/core":22}],37:[function(_dereq_,module,exports){ /** * @module Events * @submodule Acceleration * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * The system variable deviceOrientation always contains the orientation of * the device. The value of this variable will either be set 'landscape' * or 'portrait'. If no data is available it will be set to 'undefined'. * either LANDSCAPE or PORTRAIT. * * @property {Constant} deviceOrientation * @readOnly */ p5.prototype.deviceOrientation = undefined; /** * The system variable accelerationX always contains the acceleration of the * device along the x axis. Value is represented as meters per second squared. * * @property {Number} accelerationX * @readOnly */ p5.prototype.accelerationX = 0; /** * The system variable accelerationY always contains the acceleration of the * device along the y axis. Value is represented as meters per second squared. * * @property {Number} accelerationY * @readOnly */ p5.prototype.accelerationY = 0; /** * The system variable accelerationZ always contains the acceleration of the * device along the z axis. Value is represented as meters per second squared. * * @property {Number} accelerationZ * @readOnly */ p5.prototype.accelerationZ = 0; /** * The system variable pAccelerationX always contains the acceleration of the * device along the x axis in the frame previous to the current frame. Value * is represented as meters per second squared. * * @property {Number} pAccelerationX * @readOnly */ p5.prototype.pAccelerationX = 0; /** * The system variable pAccelerationY always contains the acceleration of the * device along the y axis in the frame previous to the current frame. Value * is represented as meters per second squared. * * @property {Number} pAccelerationY * @readOnly */ p5.prototype.pAccelerationY = 0; /** * The system variable pAccelerationZ always contains the acceleration of the * device along the z axis in the frame previous to the current frame. Value * is represented as meters per second squared. * * @property {Number} pAccelerationZ * @readOnly */ p5.prototype.pAccelerationZ = 0; /** * _updatePAccelerations updates the pAcceleration values * * @private */ p5.prototype._updatePAccelerations = function() { this._setProperty('pAccelerationX', this.accelerationX); this._setProperty('pAccelerationY', this.accelerationY); this._setProperty('pAccelerationZ', this.accelerationZ); }; /** * The system variable rotationX always contains the rotation of the * device along the x axis. Value is represented as 0 to +/-180 degrees. *

* Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * //rotateZ(radians(rotationZ)); * rotateX(radians(rotationX)); * //rotateY(radians(rotationY)); * box(200, 200, 200); * } * *
* * @property {Number} rotationX * @readOnly * * @alt * red horizontal line right, green vertical line bottom. black background. * */ p5.prototype.rotationX = 0; /** * The system variable rotationY always contains the rotation of the * device along the y axis. Value is represented as 0 to +/-90 degrees. *

* Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * //rotateZ(radians(rotationZ)); * //rotateX(radians(rotationX)); * rotateY(radians(rotationY)); * box(200, 200, 200); * } * *
* * @property {Number} rotationY * @readOnly * * @alt * red horizontal line right, green vertical line bottom. black background. */ p5.prototype.rotationY = 0; /** * The system variable rotationZ always contains the rotation of the * device along the z axis. Value is represented as 0 to 359 degrees. *

* Unlike rotationX and rotationY, this variable is available for devices * with a built-in compass only. *

* Note: The order the rotations are called is important, ie. if used * together, it must be called in the order Z-X-Y or there might be * unexpected behaviour. * * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateZ(radians(rotationZ)); * //rotateX(radians(rotationX)); * //rotateY(radians(rotationY)); * box(200, 200, 200); * } * *
* * @property {Number} rotationZ * @readOnly * * @alt * red horizontal line right, green vertical line bottom. black background. */ p5.prototype.rotationZ = 0; /** * The system variable pRotationX always contains the rotation of the * device along the x axis in the frame previous to the current frame. Value * is represented as 0 to +/-180 degrees. *

* pRotationX can also be used with rotationX to determine the rotate * direction of the device along the X-axis. * @example *
* * // A simple if statement looking at whether * // rotationX - pRotationX < 0 is true or not will be * // sufficient for determining the rotate direction * // in most cases. * * // Some extra logic is needed to account for cases where * // the angles wrap around. * var rotateDirection = 'clockwise'; * * // Simple range conversion to make things simpler. * // This is not absolutely necessary but the logic * // will be different in that case. * * var rX = rotationX + 180; * var pRX = pRotationX + 180; * * if ((rX - pRX > 0 && rX - pRX < 270) || rX - pRX < -270) { * rotateDirection = 'clockwise'; * } else if (rX - pRX < 0 || rX - pRX > 270) { * rotateDirection = 'counter-clockwise'; * } * * print(rotateDirection); * *
* * @alt * no image to display. * * * @property {Number} pRotationX * @readOnly */ p5.prototype.pRotationX = 0; /** * The system variable pRotationY always contains the rotation of the * device along the y axis in the frame previous to the current frame. Value * is represented as 0 to +/-90 degrees. *

* pRotationY can also be used with rotationY to determine the rotate * direction of the device along the Y-axis. * @example *
* * // A simple if statement looking at whether * // rotationY - pRotationY < 0 is true or not will be * // sufficient for determining the rotate direction * // in most cases. * * // Some extra logic is needed to account for cases where * // the angles wrap around. * var rotateDirection = 'clockwise'; * * // Simple range conversion to make things simpler. * // This is not absolutely necessary but the logic * // will be different in that case. * * var rY = rotationY + 180; * var pRY = pRotationY + 180; * * if ((rY - pRY > 0 && rY - pRY < 270) || rY - pRY < -270) { * rotateDirection = 'clockwise'; * } else if (rY - pRY < 0 || rY - pRY > 270) { * rotateDirection = 'counter-clockwise'; * } * print(rotateDirection); * *
* * @alt * no image to display. * * * @property {Number} pRotationY * @readOnly */ p5.prototype.pRotationY = 0; /** * The system variable pRotationZ always contains the rotation of the * device along the z axis in the frame previous to the current frame. Value * is represented as 0 to 359 degrees. *

* pRotationZ can also be used with rotationZ to determine the rotate * direction of the device along the Z-axis. * @example *
* * // A simple if statement looking at whether * // rotationZ - pRotationZ < 0 is true or not will be * // sufficient for determining the rotate direction * // in most cases. * * // Some extra logic is needed to account for cases where * // the angles wrap around. * var rotateDirection = 'clockwise'; * * if ( * (rotationZ - pRotationZ > 0 && rotationZ - pRotationZ < 270) || * rotationZ - pRotationZ < -270 * ) { * rotateDirection = 'clockwise'; * } else if (rotationZ - pRotationZ < 0 || rotationZ - pRotationZ > 270) { * rotateDirection = 'counter-clockwise'; * } * print(rotateDirection); * *
* * @alt * no image to display. * * * @property {Number} pRotationZ * @readOnly */ p5.prototype.pRotationZ = 0; var startAngleX = 0; var startAngleY = 0; var startAngleZ = 0; var rotateDirectionX = 'clockwise'; var rotateDirectionY = 'clockwise'; var rotateDirectionZ = 'clockwise'; var pRotateDirectionX; var pRotateDirectionY; var pRotateDirectionZ; p5.prototype._updatePRotations = function() { this._setProperty('pRotationX', this.rotationX); this._setProperty('pRotationY', this.rotationY); this._setProperty('pRotationZ', this.rotationZ); }; /** * @property {String} turnAxis * @readOnly */ p5.prototype.turnAxis = undefined; var move_threshold = 0.5; var shake_threshold = 30; /** * The setMoveThreshold() function is used to set the movement threshold for * the deviceMoved() function. The default threshold is set to 0.5. * * @method setMoveThreshold * @param {number} value The threshold value */ p5.prototype.setMoveThreshold = function(val) { p5._validateParameters('setMoveThreshold', arguments); move_threshold = val; }; /** * The setShakeThreshold() function is used to set the movement threshold for * the deviceShaken() function. The default threshold is set to 30. * * @method setShakeThreshold * @param {number} value The threshold value */ p5.prototype.setShakeThreshold = function(val) { p5._validateParameters('setShakeThreshold', arguments); shake_threshold = val; }; /** * The deviceMoved() function is called when the device is moved by more than * the threshold value along X, Y or Z axis. The default threshold is set to * 0.5. * @method deviceMoved * @example *
* * // Run this example on a mobile device * // Move the device around * // to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceMoved() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * *
* * @alt * 50x50 black rect in center of canvas. turns white on mobile when device moves * */ /** * The deviceTurned() function is called when the device rotates by * more than 90 degrees continuously. *

* The axis that triggers the deviceTurned() method is stored in the turnAxis * variable. The deviceTurned() method can be locked to trigger on any axis: * X, Y or Z by comparing the turnAxis variable to 'X', 'Y' or 'Z'. * * @method deviceTurned * @example *
* * // Run this example on a mobile device * // Rotate the device by 90 degrees * // to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceTurned() { * if (value === 0) { * value = 255; * } else if (value === 255) { * value = 0; * } * } * *
*
* * // Run this example on a mobile device * // Rotate the device by 90 degrees in the * // X-axis to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceTurned() { * if (turnAxis === 'X') { * if (value === 0) { * value = 255; * } else if (value === 255) { * value = 0; * } * } * } * *
* * @alt * 50x50 black rect in center of canvas. turns white on mobile when device turns * 50x50 black rect in center of canvas. turns white on mobile when x-axis turns * */ /** * The deviceShaken() function is called when the device total acceleration * changes of accelerationX and accelerationY values is more than * the threshold value. The default threshold is set to 30. * @method deviceShaken * @example *
* * // Run this example on a mobile device * // Shake the device to change the value. * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function deviceShaken() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * *
* * @alt * 50x50 black rect in center of canvas. turns white on mobile when device shakes * */ p5.prototype._ondeviceorientation = function(e) { this._updatePRotations(); this._setProperty('rotationX', e.beta); this._setProperty('rotationY', e.gamma); this._setProperty('rotationZ', e.alpha); this._handleMotion(); }; p5.prototype._ondevicemotion = function(e) { this._updatePAccelerations(); this._setProperty('accelerationX', e.acceleration.x * 2); this._setProperty('accelerationY', e.acceleration.y * 2); this._setProperty('accelerationZ', e.acceleration.z * 2); this._handleMotion(); }; p5.prototype._handleMotion = function() { if (window.orientation === 90 || window.orientation === -90) { this._setProperty('deviceOrientation', 'landscape'); } else if (window.orientation === 0) { this._setProperty('deviceOrientation', 'portrait'); } else if (window.orientation === undefined) { this._setProperty('deviceOrientation', 'undefined'); } var deviceMoved = this.deviceMoved || window.deviceMoved; if (typeof deviceMoved === 'function') { if ( Math.abs(this.accelerationX - this.pAccelerationX) > move_threshold || Math.abs(this.accelerationY - this.pAccelerationY) > move_threshold || Math.abs(this.accelerationZ - this.pAccelerationZ) > move_threshold ) { deviceMoved(); } } var deviceTurned = this.deviceTurned || window.deviceTurned; if (typeof deviceTurned === 'function') { // The angles given by rotationX etc is from range -180 to 180. // The following will convert them to 0 to 360 for ease of calculation // of cases when the angles wrapped around. // _startAngleX will be converted back at the end and updated. var wRX = this.rotationX + 180; var wPRX = this.pRotationX + 180; var wSAX = startAngleX + 180; if ((wRX - wPRX > 0 && wRX - wPRX < 270) || wRX - wPRX < -270) { rotateDirectionX = 'clockwise'; } else if (wRX - wPRX < 0 || wRX - wPRX > 270) { rotateDirectionX = 'counter-clockwise'; } if (rotateDirectionX !== pRotateDirectionX) { wSAX = wRX; } if (Math.abs(wRX - wSAX) > 90 && Math.abs(wRX - wSAX) < 270) { wSAX = wRX; this._setProperty('turnAxis', 'X'); deviceTurned(); } pRotateDirectionX = rotateDirectionX; startAngleX = wSAX - 180; // Y-axis is identical to X-axis except for changing some names. var wRY = this.rotationY + 180; var wPRY = this.pRotationY + 180; var wSAY = startAngleY + 180; if ((wRY - wPRY > 0 && wRY - wPRY < 270) || wRY - wPRY < -270) { rotateDirectionY = 'clockwise'; } else if (wRY - wPRY < 0 || wRY - this.pRotationY > 270) { rotateDirectionY = 'counter-clockwise'; } if (rotateDirectionY !== pRotateDirectionY) { wSAY = wRY; } if (Math.abs(wRY - wSAY) > 90 && Math.abs(wRY - wSAY) < 270) { wSAY = wRY; this._setProperty('turnAxis', 'Y'); deviceTurned(); } pRotateDirectionY = rotateDirectionY; startAngleY = wSAY - 180; // Z-axis is already in the range 0 to 360 // so no conversion is needed. if ( (this.rotationZ - this.pRotationZ > 0 && this.rotationZ - this.pRotationZ < 270) || this.rotationZ - this.pRotationZ < -270 ) { rotateDirectionZ = 'clockwise'; } else if ( this.rotationZ - this.pRotationZ < 0 || this.rotationZ - this.pRotationZ > 270 ) { rotateDirectionZ = 'counter-clockwise'; } if (rotateDirectionZ !== pRotateDirectionZ) { startAngleZ = this.rotationZ; } if ( Math.abs(this.rotationZ - startAngleZ) > 90 && Math.abs(this.rotationZ - startAngleZ) < 270 ) { startAngleZ = this.rotationZ; this._setProperty('turnAxis', 'Z'); deviceTurned(); } pRotateDirectionZ = rotateDirectionZ; this._setProperty('turnAxis', undefined); } var deviceShaken = this.deviceShaken || window.deviceShaken; if (typeof deviceShaken === 'function') { var accelerationChangeX; var accelerationChangeY; // Add accelerationChangeZ if acceleration change on Z is needed if (this.pAccelerationX !== null) { accelerationChangeX = Math.abs(this.accelerationX - this.pAccelerationX); accelerationChangeY = Math.abs(this.accelerationY - this.pAccelerationY); } if (accelerationChangeX + accelerationChangeY > shake_threshold) { deviceShaken(); } } }; module.exports = p5; },{"../core/core":22}],38:[function(_dereq_,module,exports){ /** * @module Events * @submodule Keyboard * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Holds the key codes of currently pressed keys. * @private */ var downKeys = {}; /** * The boolean system variable keyIsPressed is true if any key is pressed * and false if no keys are pressed. * * @property {Boolean} keyIsPressed * @readOnly * @example *
* * function draw() { * if (keyIsPressed === true) { * fill(0); * } else { * fill(255); * } * rect(25, 25, 50, 50); * } * *
* * @alt * 50x50 white rect that turns black on keypress. * */ p5.prototype.isKeyPressed = false; p5.prototype.keyIsPressed = false; // khan /** * The system variable key always contains the value of the most recent * key on the keyboard that was typed. To get the proper capitalization, it * is best to use it within keyTyped(). For non-ASCII keys, use the keyCode * variable. * * @property {String} key * @readOnly * @example *
* // Click any key to display it! * // (Not Guaranteed to be Case Sensitive) * function setup() { * fill(245, 123, 158); * textSize(50); * } * * function draw() { * background(200); * text(key, 33, 65); // Display last key pressed. * } *
* * @alt * canvas displays any key value that is pressed in pink font. * */ p5.prototype.key = ''; /** * The variable keyCode is used to detect special keys such as BACKSPACE, * DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, OPTION, ALT, UP_ARROW, * DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW. * You can also check for custom keys by looking up the keyCode of any key * on a site like this: keycode.info. * * @property {Integer} keyCode * @readOnly * @example *
* var fillVal = 126; * function draw() { * fill(fillVal); * rect(25, 25, 50, 50); * } * * function keyPressed() { * if (keyCode === UP_ARROW) { * fillVal = 255; * } else if (keyCode === DOWN_ARROW) { * fillVal = 0; * } * return false; // prevent default * } *
* * @alt * Grey rect center. turns white when up arrow pressed and black when down * */ p5.prototype.keyCode = 0; /** * The keyPressed() function is called once every time a key is pressed. The * keyCode for the key that was pressed is stored in the keyCode variable. *

* For non-ASCII keys, use the keyCode variable. You can check if the keyCode * equals BACKSPACE, DELETE, ENTER, RETURN, TAB, ESCAPE, SHIFT, CONTROL, * OPTION, ALT, UP_ARROW, DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW. *

* For ASCII keys that was pressed is stored in the key variable. However, it * does not distinguish between uppercase and lowercase. For this reason, it * is recommended to use keyTyped() to read the key variable, in which the * case of the variable will be distinguished. *

* Because of how operating systems handle key repeats, holding down a key * may cause multiple calls to keyTyped() (and keyReleased() as well). The * rate of repeat is set by the operating system and how each computer is * configured.

* Browsers may have different default * behaviors attached to various key events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method keyPressed * @example *
* * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyPressed() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
*
* * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyPressed() { * if (keyCode === LEFT_ARROW) { * value = 255; * } else if (keyCode === RIGHT_ARROW) { * value = 0; * } * } * *
*
* * function keyPressed() { * // Do something * return false; // prevent any default behaviour * } * *
* * @alt * black rect center. turns white when key pressed and black when released * black rect center. turns white when left arrow pressed and black when right. * */ p5.prototype._onkeydown = function(e) { if (downKeys[e.which]) { // prevent multiple firings return; } this._setProperty('isKeyPressed', true); this._setProperty('keyIsPressed', true); this._setProperty('keyCode', e.which); downKeys[e.which] = true; var key = String.fromCharCode(e.which); if (!key) { key = e.which; } this._setProperty('key', key); var keyPressed = this.keyPressed || window.keyPressed; if (typeof keyPressed === 'function' && !e.charCode) { var executeDefault = keyPressed(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The keyReleased() function is called once every time a key is released. * See key and keyCode for more information.

* Browsers may have different default * behaviors attached to various key events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method keyReleased * @example *
* * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyReleased() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * return false; // prevent any default behavior * } * *
* * @alt * black rect center. turns white when key pressed and black when pressed again * */ p5.prototype._onkeyup = function(e) { var keyReleased = this.keyReleased || window.keyReleased; downKeys[e.which] = false; if (!areDownKeys()) { this._setProperty('isKeyPressed', false); this._setProperty('keyIsPressed', false); } this._setProperty('_lastKeyCodeTyped', null); var key = String.fromCharCode(e.which); if (!key) { key = e.which; } this._setProperty('key', key); this._setProperty('keyCode', e.which); if (typeof keyReleased === 'function') { var executeDefault = keyReleased(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The keyTyped() function is called once every time a key is pressed, but * action keys such as Ctrl, Shift, and Alt are ignored. The most recent * key pressed will be stored in the key variable. *

* Because of how operating systems handle key repeats, holding down a key * will cause multiple calls to keyTyped() (and keyReleased() as well). The * rate of repeat is set by the operating system and how each computer is * configured.

* Browsers may have different default behaviors attached to various key * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method keyTyped * @example *
* * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function keyTyped() { * if (key === 'a') { * value = 255; * } else if (key === 'b') { * value = 0; * } * // uncomment to prevent any default behavior * // return false; * } * *
* * @alt * black rect center. turns white when 'a' key typed and black when 'b' pressed * */ p5.prototype._onkeypress = function(e) { if (e.which === this._lastKeyCodeTyped) { // prevent multiple firings return; } this._setProperty('keyCode', e.which); this._setProperty('_lastKeyCodeTyped', e.which); // track last keyCode this._setProperty('key', String.fromCharCode(e.which)); var keyTyped = this.keyTyped || window.keyTyped; if (typeof keyTyped === 'function') { var executeDefault = keyTyped(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The onblur function is called when the user is no longer focused * on the p5 element. Because the keyup events will not fire if the user is * not focused on the element we must assume all keys currently down have * been released. */ p5.prototype._onblur = function(e) { downKeys = {}; }; /** * The keyIsDown() function checks if the key is currently down, i.e. pressed. * It can be used if you have an object that moves, and you want several keys * to be able to affect its behaviour simultaneously, such as moving a * sprite diagonally. You can put in any number representing the keyCode of * the key, or use any of the variable keyCode names listed * here. * * @method keyIsDown * @param {Number} code The key to check for. * @return {Boolean} whether key is down or not * @example *
* var x = 100; * var y = 100; * * function setup() { * createCanvas(512, 512); * } * * function draw() { * if (keyIsDown(LEFT_ARROW)) { * x -= 5; * } * * if (keyIsDown(RIGHT_ARROW)) { * x += 5; * } * * if (keyIsDown(UP_ARROW)) { * y -= 5; * } * * if (keyIsDown(DOWN_ARROW)) { * y += 5; * } * * clear(); * fill(255, 0, 0); * ellipse(x, y, 50, 50); * } *
* * @alt * 50x50 red ellipse moves left, right, up and down with arrow presses. * */ p5.prototype.keyIsDown = function(code) { p5._validateParameters('keyIsDown', arguments); return downKeys[code]; }; /** * The checkDownKeys function returns a boolean true if any keys pressed * and a false if no keys are currently pressed. * Helps avoid instances where a multiple keys are pressed simultaneously and * releasing a single key will then switch the * keyIsPressed property to true. * @private **/ function areDownKeys() { for (var key in downKeys) { if (downKeys.hasOwnProperty(key) && downKeys[key] === true) { return true; } } return false; } module.exports = p5; },{"../core/core":22}],39:[function(_dereq_,module,exports){ /** * @module Events * @submodule Mouse * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); /* * This is a flag which is false until the first time * we receive a mouse event. The pmouseX and pmouseY * values will match the mouseX and mouseY values until * this interaction takes place. */ p5.prototype._hasMouseInteracted = false; /** * The system variable mouseX always contains the current horizontal * position of the mouse, relative to (0, 0) of the canvas. If touch is * used instead of mouse input, mouseX will hold the x value of the most * recent touch point. * * @property {Number} mouseX * @readOnly * * @example *
* * // Move the mouse across the canvas * function draw() { * background(244, 248, 252); * line(mouseX, 0, mouseX, 100); * } * *
* * @alt * horizontal black line moves left and right with mouse x-position * */ p5.prototype.mouseX = 0; /** * The system variable mouseY always contains the current vertical position * of the mouse, relative to (0, 0) of the canvas. If touch is * used instead of mouse input, mouseY will hold the y value of the most * recent touch point. * * @property {Number} mouseY * @readOnly * * @example *
* * // Move the mouse across the canvas * function draw() { * background(244, 248, 252); * line(0, mouseY, 100, mouseY); * } * *
* * @alt * vertical black line moves up and down with mouse y-position * */ p5.prototype.mouseY = 0; /** * The system variable pmouseX always contains the horizontal position of * the mouse or finger in the frame previous to the current frame, relative to * (0, 0) of the canvas. * * @property {Number} pmouseX * @readOnly * * @example *
* * // Move the mouse across the canvas to leave a trail * function setup() { * //slow down the frameRate to make it more visible * frameRate(10); * } * * function draw() { * background(244, 248, 252); * line(mouseX, mouseY, pmouseX, pmouseY); * print(pmouseX + ' -> ' + mouseX); * } * *
* * @alt * line trail is created from cursor movements. faster movement make longer line. * */ p5.prototype.pmouseX = 0; /** * The system variable pmouseY always contains the vertical position of the * mouse or finger in the frame previous to the current frame, relative to * (0, 0) of the canvas. * * @property {Number} pmouseY * @readOnly * * @example *
* * function draw() { * background(237, 34, 93); * fill(0); * //draw a square only if the mouse is not moving * if (mouseY === pmouseY && mouseX === pmouseX) { * rect(20, 20, 60, 60); * } * * print(pmouseY + ' -> ' + mouseY); * } * *
* * @alt * 60x60 black rect center, fuschia background. rect flickers on mouse movement * */ p5.prototype.pmouseY = 0; /** * The system variable winMouseX always contains the current horizontal * position of the mouse, relative to (0, 0) of the window. * * @property {Number} winMouseX * @readOnly * * @example *
* * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * } * * function draw() { * background(237, 34, 93); * fill(0); * * //move the canvas to the horizontal mouse position * //rela tive to the window * myCanvas.position(winMouseX + 1, windowHeight / 2); * * //the y of the square is relative to the canvas * rect(20, mouseY, 60, 60); * } * *
* * @alt * 60x60 black rect y moves with mouse y and fuschia canvas moves with mouse x * */ p5.prototype.winMouseX = 0; /** * The system variable winMouseY always contains the current vertical * position of the mouse, relative to (0, 0) of the window. * * @property {Number} winMouseY * @readOnly * * @example *
* * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * } * * function draw() { * background(237, 34, 93); * fill(0); * * //move the canvas to the vertical mouse position * //rel ative to the window * myCanvas.position(windowWidth / 2, winMouseY + 1); * * //the x of the square is relative to the canvas * rect(mouseX, 20, 60, 60); * } * *
* * @alt * 60x60 black rect x moves with mouse x and fuschia canvas y moves with mouse y * */ p5.prototype.winMouseY = 0; /** * The system variable pwinMouseX always contains the horizontal position * of the mouse in the frame previous to the current frame, relative to * (0, 0) of the window. * * @property {Number} pwinMouseX * @readOnly * * @example *
* * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * noStroke(); * fill(237, 34, 93); * } * * function draw() { * clear(); * //the difference between previous and * //current x position is the horizontal mouse speed * var speed = abs(winMouseX - pwinMouseX); * //change the size of the circle * //according to the horizontal speed * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5); * //move the canvas to the mouse position * myCanvas.position(winMouseX + 1, winMouseY + 1); * } * *
* * @alt * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed * */ p5.prototype.pwinMouseX = 0; /** * The system variable pwinMouseY always contains the vertical position of * the mouse in the frame previous to the current frame, relative to (0, 0) * of the window. * * @property {Number} pwinMouseY * @readOnly * * * @example *
* * var myCanvas; * * function setup() { * //use a variable to store a pointer to the canvas * myCanvas = createCanvas(100, 100); * noStroke(); * fill(237, 34, 93); * } * * function draw() { * clear(); * //the difference between previous and * //current y position is the vertical mouse speed * var speed = abs(winMouseY - pwinMouseY); * //change the size of the circle * //according to the vertical speed * ellipse(50, 50, 10 + speed * 5, 10 + speed * 5); * //move the canvas to the mouse position * myCanvas.position(winMouseX + 1, winMouseY + 1); * } * *
* * @alt * fuschia ellipse moves with mouse x and y. Grows and shrinks with mouse speed * */ p5.prototype.pwinMouseY = 0; /** * Processing automatically tracks if the mouse button is pressed and which * button is pressed. The value of the system variable mouseButton is either * LEFT, RIGHT, or CENTER depending on which button was pressed last. * Warning: different browsers may track mouseButton differently. * * @property {Constant} mouseButton * @readOnly * * @example *
* * function draw() { * background(237, 34, 93); * fill(0); * * if (mouseIsPressed) { * if (mouseButton === LEFT) { * ellipse(50, 50, 50, 50); * } * if (mouseButton === RIGHT) { * rect(25, 25, 50, 50); * } * if (mouseButton === CENTER) { * triangle(23, 75, 50, 20, 78, 75); * } * } * * print(mouseButton); * } * *
* * @alt * 50x50 black ellipse appears on center of fuschia canvas on mouse click/press. * */ p5.prototype.mouseButton = 0; /** * The boolean system variable mouseIsPressed is true if the mouse is pressed * and false if not. * * @property {Boolean} mouseIsPressed * @readOnly * * @example *
* * function draw() { * background(237, 34, 93); * fill(0); * * if (mouseIsPressed) { * ellipse(50, 50, 50, 50); * } else { * rect(25, 25, 50, 50); * } * * print(mouseIsPressed); * } * *
* * @alt * black 50x50 rect becomes ellipse with mouse click/press. fuschia background. * */ p5.prototype.mouseIsPressed = false; p5.prototype._updateNextMouseCoords = function(e) { if (this._curElement !== null && (!e.touches || e.touches.length > 0)) { var mousePos = getMousePos( this._curElement.elt, this.width, this.height, e ); this._setProperty('mouseX', mousePos.x); this._setProperty('mouseY', mousePos.y); this._setProperty('winMouseX', mousePos.winX); this._setProperty('winMouseY', mousePos.winY); } if (!this._hasMouseInteracted) { // For first draw, make previous and next equal this._updateMouseCoords(); this._setProperty('_hasMouseInteracted', true); } }; p5.prototype._updateMouseCoords = function() { this._setProperty('pmouseX', this.mouseX); this._setProperty('pmouseY', this.mouseY); this._setProperty('pwinMouseX', this.winMouseX); this._setProperty('pwinMouseY', this.winMouseY); }; function getMousePos(canvas, w, h, evt) { if (evt && !evt.clientX) { // use touches if touch and not mouse if (evt.touches) { evt = evt.touches[0]; } else if (evt.changedTouches) { evt = evt.changedTouches[0]; } } var rect = canvas.getBoundingClientRect(); var sx = canvas.scrollWidth / w; var sy = canvas.scrollHeight / h; return { x: (evt.clientX - rect.left) / sx, y: (evt.clientY - rect.top) / sy, winX: evt.clientX, winY: evt.clientY, id: evt.identifier }; } p5.prototype._setMouseButton = function(e) { if (e.button === 1) { this._setProperty('mouseButton', constants.CENTER); } else if (e.button === 2) { this._setProperty('mouseButton', constants.RIGHT); } else { this._setProperty('mouseButton', constants.LEFT); } }; /** * The mouseMoved() function is called every time the mouse moves and a mouse * button is not pressed.

* Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mouseMoved * @example *
* * // Move the mouse across the page * // to change its value * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mouseMoved() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * *
* *
* * function mouseMoved() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * black 50x50 rect becomes lighter with mouse movements until white then resets * no image displayed * */ /** * The mouseDragged() function is called once every time the mouse moves and * a mouse button is pressed. If no mouseDragged() function is defined, the * touchMoved() function will be called instead if it is defined.

* Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mouseDragged * @example *
* * // Drag the mouse across the page * // to change its value * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mouseDragged() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * *
* *
* * function mouseDragged() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * black 50x50 rect turns lighter with mouse click and drag until white, resets * no image displayed * */ p5.prototype._onmousemove = function(e) { var context = this._isGlobal ? window : this; var executeDefault; this._updateNextMouseCoords(e); if (!this.mouseIsPressed) { if (typeof context.mouseMoved === 'function') { executeDefault = context.mouseMoved(e); if (executeDefault === false) { e.preventDefault(); } } } else { if (typeof context.mouseDragged === 'function') { executeDefault = context.mouseDragged(e); if (executeDefault === false) { e.preventDefault(); } } else if (typeof context.touchMoved === 'function') { executeDefault = context.touchMoved(e); if (executeDefault === false) { e.preventDefault(); } } } }; /** * The mousePressed() function is called once after every time a mouse button * is pressed. The mouseButton variable (see the related reference entry) * can be used to determine which button has been pressed. If no * mousePressed() function is defined, the touchStarted() function will be * called instead if it is defined.

* Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mousePressed * @example *
* * // Click within the image to change * // the value of the rectangle * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mousePressed() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
* *
* * function mousePressed() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed * */ p5.prototype._onmousedown = function(e) { var context = this._isGlobal ? window : this; var executeDefault; this._setProperty('mouseIsPressed', true); this._setMouseButton(e); this._updateNextMouseCoords(e); if (typeof context.mousePressed === 'function') { executeDefault = context.mousePressed(e); if (executeDefault === false) { e.preventDefault(); } } else if (typeof context.touchStarted === 'function') { executeDefault = context.touchStarted(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The mouseReleased() function is called every time a mouse button is * released. If no mouseReleased() function is defined, the touchEnded() * function will be called instead if it is defined.

* Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * * @method mouseReleased * @example *
* * // Click within the image to change * // the value of the rectangle * // after the mouse has been clicked * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function mouseReleased() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
* *
* * function mouseReleased() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed * */ p5.prototype._onmouseup = function(e) { var context = this._isGlobal ? window : this; var executeDefault; this._setProperty('mouseIsPressed', false); if (typeof context.mouseReleased === 'function') { executeDefault = context.mouseReleased(e); if (executeDefault === false) { e.preventDefault(); } } else if (typeof context.touchEnded === 'function') { executeDefault = context.touchEnded(e); if (executeDefault === false) { e.preventDefault(); } } }; p5.prototype._ondragend = p5.prototype._onmouseup; p5.prototype._ondragover = p5.prototype._onmousemove; /** * The mouseClicked() function is called once after a mouse button has been * pressed and then released.

* Browsers handle clicks differently, so this function is only guaranteed to be * run when the left mouse button is clicked. To handle other mouse buttons * being pressed or released, see mousePressed() or mouseReleased().

* Browsers may have different default * behaviors attached to various mouse events. To prevent any default * behavior for this event, add "return false" to the end of the method. * * @method mouseClicked * @example *
* * // Click within the image to change * // the value of the rectangle * // after the mouse has been clicked * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * * function mouseClicked() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
* *
* * function mouseClicked() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * black 50x50 rect turns white with mouse click/press. * no image displayed * */ p5.prototype._onclick = function(e) { var context = this._isGlobal ? window : this; if (typeof context.mouseClicked === 'function') { var executeDefault = context.mouseClicked(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The doubleClicked() function is executed every time a event * listener has detected a dblclick event which is a part of the * DOM L3 specification. The doubleClicked event is fired when a * pointing device button (usually a mouse's primary button) * is clicked twice on a single element. For more info on the * dblclick event refer to mozilla's documentation here: * https://developer.mozilla.org/en-US/docs/Web/Events/dblclick * * @method doubleClicked * @example *
* * // Click within the image to change * // the value of the rectangle * // after the mouse has been double clicked * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * * function doubleClicked() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
* *
* * function doubleClicked() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * black 50x50 rect turns white with mouse doubleClick/press. * no image displayed */ p5.prototype._ondblclick = function(e) { var context = this._isGlobal ? window : this; if (typeof context.doubleClicked === 'function') { var executeDefault = context.doubleClicked(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The function mouseWheel() is executed every time a vertical mouse wheel * event is detected either triggered by an actual mouse wheel or by a * touchpad.

* The event.delta property returns the amount the mouse wheel * have scrolled. The values can be positive or negative depending on the * scroll direction (on OS X with "natural" scrolling enabled, the signs * are inverted).

* Browsers may have different default behaviors attached to various * mouse events. To prevent any default behavior for this event, add * "return false" to the end of the method.

* Due to the current support of the "wheel" event on Safari, the function * may only work as expected if "return false" is included while using Safari. * * @method mouseWheel * * @example *
* * var pos = 25; * * function draw() { * background(237, 34, 93); * fill(0); * rect(25, pos, 50, 50); * } * * function mouseWheel(event) { * print(event.delta); * //move the square according to the vertical scroll amount * pos += event.delta; * //uncomment to block page scrolling * //return false; * } * *
* * @alt * black 50x50 rect moves up and down with vertical scroll. fuschia background * */ p5.prototype._onwheel = function(e) { var context = this._isGlobal ? window : this; if (typeof context.mouseWheel === 'function') { e.delta = e.deltaY; var executeDefault = context.mouseWheel(e); if (executeDefault === false) { e.preventDefault(); } } }; module.exports = p5; },{"../core/constants":21,"../core/core":22}],40:[function(_dereq_,module,exports){ /** * @module Events * @submodule Touch * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * The system variable touches[] contains an array of the positions of all * current touch points, relative to (0, 0) of the canvas, and IDs identifying a * unique touch as it moves. Each element in the array is an object with x, y, * and id properties. * * The touches[] array is not supported on Safari and IE on touch-based * desktops (laptops). * * @property {Object[]} touches * @readOnly */ p5.prototype.touches = []; p5.prototype._updateTouchCoords = function(e) { if (this._curElement !== null) { var touches = []; for (var i = 0; i < e.touches.length; i++) { touches[i] = getTouchInfo( this._curElement.elt, this.width, this.height, e, i ); } this._setProperty('touches', touches); } }; function getTouchInfo(canvas, w, h, e, i) { i = i || 0; var rect = canvas.getBoundingClientRect(); var sx = canvas.scrollWidth / w; var sy = canvas.scrollHeight / h; var touch = e.touches[i] || e.changedTouches[i]; return { x: (touch.clientX - rect.left) / sx, y: (touch.clientY - rect.top) / sy, winX: touch.clientX, winY: touch.clientY, id: touch.identifier }; } /** * The touchStarted() function is called once after every time a touch is * registered. If no touchStarted() function is defined, the mousePressed() * function will be called instead if it is defined.

* Browsers may have different default behaviors attached to various touch * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method touchStarted * @example *
* * // Touch within the image to change * // the value of the rectangle * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function touchStarted() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
* *
* * function touchStarted() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * 50x50 black rect turns white with touch event. * no image displayed */ p5.prototype._ontouchstart = function(e) { var context = this._isGlobal ? window : this; var executeDefault; this._setProperty('mouseIsPressed', true); this._updateTouchCoords(e); this._updateNextMouseCoords(e); if (typeof context.touchStarted === 'function') { executeDefault = context.touchStarted(e); if (executeDefault === false) { e.preventDefault(); } } else if (typeof context.mousePressed === 'function') { executeDefault = context.mousePressed(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The touchMoved() function is called every time a touch move is registered. * If no touchMoved() function is defined, the mouseDragged() function will * be called instead if it is defined.

* Browsers may have different default behaviors attached to various touch * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method touchMoved * @example *
* * // Move your finger across the page * // to change its value * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function touchMoved() { * value = value + 5; * if (value > 255) { * value = 0; * } * } * *
* *
* * function touchMoved() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * 50x50 black rect turns lighter with touch until white. resets * no image displayed * */ p5.prototype._ontouchmove = function(e) { var context = this._isGlobal ? window : this; var executeDefault; this._updateTouchCoords(e); this._updateNextMouseCoords(e); if (typeof context.touchMoved === 'function') { executeDefault = context.touchMoved(e); if (executeDefault === false) { e.preventDefault(); } } else if (typeof context.mouseDragged === 'function') { executeDefault = context.mouseDragged(e); if (executeDefault === false) { e.preventDefault(); } } }; /** * The touchEnded() function is called every time a touch ends. If no * touchEnded() function is defined, the mouseReleased() function will be * called instead if it is defined.

* Browsers may have different default behaviors attached to various touch * events. To prevent any default behavior for this event, add "return false" * to the end of the method. * * @method touchEnded * @example *
* * // Release touch within the image to * // change the value of the rectangle * * var value = 0; * function draw() { * fill(value); * rect(25, 25, 50, 50); * } * function touchEnded() { * if (value === 0) { * value = 255; * } else { * value = 0; * } * } * *
* *
* * function touchEnded() { * ellipse(mouseX, mouseY, 5, 5); * // prevent default * return false; * } * *
* * @alt * 50x50 black rect turns white with touch. * no image displayed * */ p5.prototype._ontouchend = function(e) { this._setProperty('mouseIsPressed', false); this._updateTouchCoords(e); this._updateNextMouseCoords(e); var context = this._isGlobal ? window : this; var executeDefault; if (typeof context.touchEnded === 'function') { executeDefault = context.touchEnded(e); if (executeDefault === false) { e.preventDefault(); } } else if (typeof context.mouseReleased === 'function') { executeDefault = context.mouseReleased(e); if (executeDefault === false) { e.preventDefault(); } } }; module.exports = p5; },{"../core/core":22}],41:[function(_dereq_,module,exports){ /*global ImageData:false */ /** * This module defines the filters for use with image buffers. * * This module is basically a collection of functions stored in an object * as opposed to modules. The functions are destructive, modifying * the passed in canvas rather than creating a copy. * * Generally speaking users of this module will use the Filters.apply method * on a canvas to create an effect. * * A number of functions are borrowed/adapted from * http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * or the java processing implementation. */ 'use strict'; var Filters = {}; /* * Helper functions */ /** * Returns the pixel buffer for a canvas * * @private * * @param {Canvas|ImageData} canvas the canvas to get pixels from * @return {Uint8ClampedArray} a one-dimensional array containing * the data in thc RGBA order, with integer * values between 0 and 255 */ Filters._toPixels = function(canvas) { if (canvas instanceof ImageData) { return canvas.data; } else { return canvas .getContext('2d') .getImageData(0, 0, canvas.width, canvas.height).data; } }; /** * Returns a 32 bit number containing ARGB data at ith pixel in the * 1D array containing pixels data. * * @private * * @param {Uint8ClampedArray} data array returned by _toPixels() * @param {Integer} i index of a 1D Image Array * @return {Integer} 32 bit integer value representing * ARGB value. */ Filters._getARGB = function(data, i) { var offset = i * 4; return ( ((data[offset + 3] << 24) & 0xff000000) | ((data[offset] << 16) & 0x00ff0000) | ((data[offset + 1] << 8) & 0x0000ff00) | (data[offset + 2] & 0x000000ff) ); }; /** * Modifies pixels RGBA values to values contained in the data object. * * @private * * @param {Uint8ClampedArray} pixels array returned by _toPixels() * @param {Int32Array} data source 1D array where each value * represents ARGB values */ Filters._setPixels = function(pixels, data) { var offset = 0; for (var i = 0, al = pixels.length; i < al; i++) { offset = i * 4; pixels[offset + 0] = (data[i] & 0x00ff0000) >>> 16; pixels[offset + 1] = (data[i] & 0x0000ff00) >>> 8; pixels[offset + 2] = data[i] & 0x000000ff; pixels[offset + 3] = (data[i] & 0xff000000) >>> 24; } }; /** * Returns the ImageData object for a canvas * https://developer.mozilla.org/en-US/docs/Web/API/ImageData * * @private * * @param {Canvas|ImageData} canvas canvas to get image data from * @return {ImageData} Holder of pixel data (and width and * height) for a canvas */ Filters._toImageData = function(canvas) { if (canvas instanceof ImageData) { return canvas; } else { return canvas .getContext('2d') .getImageData(0, 0, canvas.width, canvas.height); } }; /** * Returns a blank ImageData object. * * @private * * @param {Integer} width * @param {Integer} height * @return {ImageData} */ Filters._createImageData = function(width, height) { Filters._tmpCanvas = document.createElement('canvas'); Filters._tmpCtx = Filters._tmpCanvas.getContext('2d'); return this._tmpCtx.createImageData(width, height); }; /** * Applys a filter function to a canvas. * * The difference between this and the actual filter functions defined below * is that the filter functions generally modify the pixel buffer but do * not actually put that data back to the canvas (where it would actually * update what is visible). By contrast this method does make the changes * actually visible in the canvas. * * The apply method is the method that callers of this module would generally * use. It has been separated from the actual filters to support an advanced * use case of creating a filter chain that executes without actually updating * the canvas in between everystep. * * @private * @param {HTMLCanvasElement} canvas [description] * @param {function(ImageData,Object)} func [description] * @param {Object} filterParam [description] */ Filters.apply = function(canvas, func, filterParam) { var ctx = canvas.getContext('2d'); var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); //Filters can either return a new ImageData object, or just modify //the one they received. var newImageData = func(imageData, filterParam); if (newImageData instanceof ImageData) { ctx.putImageData(newImageData, 0, 0, 0, 0, canvas.width, canvas.height); } else { ctx.putImageData(imageData, 0, 0, 0, 0, canvas.width, canvas.height); } }; /* * Filters */ /** * Converts the image to black and white pixels depending if they are above or * below the threshold defined by the level parameter. The parameter must be * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. * * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * * @private * @param {Canvas} canvas * @param {Float} level */ Filters.threshold = function(canvas, level) { var pixels = Filters._toPixels(canvas); if (level === undefined) { level = 0.5; } var thresh = Math.floor(level * 255); for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; var val; if (gray >= thresh) { val = 255; } else { val = 0; } pixels[i] = pixels[i + 1] = pixels[i + 2] = val; } }; /** * Converts any colors in the image to grayscale equivalents. * No parameter is used. * * Borrowed from http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ * * @private * @param {Canvas} canvas */ Filters.gray = function(canvas) { var pixels = Filters._toPixels(canvas); for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; // CIE luminance for RGB var gray = 0.2126 * r + 0.7152 * g + 0.0722 * b; pixels[i] = pixels[i + 1] = pixels[i + 2] = gray; } }; /** * Sets the alpha channel to entirely opaque. No parameter is used. * * @private * @param {Canvas} canvas */ Filters.opaque = function(canvas) { var pixels = Filters._toPixels(canvas); for (var i = 0; i < pixels.length; i += 4) { pixels[i + 3] = 255; } return pixels; }; /** * Sets each pixel to its inverse value. No parameter is used. * @private * @param {Canvas} canvas */ Filters.invert = function(canvas) { var pixels = Filters._toPixels(canvas); for (var i = 0; i < pixels.length; i += 4) { pixels[i] = 255 - pixels[i]; pixels[i + 1] = 255 - pixels[i + 1]; pixels[i + 2] = 255 - pixels[i + 2]; } }; /** * Limits each channel of the image to the number of colors specified as * the parameter. The parameter can be set to values between 2 and 255, but * results are most noticeable in the lower ranges. * * Adapted from java based processing implementation * * @private * @param {Canvas} canvas * @param {Integer} level */ Filters.posterize = function(canvas, level) { var pixels = Filters._toPixels(canvas); if (level < 2 || level > 255) { throw new Error( 'Level must be greater than 2 and less than 255 for posterize' ); } var levels1 = level - 1; for (var i = 0; i < pixels.length; i += 4) { var rlevel = pixels[i]; var glevel = pixels[i + 1]; var blevel = pixels[i + 2]; pixels[i] = ((rlevel * level) >> 8) * 255 / levels1; pixels[i + 1] = ((glevel * level) >> 8) * 255 / levels1; pixels[i + 2] = ((blevel * level) >> 8) * 255 / levels1; } }; /** * reduces the bright areas in an image * @private * @param {Canvas} canvas * */ Filters.dilate = function(canvas) { var pixels = Filters._toPixels(canvas); var currIdx = 0; var maxIdx = pixels.length ? pixels.length / 4 : 0; var out = new Int32Array(maxIdx); var currRowIdx, maxRowIdx, colOrig, colOut, currLum; var idxRight, idxLeft, idxUp, idxDown; var colRight, colLeft, colUp, colDown; var lumRight, lumLeft, lumUp, lumDown; while (currIdx < maxIdx) { currRowIdx = currIdx; maxRowIdx = currIdx + canvas.width; while (currIdx < maxRowIdx) { colOrig = colOut = Filters._getARGB(pixels, currIdx); idxLeft = currIdx - 1; idxRight = currIdx + 1; idxUp = currIdx - canvas.width; idxDown = currIdx + canvas.width; if (idxLeft < currRowIdx) { idxLeft = currIdx; } if (idxRight >= maxRowIdx) { idxRight = currIdx; } if (idxUp < 0) { idxUp = 0; } if (idxDown >= maxIdx) { idxDown = currIdx; } colUp = Filters._getARGB(pixels, idxUp); colLeft = Filters._getARGB(pixels, idxLeft); colDown = Filters._getARGB(pixels, idxDown); colRight = Filters._getARGB(pixels, idxRight); //compute luminance currLum = 77 * ((colOrig >> 16) & 0xff) + 151 * ((colOrig >> 8) & 0xff) + 28 * (colOrig & 0xff); lumLeft = 77 * ((colLeft >> 16) & 0xff) + 151 * ((colLeft >> 8) & 0xff) + 28 * (colLeft & 0xff); lumRight = 77 * ((colRight >> 16) & 0xff) + 151 * ((colRight >> 8) & 0xff) + 28 * (colRight & 0xff); lumUp = 77 * ((colUp >> 16) & 0xff) + 151 * ((colUp >> 8) & 0xff) + 28 * (colUp & 0xff); lumDown = 77 * ((colDown >> 16) & 0xff) + 151 * ((colDown >> 8) & 0xff) + 28 * (colDown & 0xff); if (lumLeft > currLum) { colOut = colLeft; currLum = lumLeft; } if (lumRight > currLum) { colOut = colRight; currLum = lumRight; } if (lumUp > currLum) { colOut = colUp; currLum = lumUp; } if (lumDown > currLum) { colOut = colDown; currLum = lumDown; } out[currIdx++] = colOut; } } Filters._setPixels(pixels, out); }; /** * increases the bright areas in an image * @private * @param {Canvas} canvas * */ Filters.erode = function(canvas) { var pixels = Filters._toPixels(canvas); var currIdx = 0; var maxIdx = pixels.length ? pixels.length / 4 : 0; var out = new Int32Array(maxIdx); var currRowIdx, maxRowIdx, colOrig, colOut, currLum; var idxRight, idxLeft, idxUp, idxDown; var colRight, colLeft, colUp, colDown; var lumRight, lumLeft, lumUp, lumDown; while (currIdx < maxIdx) { currRowIdx = currIdx; maxRowIdx = currIdx + canvas.width; while (currIdx < maxRowIdx) { colOrig = colOut = Filters._getARGB(pixels, currIdx); idxLeft = currIdx - 1; idxRight = currIdx + 1; idxUp = currIdx - canvas.width; idxDown = currIdx + canvas.width; if (idxLeft < currRowIdx) { idxLeft = currIdx; } if (idxRight >= maxRowIdx) { idxRight = currIdx; } if (idxUp < 0) { idxUp = 0; } if (idxDown >= maxIdx) { idxDown = currIdx; } colUp = Filters._getARGB(pixels, idxUp); colLeft = Filters._getARGB(pixels, idxLeft); colDown = Filters._getARGB(pixels, idxDown); colRight = Filters._getARGB(pixels, idxRight); //compute luminance currLum = 77 * ((colOrig >> 16) & 0xff) + 151 * ((colOrig >> 8) & 0xff) + 28 * (colOrig & 0xff); lumLeft = 77 * ((colLeft >> 16) & 0xff) + 151 * ((colLeft >> 8) & 0xff) + 28 * (colLeft & 0xff); lumRight = 77 * ((colRight >> 16) & 0xff) + 151 * ((colRight >> 8) & 0xff) + 28 * (colRight & 0xff); lumUp = 77 * ((colUp >> 16) & 0xff) + 151 * ((colUp >> 8) & 0xff) + 28 * (colUp & 0xff); lumDown = 77 * ((colDown >> 16) & 0xff) + 151 * ((colDown >> 8) & 0xff) + 28 * (colDown & 0xff); if (lumLeft < currLum) { colOut = colLeft; currLum = lumLeft; } if (lumRight < currLum) { colOut = colRight; currLum = lumRight; } if (lumUp < currLum) { colOut = colUp; currLum = lumUp; } if (lumDown < currLum) { colOut = colDown; currLum = lumDown; } out[currIdx++] = colOut; } } Filters._setPixels(pixels, out); }; // BLUR // internal kernel stuff for the gaussian blur filter var blurRadius; var blurKernelSize; var blurKernel; var blurMult; /* * Port of https://github.com/processing/processing/blob/ * master/core/src/processing/core/PImage.java#L1250 * * Optimized code for building the blur kernel. * further optimized blur code (approx. 15% for radius=20) * bigger speed gains for larger radii (~30%) * added support for various image types (ALPHA, RGB, ARGB) * [toxi 050728] */ function buildBlurKernel(r) { var radius = (r * 3.5) | 0; radius = radius < 1 ? 1 : radius < 248 ? radius : 248; if (blurRadius !== radius) { blurRadius = radius; blurKernelSize = (1 + blurRadius) << 1; blurKernel = new Int32Array(blurKernelSize); blurMult = new Array(blurKernelSize); for (var l = 0; l < blurKernelSize; l++) { blurMult[l] = new Int32Array(256); } var bk, bki; var bm, bmi; for (var i = 1, radiusi = radius - 1; i < radius; i++) { blurKernel[radius + i] = blurKernel[radiusi] = bki = radiusi * radiusi; bm = blurMult[radius + i]; bmi = blurMult[radiusi--]; for (var j = 0; j < 256; j++) { bm[j] = bmi[j] = bki * j; } } bk = blurKernel[radius] = radius * radius; bm = blurMult[radius]; for (var k = 0; k < 256; k++) { bm[k] = bk * k; } } } // Port of https://github.com/processing/processing/blob/ // master/core/src/processing/core/PImage.java#L1433 function blurARGB(canvas, radius) { var pixels = Filters._toPixels(canvas); var width = canvas.width; var height = canvas.height; var numPackedPixels = width * height; var argb = new Int32Array(numPackedPixels); for (var j = 0; j < numPackedPixels; j++) { argb[j] = Filters._getARGB(pixels, j); } var sum, cr, cg, cb, ca; var read, ri, ym, ymi, bk0; var a2 = new Int32Array(numPackedPixels); var r2 = new Int32Array(numPackedPixels); var g2 = new Int32Array(numPackedPixels); var b2 = new Int32Array(numPackedPixels); var yi = 0; buildBlurKernel(radius); var x, y, i; var bm; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; read = x - blurRadius; if (read < 0) { bk0 = -read; read = 0; } else { if (read >= width) { break; } bk0 = 0; } for (i = bk0; i < blurKernelSize; i++) { if (read >= width) { break; } var c = argb[read + yi]; bm = blurMult[i]; ca += bm[(c & -16777216) >>> 24]; cr += bm[(c & 16711680) >> 16]; cg += bm[(c & 65280) >> 8]; cb += bm[c & 255]; sum += blurKernel[i]; read++; } ri = yi + x; a2[ri] = ca / sum; r2[ri] = cr / sum; g2[ri] = cg / sum; b2[ri] = cb / sum; } yi += width; } yi = 0; ym = -blurRadius; ymi = ym * width; for (y = 0; y < height; y++) { for (x = 0; x < width; x++) { cb = cg = cr = ca = sum = 0; if (ym < 0) { bk0 = ri = -ym; read = x; } else { if (ym >= height) { break; } bk0 = 0; ri = ym; read = x + ymi; } for (i = bk0; i < blurKernelSize; i++) { if (ri >= height) { break; } bm = blurMult[i]; ca += bm[a2[read]]; cr += bm[r2[read]]; cg += bm[g2[read]]; cb += bm[b2[read]]; sum += blurKernel[i]; ri++; read += width; } argb[x + yi] = ((ca / sum) << 24) | ((cr / sum) << 16) | ((cg / sum) << 8) | (cb / sum); } yi += width; ymi += width; ym++; } Filters._setPixels(pixels, argb); } Filters.blur = function(canvas, radius) { blurARGB(canvas, radius); }; module.exports = Filters; },{}],42:[function(_dereq_,module,exports){ /** * @module Image * @submodule Image * @for p5 * @requires core */ /** * This module defines the p5 methods for the p5.Image class * for drawing images to the main display canvas. */ 'use strict'; var p5 = _dereq_('../core/core'); // This is not global, but JSHint is not aware that // this module is implicitly enclosed with Browserify: this overrides the // redefined-global error and permits using the name "frames" for the array // of saved animation frames. /* global frames:true */ var frames = []; /** * Creates a new p5.Image (the datatype for storing images). This provides a * fresh buffer of pixels to play with. Set the size of the buffer with the * width and height parameters. *

* .pixels gives access to an array containing the values for all the pixels * in the display window. * These values are numbers. This array is the size (including an appropriate * factor for the pixelDensity) of the display window x4, * representing the R, G, B, A values in order for each pixel, moving from * left to right across each row, then down each column. See .pixels for * more info. It may also be simpler to use set() or get(). *

* Before accessing the pixels of an image, the data must loaded with the * loadPixels() function. After the array data has been modified, the * updatePixels() function must be run to update the changes. * * @method createImage * @param {Integer} width width in pixels * @param {Integer} height height in pixels * @return {p5.Image} the p5.Image object * @example *
* * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102)); * } * } * img.updatePixels(); * image(img, 17, 17); * *
* *
* * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102, (i % img.width) * 2)); * } * } * img.updatePixels(); * image(img, 17, 17); * image(img, 34, 34); * *
* *
* * var pink = color(255, 102, 204); * var img = createImage(66, 66); * img.loadPixels(); * var d = pixelDensity(); * var halfImage = 4 * (width * d) * (height / 2 * d); * for (var i = 0; i < halfImage; i += 4) { * img.pixels[i] = red(pink); * img.pixels[i + 1] = green(pink); * img.pixels[i + 2] = blue(pink); * img.pixels[i + 3] = alpha(pink); * } * img.updatePixels(); * image(img, 17, 17); * *
* * @alt * 66x66 dark turquoise rect in center of canvas. * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas * no image displayed * */ p5.prototype.createImage = function(width, height) { p5._validateParameters('createImage', arguments); return new p5.Image(width, height); }; /** * Save the current canvas as an image. In Safari, this will open the * image in the window and the user must provide their own * filename on save-as. Other browsers will either save the * file immediately, or prompt the user with a dialogue window. * * @method saveCanvas * @param {p5.Element|HTMLCanvasElement} selectedCanvas a variable * representing a specific html5 canvas (optional) * @param {String} [filename] * @param {String} [extension] 'jpg' or 'png' * * @example *
* function setup() { * var c = createCanvas(100, 100); * background(255, 0, 0); * saveCanvas(c, 'myCanvas', 'jpg'); * } *
*
* // note that this example has the same result as above * // if no canvas is specified, defaults to main canvas * function setup() { * var c = createCanvas(100, 100); * background(255, 0, 0); * saveCanvas('myCanvas', 'jpg'); * * // all of the following are valid * saveCanvas(c, 'myCanvas', 'jpg'); * saveCanvas(c, 'myCanvas.jpg'); * saveCanvas(c, 'myCanvas'); * saveCanvas(c); * saveCanvas('myCanvas', 'png'); * saveCanvas('myCanvas'); * saveCanvas(); * } *
* * @alt * no image displayed * no image displayed * no image displayed */ /** * @method saveCanvas * @param {String} [filename] * @param {String} [extension] */ p5.prototype.saveCanvas = function() { p5._validateParameters('saveCanvas', arguments); // copy arguments to array var args = [].slice.call(arguments); var htmlCanvas, filename, extension; if (arguments[0] instanceof HTMLCanvasElement) { htmlCanvas = arguments[0]; args.shift(); } else if (arguments[0] instanceof p5.Element) { htmlCanvas = arguments[0].elt; args.shift(); } else { htmlCanvas = this._curElement && this._curElement.elt; } if (args.length >= 1) { filename = args[0]; } if (args.length >= 2) { extension = args[1]; } extension = extension || p5.prototype._checkFileExtension(filename, extension)[1] || 'png'; var mimeType; switch (extension) { default: //case 'png': mimeType = 'image/png'; break; case 'jpeg': case 'jpg': mimeType = 'image/jpeg'; break; } htmlCanvas.toBlob(function(blob) { p5.prototype.downloadFile(blob, filename, extension); }, mimeType); }; /** * Capture a sequence of frames that can be used to create a movie. * Accepts a callback. For example, you may wish to send the frames * to a server where they can be stored or converted into a movie. * If no callback is provided, the browser will pop up save dialogues in an * attempt to download all of the images that have just been created. With the * callback provided the image data isn't saved by default but instead passed * as an argument to the callback function as an array of objects, with the * size of array equal to the total number of frames. * * Note that saveFrames() will only save the first 15 frames of an animation. * To export longer animations, you might look into a library like * ccapture.js. * * @method saveFrames * @param {String} filename * @param {String} extension 'jpg' or 'png' * @param {Number} duration Duration in seconds to save the frames for. * @param {Number} framerate Framerate to save the frames in. * @param {function(Array)} [callback] A callback function that will be executed to handle the image data. This function should accept an array as argument. The array will contain the specified number of frames of objects. Each object has three properties: imageData - an image/octet-stream, filename and extension. * @example *
* function draw() { * background(mouseX); * } * * function mousePressed() { * saveFrames('out', 'png', 1, 25, function(data) { * print(data); * }); * }
* * @alt * canvas background goes from light to dark with mouse x. * */ p5.prototype.saveFrames = function(fName, ext, _duration, _fps, callback) { p5._validateParameters('saveFrames', arguments); var duration = _duration || 3; duration = p5.prototype.constrain(duration, 0, 15); duration = duration * 1000; var fps = _fps || 15; fps = p5.prototype.constrain(fps, 0, 22); var count = 0; var makeFrame = p5.prototype._makeFrame; var cnv = this._curElement.elt; var frameFactory = setInterval(function() { makeFrame(fName + count, ext, cnv); count++; }, 1000 / fps); setTimeout(function() { clearInterval(frameFactory); if (callback) { callback(frames); } else { for (var i = 0; i < frames.length; i++) { var f = frames[i]; p5.prototype.downloadFile(f.imageData, f.filename, f.ext); } } frames = []; // clear frames }, duration + 0.01); }; p5.prototype._makeFrame = function(filename, extension, _cnv) { var cnv; if (this) { cnv = this._curElement.elt; } else { cnv = _cnv; } var mimeType; if (!extension) { extension = 'png'; mimeType = 'image/png'; } else { switch (extension.toLowerCase()) { case 'png': mimeType = 'image/png'; break; case 'jpeg': mimeType = 'image/jpeg'; break; case 'jpg': mimeType = 'image/jpeg'; break; default: mimeType = 'image/png'; break; } } var downloadMime = 'image/octet-stream'; var imageData = cnv.toDataURL(mimeType); imageData = imageData.replace(mimeType, downloadMime); var thisFrame = {}; thisFrame.imageData = imageData; thisFrame.filename = filename; thisFrame.ext = extension; frames.push(thisFrame); }; module.exports = p5; },{"../core/core":22}],43:[function(_dereq_,module,exports){ /** * @module Image * @submodule Loading & Displaying * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var Filters = _dereq_('./filters'); var canvas = _dereq_('../core/canvas'); var constants = _dereq_('../core/constants'); _dereq_('../core/error_helpers'); /** * Loads an image from a path and creates a p5.Image from it. *

* The image may not be immediately available for rendering * If you want to ensure that the image is ready before doing * anything with it, place the loadImage() call in preload(). * You may also supply a callback function to handle the image when it's ready. *

* The path to the image should be relative to the HTML file * that links in your sketch. Loading an image from a URL or other * remote location may be blocked due to your browser's built-in * security. * * @method loadImage * @param {String} path Path of the image to be loaded * @param {function(p5.Image)} [successCallback] Function to be called once * the image is loaded. Will be passed the * p5.Image. * @param {function(Event)} [failureCallback] called with event error if * the image fails to load. * @return {p5.Image} the p5.Image object * @example *
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * } * *
*
* * function setup() { * // here we use a callback to display the image after loading * loadImage('assets/laDefense.jpg', function(img) { * image(img, 0, 0); * }); * } * *
* * @alt * image of the underside of a white umbrella and grided ceililng above * image of the underside of a white umbrella and grided ceililng above * */ p5.prototype.loadImage = function(path, successCallback, failureCallback) { p5._validateParameters('loadImage', arguments); var img = new Image(); var pImg = new p5.Image(1, 1, this); var self = this; img.onload = function() { pImg.width = pImg.canvas.width = img.width; pImg.height = pImg.canvas.height = img.height; // Draw the image into the backing canvas of the p5.Image pImg.drawingContext.drawImage(img, 0, 0); pImg.modified = true; if (typeof successCallback === 'function') { successCallback(pImg); } self._decrementPreload(); }; img.onerror = function(e) { p5._friendlyFileLoadError(0, img.src); if (typeof failureCallback === 'function') { failureCallback(e); } }; //set crossOrigin in case image is served which CORS headers //this will let us draw to canvas without tainting it. //see https://developer.mozilla.org/en-US/docs/HTML/CORS_Enabled_Image // When using data-uris the file will be loaded locally // so we don't need to worry about crossOrigin with base64 file types if (path.indexOf('data:image/') !== 0) { img.crossOrigin = 'Anonymous'; } //start loading the image img.src = path; return pImg; }; /** * Validates clipping params. Per drawImage spec sWidth and sHight cannot be * negative or greater than image intrinsic width and height * @private * @param {Number} sVal * @param {Number} iVal * @returns {Number} * @private */ function _sAssign(sVal, iVal) { if (sVal > 0 && sVal < iVal) { return sVal; } else { return iVal; } } /** * Draw an image to the p5.js canvas. * * This function can be used with different numbers of parameters. The * simplest use requires only three parameters: img, x, and y—where (x, y) is * the position of the image. Two more parameters can optionally be added to * specify the width and height of the image. * * This function can also be used with all eight Number parameters. To * differentiate between all these parameters, p5.js uses the language of * "destination rectangle" (which corresponds to "dx", "dy", etc.) and "source * image" (which corresponds to "sx", "sy", etc.) below. Specifying the * "source image" dimensions can be useful when you want to display a * subsection of the source image instead of the whole thing. Here's a diagram * to explain further: * * * @method image * @param {p5.Image|p5.Element} img the image to display * @param {Number} x the x-coordinate of the top-left corner of the image * @param {Number} y the y-coordinate of the top-left corner of the image * @param {Number} [width] the width to draw the image * @param {Number} [height] the height to draw the image * @example *
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * // Top-left corner of the img is at (0, 0) * // Width and height are the img's original width and height * image(img, 0, 0); * } * *
*
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * background(50); * // Top-left corner of the img is at (10, 10) * // Width and height are 50 x 50 * image(img, 10, 10, 50, 50); * } * *
*
* * function setup() { * // Here, we use a callback to display the image after loading * loadImage('assets/laDefense.jpg', function(img) { * image(img, 0, 0); * }); * } * *
*
* * var img; * function preload() { * img = loadImage('assets/gradient.png'); * } * function setup() { * // 1. Background image * // Top-left corner of the img is at (0, 0) * // Width and height are the img's original width and height, 100 x 100 * image(img, 0, 0); * // 2. Top right image * // Top-left corner of destination rectangle is at (50, 0) * // Destination rectangle width and height are 40 x 20 * // The next parameters are relative to the source image: * // - Starting at position (50, 50) on the source image, capture a 50 x 50 * // subsection * // - Draw this subsection to fill the dimensions of the destination rectangle * image(img, 50, 0, 40, 20, 50, 50, 50, 50); * } * *
* @alt * image of the underside of a white umbrella and gridded ceiling above * image of the underside of a white umbrella and gridded ceiling above * */ /** * @method image * @param {p5.Image|p5.Element} img * @param {Number} dx the x-coordinate of the destination * rectangle in which to draw the source image * @param {Number} dy the y-coordinate of the destination * rectangle in which to draw the source image * @param {Number} dWidth the width of the destination rectangle * @param {Number} dHeight the height of the destination rectangle * @param {Number} sx the x-coordinate of the subsection of the source * image to draw into the destination rectangle * @param {Number} sy the y-coordinate of the subsection of the source * image to draw into the destination rectangle * @param {Number} [sWidth] the width of the subsection of the * source image to draw into the destination * rectangle * @param {Number} [sHeight] the height of the subsection of the * source image to draw into the destination rectangle */ p5.prototype.image = function( img, dx, dy, dWidth, dHeight, sx, sy, sWidth, sHeight ) { // set defaults per spec: https://goo.gl/3ykfOq p5._validateParameters('image', arguments); var defW = img.width; var defH = img.height; if (img.elt && img.elt.videoWidth && !img.canvas) { // video no canvas defW = img.elt.videoWidth; defH = img.elt.videoHeight; } var _dx = dx; var _dy = dy; var _dw = dWidth || defW; var _dh = dHeight || defH; var _sx = sx || 0; var _sy = sy || 0; var _sw = sWidth || defW; var _sh = sHeight || defH; _sw = _sAssign(_sw, defW); _sh = _sAssign(_sh, defH); // This part needs cleanup and unit tests // see issues https://github.com/processing/p5.js/issues/1741 // and https://github.com/processing/p5.js/issues/1673 var pd = 1; if (img.elt && !img.canvas && img.elt.style.width) { //if img is video and img.elt.size() has been used and //no width passed to image() if (img.elt.videoWidth && !dWidth) { pd = img.elt.videoWidth; } else { //all other cases pd = img.elt.width; } pd /= parseInt(img.elt.style.width, 10); } _sx *= pd; _sy *= pd; _sh *= pd; _sw *= pd; var vals = canvas.modeAdjust(_dx, _dy, _dw, _dh, this._renderer._imageMode); // tint the image if there is a tint this._renderer.image(img, _sx, _sy, _sw, _sh, vals.x, vals.y, vals.w, vals.h); }; /** * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by including an alpha value. *

* To apply transparency to an image without affecting its color, use * white as the tint color and specify an alpha value. For instance, * tint(255, 128) will make an image 50% transparent (assuming the default * alpha range of 0-255, which can be changed with colorMode()). *

* The value for the gray parameter must be less than or equal to the current * maximum value as specified by colorMode(). The default maximum value is * 255. * * * @method tint * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * * @example *
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * tint(0, 153, 204); // Tint blue * image(img, 50, 0); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * tint(0, 153, 204, 126); // Tint blue and set transparency * image(img, 50, 0); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * function setup() { * image(img, 0, 0); * tint(255, 126); // Apply transparency without changing color * image(img, 50, 0); * } * *
* * @alt * 2 side by side images of umbrella and ceiling, one image with blue tint * Images of umbrella and ceiling, one half of image with blue tint * 2 side by side images of umbrella and ceiling, one image translucent * */ /** * @method tint * @param {String} value a color string */ /** * @method tint * @param {Number} gray a gray value * @param {Number} [alpha] */ /** * @method tint * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color */ /** * @method tint * @param {p5.Color} color the tint color */ p5.prototype.tint = function() { p5._validateParameters('tint', arguments); var c = this.color.apply(this, arguments); this._renderer._tint = c.levels; }; /** * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * @method noTint * @example *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * tint(0, 153, 204); // Tint blue * image(img, 0, 0); * noTint(); // Disable tint * image(img, 50, 0); * } * *
* * @alt * 2 side by side images of bricks, left image with blue tint * */ p5.prototype.noTint = function() { this._renderer._tint = null; }; /** * Apply the current tint color to the input image, return the resulting * canvas. * * @private * @param {p5.Image} The image to be tinted * @return {canvas} The resulting tinted canvas * */ p5.prototype._getTintedImageCanvas = function(img) { if (!img.canvas) { return img; } var pixels = Filters._toPixels(img.canvas); var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = img.canvas.width; tmpCanvas.height = img.canvas.height; var tmpCtx = tmpCanvas.getContext('2d'); var id = tmpCtx.createImageData(img.canvas.width, img.canvas.height); var newPixels = id.data; for (var i = 0; i < pixels.length; i += 4) { var r = pixels[i]; var g = pixels[i + 1]; var b = pixels[i + 2]; var a = pixels[i + 3]; newPixels[i] = r * this._renderer._tint[0] / 255; newPixels[i + 1] = g * this._renderer._tint[1] / 255; newPixels[i + 2] = b * this._renderer._tint[2] / 255; newPixels[i + 3] = a * this._renderer._tint[3] / 255; } tmpCtx.putImageData(id, 0, 0); return tmpCanvas; }; /** * Set image mode. Modifies the location from which images are drawn by * changing the way in which parameters given to image() are interpreted. * The default mode is imageMode(CORNER), which interprets the second and * third parameters of image() as the upper-left corner of the image. If * two additional parameters are specified, they are used to set the image's * width and height. *

* imageMode(CORNERS) interprets the second and third parameters of image() * as the location of one corner, and the fourth and fifth parameters as the * opposite corner. *

* imageMode(CENTER) interprets the second and third parameters of image() * as the image's center point. If two additional parameters are specified, * they are used to set the image's width and height. * * @method imageMode * @param {Constant} mode either CORNER, CORNERS, or CENTER * @example * *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * imageMode(CORNER); * image(img, 10, 10, 50, 50); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * imageMode(CORNERS); * image(img, 10, 10, 90, 40); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * imageMode(CENTER); * image(img, 50, 50, 80, 80); * } * *
* * @alt * small square image of bricks * horizontal rectangle image of bricks * large square image of bricks * */ p5.prototype.imageMode = function(m) { p5._validateParameters('imageMode', arguments); if ( m === constants.CORNER || m === constants.CORNERS || m === constants.CENTER ) { this._renderer._imageMode = m; } }; module.exports = p5; },{"../core/canvas":20,"../core/constants":21,"../core/core":22,"../core/error_helpers":25,"./filters":41}],44:[function(_dereq_,module,exports){ /** * @module Image * @submodule Image * @requires core * @requires constants * @requires filters */ /** * This module defines the p5.Image class and P5 methods for * drawing images to the main display canvas. */ 'use strict'; var p5 = _dereq_('../core/core'); var Filters = _dereq_('./filters'); /* * Class methods */ /** * Creates a new p5.Image. A p5.Image is a canvas backed representation of an * image. *

* p5 can display .gif, .jpg and .png images. Images may be displayed * in 2D and 3D space. Before an image is used, it must be loaded with the * loadImage() function. The p5.Image class contains fields for the width and * height of the image, as well as an array called pixels[] that contains the * values for every pixel in the image. *

* The methods described below allow easy access to the image's pixels and * alpha channel and simplify the process of compositing. *

* Before using the pixels[] array, be sure to use the loadPixels() method on * the image to make sure that the pixel data is properly loaded. * @example *
* function setup() { * var img = createImage(100, 100); // same as new p5.Image(100, 100); * img.loadPixels(); * createCanvas(100, 100); * background(0); * * // helper for writing color to array * function writeColor(image, x, y, red, green, blue, alpha) { * var index = (x + y * width) * 4; * image.pixels[index] = red; * image.pixels[index + 1] = green; * image.pixels[index + 2] = blue; * image.pixels[index + 3] = alpha; * } * * var x, y; * // fill with random colors * for (y = 0; y < img.height; y++) { * for (x = 0; x < img.width; x++) { * var red = random(255); * var green = random(255); * var blue = random(255); * var alpha = 255; * writeColor(img, x, y, red, green, blue, alpha); * } * } * * // draw a red line * y = 0; * for (x = 0; x < img.width; x++) { * writeColor(img, x, y, 255, 0, 0, 255); * } * * // draw a green line * y = img.height - 1; * for (x = 0; x < img.width; x++) { * writeColor(img, x, y, 0, 255, 0, 255); * } * * img.updatePixels(); * image(img, 0, 0); * } *
* * * @class p5.Image * @param {Number} width * @param {Number} height */ p5.Image = function(width, height) { /** * Image width. * @property {Number} width * @readOnly * @example *
* var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * createCanvas(100, 100); * image(img, 0, 0); * for (var i = 0; i < img.width; i++) { * var c = img.get(i, img.height / 2); * stroke(c); * line(i, height / 2, i, height); * } * } *
* * @alt * rocky mountains in top and horizontal lines in corresponding colors in bottom. * */ this.width = width; /** * Image height. * @property {Number} height * @readOnly * @example *
* var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * createCanvas(100, 100); * image(img, 0, 0); * for (var i = 0; i < img.height; i++) { * var c = img.get(img.width / 2, i); * stroke(c); * line(0, i, width / 2, i); * } * } *
* * @alt * rocky mountains on right and vertical lines in corresponding colors on left. * */ this.height = height; this.canvas = document.createElement('canvas'); this.canvas.width = this.width; this.canvas.height = this.height; this.drawingContext = this.canvas.getContext('2d'); this._pixelDensity = 1; //used for webgl texturing only this._modified = false; /** * Array containing the values for all the pixels in the display window. * These values are numbers. This array is the size (include an appropriate * factor for pixelDensity) of the display window x4, * representing the R, G, B, A values in order for each pixel, moving from * left to right across each row, then down each column. Retina and other * high denisty displays may have more pixels[] (by a factor of * pixelDensity^2). * For example, if the image is 100x100 pixels, there will be 40,000. With * pixelDensity = 2, there will be 160,000. The first four values * (indices 0-3) in the array will be the R, G, B, A values of the pixel at * (0, 0). The second four values (indices 4-7) will contain the R, G, B, A * values of the pixel at (1, 0). More generally, to set values for a pixel * at (x, y): * ```javascript * var d = pixelDensity(); * for (var i = 0; i < d; i++) { * for (var j = 0; j < d; j++) { * // loop over * idx = 4 * ((y * d + j) * width * d + (x * d + i)); * pixels[idx] = r; * pixels[idx+1] = g; * pixels[idx+2] = b; * pixels[idx+3] = a; * } * } * ``` *

* Before accessing this array, the data must loaded with the loadPixels() * function. After the array data has been modified, the updatePixels() * function must be run to update the changes. * @property {Number[]} pixels * @example *
* * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102)); * } * } * img.updatePixels(); * image(img, 17, 17); * *
*
* * var pink = color(255, 102, 204); * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < 4 * (width * height / 2); i += 4) { * img.pixels[i] = red(pink); * img.pixels[i + 1] = green(pink); * img.pixels[i + 2] = blue(pink); * img.pixels[i + 3] = alpha(pink); * } * img.updatePixels(); * image(img, 17, 17); * *
* * @alt * 66x66 turquoise rect in center of canvas * 66x66 pink rect in center of canvas * */ this.pixels = []; }; /** * Helper fxn for sharing pixel methods * */ p5.Image.prototype._setProperty = function(prop, value) { this[prop] = value; this.setModified(true); }; /** * Loads the pixels data for this image into the [pixels] attribute. * * @method loadPixels * @example *
* var myImage; * var halfImage; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); * } * * function setup() { * myImage.loadPixels(); * halfImage = 4 * width * height / 2; * for (var i = 0; i < halfImage; i++) { * myImage.pixels[i + halfImage] = myImage.pixels[i]; * } * myImage.updatePixels(); * } * * function draw() { * image(myImage, 0, 0); * } *
* * @alt * 2 images of rocky mountains vertically stacked * */ p5.Image.prototype.loadPixels = function() { p5.Renderer2D.prototype.loadPixels.call(this); this.setModified(true); }; /** * Updates the backing canvas for this image with the contents of * the [pixels] array. * * @method updatePixels * @param {Integer} x x-offset of the target update area for the * underlying canvas * @param {Integer} y y-offset of the target update area for the * underlying canvas * @param {Integer} w height of the target update area for the * underlying canvas * @param {Integer} h height of the target update area for the * underlying canvas * @example *
* var myImage; * var halfImage; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); * } * * function setup() { * myImage.loadPixels(); * halfImage = 4 * width * height / 2; * for (var i = 0; i < halfImage; i++) { * myImage.pixels[i + halfImage] = myImage.pixels[i]; * } * myImage.updatePixels(); * } * * function draw() { * image(myImage, 0, 0); * } *
* * @alt * 2 images of rocky mountains vertically stacked * */ /** * @method updatePixels */ p5.Image.prototype.updatePixels = function(x, y, w, h) { p5.Renderer2D.prototype.updatePixels.call(this, x, y, w, h); this.setModified(true); }; /** * Get a region of pixels from an image. * * If no params are passed, those whole image is returned, * if x and y are the only params passed a single pixel is extracted * if all params are passed a rectangle region is extracted and a p5.Image * is returned. * * Returns undefined if the region is outside the bounds of the image * * @method get * @param {Number} [x] x-coordinate of the pixel * @param {Number} [y] y-coordinate of the pixel * @param {Number} [w] width * @param {Number} [h] height * @return {Number[]|Color|p5.Image} color of pixel at x,y in array format * [R, G, B, A] or p5.Image * @example *
* var myImage; * var c; * * function preload() { * myImage = loadImage('assets/rockies.jpg'); * } * * function setup() { * background(myImage); * noStroke(); * c = myImage.get(60, 90); * fill(c); * rect(25, 25, 50, 50); * } * * //get() returns color here *
* * @alt * image of rocky mountains with 50x50 green rect in front * */ p5.Image.prototype.get = function(x, y, w, h) { return p5.Renderer2D.prototype.get.call(this, x, y, w, h); }; /** * Set the color of a single pixel or write an image into * this p5.Image. * * Note that for a large number of pixels this will * be slower than directly manipulating the pixels array * and then calling updatePixels(). * * @method set * @param {Number} x x-coordinate of the pixel * @param {Number} y y-coordinate of the pixel * @param {Number|Number[]|Object} a grayscale value | pixel array | * a p5.Color | image to copy * @example *
* * var img = createImage(66, 66); * img.loadPixels(); * for (var i = 0; i < img.width; i++) { * for (var j = 0; j < img.height; j++) { * img.set(i, j, color(0, 90, 102, (i % img.width) * 2)); * } * } * img.updatePixels(); * image(img, 17, 17); * image(img, 34, 34); * *
* * @alt * 2 gradated dark turquoise rects fade left. 1 center 1 bottom right of canvas * */ p5.Image.prototype.set = function(x, y, imgOrCol) { p5.Renderer2D.prototype.set.call(this, x, y, imgOrCol); this.setModified(true); }; /** * Resize the image to a new width and height. To make the image scale * proportionally, use 0 as the value for the wide or high parameter. * For instance, to make the width of an image 150 pixels, and change * the height using the same proportion, use resize(150, 0). * * @method resize * @param {Number} width the resized image width * @param {Number} height the resized image height * @example *
* var img; * * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function draw() { * image(img, 0, 0); * } * * function mousePressed() { * img.resize(50, 100); * } *
* * @alt * image of rocky mountains. zoomed in * */ p5.Image.prototype.resize = function(width, height) { // Copy contents to a temporary canvas, resize the original // and then copy back. // // There is a faster approach that involves just one copy and swapping the // this.canvas reference. We could switch to that approach if (as i think // is the case) there an expectation that the user would not hold a // reference to the backing canvas of a p5.Image. But since we do not // enforce that at the moment, I am leaving in the slower, but safer // implementation. // auto-resize if (width === 0 && height === 0) { width = this.canvas.width; height = this.canvas.height; } else if (width === 0) { width = this.canvas.width * height / this.canvas.height; } else if (height === 0) { height = this.canvas.height * width / this.canvas.width; } width = Math.floor(width); height = Math.floor(height); var tempCanvas = document.createElement('canvas'); tempCanvas.width = width; tempCanvas.height = height; // prettier-ignore tempCanvas.getContext('2d').drawImage( this.canvas, 0, 0, this.canvas.width, this.canvas.height, 0, 0, tempCanvas.width, tempCanvas.height ); // Resize the original canvas, which will clear its contents this.canvas.width = this.width = width; this.canvas.height = this.height = height; //Copy the image back // prettier-ignore this.drawingContext.drawImage( tempCanvas, 0, 0, width, height, 0, 0, width, height ); if (this.pixels.length > 0) { this.loadPixels(); } this.setModified(true); }; /** * Copies a region of pixels from one image to another. If no * srcImage is specified this is used as the source. If the source * and destination regions aren't the same size, it will * automatically resize source pixels to fit the specified * target region. * * @method copy * @param {p5.Image|p5.Element} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * @example *
* var photo; * var bricks; * var x; * var y; * * function preload() { * photo = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks.jpg'); * } * * function setup() { * x = bricks.width / 2; * y = bricks.height / 2; * photo.copy(bricks, 0, 0, x, y, 0, 0, x, y); * image(photo, 0, 0); * } *
* * @alt * image of rocky mountains and smaller image on top of bricks at top left * */ /** * @method copy * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh */ p5.Image.prototype.copy = function() { var srcImage, sx, sy, sw, sh, dx, dy, dw, dh; if (arguments.length === 9) { srcImage = arguments[0]; sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else if (arguments.length === 8) { srcImage = this; sx = arguments[0]; sy = arguments[1]; sw = arguments[2]; sh = arguments[3]; dx = arguments[4]; dy = arguments[5]; dw = arguments[6]; dh = arguments[7]; } else { throw new Error('Signature not supported'); } p5.Renderer2D._copyHelper(this, srcImage, sx, sy, sw, sh, dx, dy, dw, dh); }; /** * Masks part of an image from displaying by loading another * image and using it's alpha channel as an alpha channel for * this image. * * @method mask * @param {p5.Image} srcImage source image * @example *
* var photo, maskImage; * function preload() { * photo = loadImage('assets/rockies.jpg'); * maskImage = loadImage('assets/mask2.png'); * } * * function setup() { * createCanvas(100, 100); * photo.mask(maskImage); * image(photo, 0, 0); * } *
* * @alt * image of rocky mountains with white at right * * * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ * */ // TODO: - Accept an array of alpha values. // - Use other channels of an image. p5 uses the // blue channel (which feels kind of arbitrary). Note: at the // moment this method does not match native processings original // functionality exactly. p5.Image.prototype.mask = function(p5Image) { if (p5Image === undefined) { p5Image = this; } var currBlend = this.drawingContext.globalCompositeOperation; var scaleFactor = 1; if (p5Image instanceof p5.Renderer) { scaleFactor = p5Image._pInst._pixelDensity; } var copyArgs = [ p5Image, 0, 0, scaleFactor * p5Image.width, scaleFactor * p5Image.height, 0, 0, this.width, this.height ]; this.drawingContext.globalCompositeOperation = 'destination-in'; p5.Image.prototype.copy.apply(this, copyArgs); this.drawingContext.globalCompositeOperation = currBlend; this.setModified(true); }; /** * Applies an image filter to a p5.Image * * @method filter * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, BLUR, ERODE, DILATE or BLUR. * See Filters.js for docs on * each available filter * @param {Number} [filterParam] an optional parameter unique * to each filter, see above * @example *
* var photo1; * var photo2; * * function preload() { * photo1 = loadImage('assets/rockies.jpg'); * photo2 = loadImage('assets/rockies.jpg'); * } * * function setup() { * photo2.filter('gray'); * image(photo1, 0, 0); * image(photo2, width / 2, 0); * } *
* * @alt * 2 images of rocky mountains left one in color, right in black and white * */ p5.Image.prototype.filter = function(operation, value) { Filters.apply(this.canvas, Filters[operation.toLowerCase()], value); this.setModified(true); }; /** * Copies a region of pixels from one image to another, using a specified * blend mode to do the operation. * * @method blend * @param {p5.Image} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * @param {Constant} blendMode the blend mode. either * BLEND, DARKEST, LIGHTEST, DIFFERENCE, * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. * * Available blend modes are: normal | multiply | screen | overlay | * darken | lighten | color-dodge | color-burn | hard-light | * soft-light | difference | exclusion | hue | saturation | * color | luminosity * * * http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/ * @example *
* var mountains; * var bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, ADD); * image(mountains, 0, 0); * image(bricks, 0, 0); * } *
*
* var mountains; * var bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); * image(mountains, 0, 0); * image(bricks, 0, 0); * } *
*
* var mountains; * var bricks; * * function preload() { * mountains = loadImage('assets/rockies.jpg'); * bricks = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * mountains.blend(bricks, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); * image(mountains, 0, 0); * image(bricks, 0, 0); * } *
* * @alt * image of rocky mountains. Brick images on left and right. Right overexposed * image of rockies. Brickwall images on left and right. Right mortar transparent * image of rockies. Brickwall images on left and right. Right translucent * */ /** * @method blend * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh * @param {Constant} blendMode */ p5.Image.prototype.blend = function() { p5.prototype.blend.apply(this, arguments); this.setModified(true); }; /** * helper method for web GL mode to indicate that an image has been * changed or unchanged since last upload. gl texture upload will * set this value to false after uploading the texture. * @method setModified * @param {boolean} val sets whether or not the image has been * modified. * @private */ p5.Image.prototype.setModified = function(val) { this._modified = val; //enforce boolean? }; /** * helper method for web GL mode to figure out if the image * has been modified and might need to be re-uploaded to texture * memory between frames. * @method isModified * @private * @return {boolean} a boolean indicating whether or not the * image has been updated or modified since last texture upload. */ p5.Image.prototype.isModified = function() { return this._modified; }; /** * Saves the image to a file and force the browser to download it. * Accepts two strings for filename and file extension * Supports png (default) and jpg. * * @method save * @param {String} filename give your file a name * @param {String} extension 'png' or 'jpg' * @example *
* var photo; * * function preload() { * photo = loadImage('assets/rockies.jpg'); * } * * function draw() { * image(photo, 0, 0); * } * * function keyTyped() { * if (key === 's') { * photo.save('photo', 'png'); * } * } *
* * @alt * image of rocky mountains. * */ p5.Image.prototype.save = function(filename, extension) { p5.prototype.saveCanvas(this.canvas, filename, extension); }; module.exports = p5.Image; },{"../core/core":22,"./filters":41}],45:[function(_dereq_,module,exports){ /** * @module Image * @submodule Pixels * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var Filters = _dereq_('./filters'); _dereq_('../color/p5.Color'); /** * Uint8ClampedArray * containing the values for all the pixels in the display window. * These values are numbers. This array is the size (include an appropriate * factor for pixelDensity) of the display window x4, * representing the R, G, B, A values in order for each pixel, moving from * left to right across each row, then down each column. Retina and other * high density displays will have more pixels[] (by a factor of * pixelDensity^2). * For example, if the image is 100x100 pixels, there will be 40,000. On a * retina display, there will be 160,000. *

* The first four values (indices 0-3) in the array will be the R, G, B, A * values of the pixel at (0, 0). The second four values (indices 4-7) will * contain the R, G, B, A values of the pixel at (1, 0). More generally, to * set values for a pixel at (x, y): * ```javascript * var d = pixelDensity(); * for (var i = 0; i < d; i++) { * for (var j = 0; j < d; j++) { * // loop over * idx = 4 * ((y * d + j) * width * d + (x * d + i)); * pixels[idx] = r; * pixels[idx+1] = g; * pixels[idx+2] = b; * pixels[idx+3] = a; * } * } * ``` *

While the above method is complex, it is flexible enough to work with * any pixelDensity. Note that set() will automatically take care of * setting all the appropriate values in pixels[] for a given (x, y) at * any pixelDensity, but the performance may not be as fast when lots of * modifications are made to the pixel array. *

* Before accessing this array, the data must loaded with the loadPixels() * function. After the array data has been modified, the updatePixels() * function must be run to update the changes. *

* Note that this is not a standard javascript array. This means that * standard javascript functions such as slice() or * arrayCopy() do not * work.

* * @property {Number[]} pixels * @example *
* * var pink = color(255, 102, 204); * loadPixels(); * var d = pixelDensity(); * var halfImage = 4 * (width * d) * (height / 2 * d); * for (var i = 0; i < halfImage; i += 4) { * pixels[i] = red(pink); * pixels[i + 1] = green(pink); * pixels[i + 2] = blue(pink); * pixels[i + 3] = alpha(pink); * } * updatePixels(); * *
* * @alt * top half of canvas pink, bottom grey * */ p5.prototype.pixels = []; /** * Copies a region of pixels from one image to another, using a specified * blend mode to do the operation. * * @method blend * @param {p5.Image} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * @param {Constant} blendMode the blend mode. either * BLEND, DARKEST, LIGHTEST, DIFFERENCE, * MULTIPLY, EXCLUSION, SCREEN, REPLACE, OVERLAY, HARD_LIGHT, * SOFT_LIGHT, DODGE, BURN, ADD or NORMAL. * * @example *
* var img0; * var img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); * img1 = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * background(img0); * image(img1, 0, 0); * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, LIGHTEST); * } *
*
* var img0; * var img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); * img1 = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * background(img0); * image(img1, 0, 0); * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, DARKEST); * } *
*
* var img0; * var img1; * * function preload() { * img0 = loadImage('assets/rockies.jpg'); * img1 = loadImage('assets/bricks_third.jpg'); * } * * function setup() { * background(img0); * image(img1, 0, 0); * blend(img1, 0, 0, 33, 100, 67, 0, 33, 100, ADD); * } *
* * @alt * image of rocky mountains. Brick images on left and right. Right overexposed * image of rockies. Brickwall images on left and right. Right mortar transparent * image of rockies. Brickwall images on left and right. Right translucent * * */ /** * @method blend * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh * @param {Constant} blendMode */ p5.prototype.blend = function() { p5._validateParameters('blend', arguments); if (this._renderer) { this._renderer.blend.apply(this._renderer, arguments); } else { p5.Renderer2D.prototype.blend.apply(this, arguments); } }; /** * Copies a region of the canvas to another region of the canvas * and copies a region of pixels from an image used as the srcImg parameter * into the canvas srcImage is specified this is used as the source. If * the source and destination regions aren't the same size, it will * automatically resize source pixels to fit the specified * target region. * * @method copy * @param {p5.Image|p5.Element} srcImage source image * @param {Integer} sx X coordinate of the source's upper left corner * @param {Integer} sy Y coordinate of the source's upper left corner * @param {Integer} sw source image width * @param {Integer} sh source image height * @param {Integer} dx X coordinate of the destination's upper left corner * @param {Integer} dy Y coordinate of the destination's upper left corner * @param {Integer} dw destination image width * @param {Integer} dh destination image height * * @example *
* var img; * * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * background(img); * copy(img, 7, 22, 10, 10, 35, 25, 50, 50); * stroke(255); * noFill(); * // Rectangle shows area being copied * rect(7, 22, 10, 10); * } *
* * @alt * image of rocky mountains. Brick images on left and right. Right overexposed * image of rockies. Brickwall images on left and right. Right mortar transparent * image of rockies. Brickwall images on left and right. Right translucent * */ /** * @method copy * @param {Integer} sx * @param {Integer} sy * @param {Integer} sw * @param {Integer} sh * @param {Integer} dx * @param {Integer} dy * @param {Integer} dw * @param {Integer} dh */ p5.prototype.copy = function() { p5._validateParameters('copy', arguments); p5.Renderer2D.prototype.copy.apply(this._renderer, arguments); }; /** * Applies a filter to the canvas. *

* * The presets options are: *

* * THRESHOLD * Converts the image to black and white pixels depending if they are above or * below the threshold defined by the level parameter. The parameter must be * between 0.0 (black) and 1.0 (white). If no level is specified, 0.5 is used. *

* * GRAY * Converts any colors in the image to grayscale equivalents. No parameter * is used. *

* * OPAQUE * Sets the alpha channel to entirely opaque. No parameter is used. *

* * INVERT * Sets each pixel to its inverse value. No parameter is used. *

* * POSTERIZE * Limits each channel of the image to the number of colors specified as the * parameter. The parameter can be set to values between 2 and 255, but * results are most noticeable in the lower ranges. *

* * BLUR * Executes a Gaussian blur with the level parameter specifying the extent * of the blurring. If no parameter is used, the blur is equivalent to * Gaussian blur of radius 1. Larger values increase the blur. *

* * ERODE * Reduces the light areas. No parameter is used. *

* * DILATE * Increases the light areas. No parameter is used. * * @method filter * @param {Constant} filterType either THRESHOLD, GRAY, OPAQUE, INVERT, * POSTERIZE, BLUR, ERODE, DILATE or BLUR. * See Filters.js for docs on * each available filter * @param {Number} [filterParam] an optional parameter unique * to each filter, see above * * @example *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(THRESHOLD); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(GRAY); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(OPAQUE); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(INVERT); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(POSTERIZE, 3); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(DILATE); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(BLUR, 3); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/bricks.jpg'); * } * function setup() { * image(img, 0, 0); * filter(ERODE); * } * *
* * @alt * black and white image of a brick wall. * greyscale image of a brickwall * image of a brickwall * jade colored image of a brickwall * red and pink image of a brickwall * image of a brickwall * blurry image of a brickwall * image of a brickwall * image of a brickwall with less detail * */ p5.prototype.filter = function(operation, value) { p5._validateParameters('filter', arguments); if (this.canvas !== undefined) { Filters.apply(this.canvas, Filters[operation.toLowerCase()], value); } else { Filters.apply(this.elt, Filters[operation.toLowerCase()], value); } }; /** * Returns an array of [R,G,B,A] values for any pixel or grabs a section of * an image. If no parameters are specified, the entire image is returned. * Use the x and y parameters to get the value of one pixel. Get a section of * the display window by specifying additional w and h parameters. When * getting an image, the x and y parameters define the coordinates for the * upper-left corner of the image, regardless of the current imageMode(). *

* If the pixel requested is outside of the image window, [0,0,0,255] is * returned. To get the numbers scaled according to the current color ranges * and taking into account colorMode, use getColor instead of get. *

* Getting the color of a single pixel with get(x, y) is easy, but not as fast * as grabbing the data directly from pixels[]. The equivalent statement to * get(x, y) using pixels[] with pixel density d is * * var x, y, d; // set these to the coordinates * var off = (y * width + x) * d * 4; * var components = [ * pixels[off], * pixels[off + 1], * pixels[off + 2], * pixels[off + 3] * ]; * print(components); * *

* See the reference for pixels[] for more information. * * @method get * @param {Number} [x] x-coordinate of the pixel * @param {Number} [y] y-coordinate of the pixel * @param {Number} [w] width * @param {Number} [h] height * @return {Number[]|p5.Image} values of pixel at x,y in array format * [R, G, B, A] or p5.Image * @example *
* * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function setup() { * image(img, 0, 0); * var c = get(); * image(c, width / 2, 0); * } * *
* *
* * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * function setup() { * image(img, 0, 0); * var c = get(50, 90); * fill(c); * noStroke(); * rect(25, 25, 50, 50); * } * *
* * @alt * 2 images of the rocky mountains, side-by-side * Image of the rocky mountains with 50x50 green rect in center of canvas * */ p5.prototype.get = function(x, y, w, h) { return this._renderer.get(x, y, w, h); }; /** * Loads the pixel data for the display window into the pixels[] array. This * function must always be called before reading from or writing to pixels[]. * Note that only changes made with set() or direct manipulation of pixels[] * will occur. * * @method loadPixels * @example *
* * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * image(img, 0, 0); * var d = pixelDensity(); * var halfImage = 4 * (img.width * d) * (img.height * d / 2); * loadPixels(); * for (var i = 0; i < halfImage; i++) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); * } * *
* * @alt * two images of the rocky mountains. one on top, one on bottom of canvas. * */ p5.prototype.loadPixels = function() { p5._validateParameters('loadPixels', arguments); this._renderer.loadPixels(); }; /** *

Changes the color of any pixel, or writes an image directly to the * display window.

*

The x and y parameters specify the pixel to change and the c parameter * specifies the color value. This can be a p5.Color object, or [R, G, B, A] * pixel array. It can also be a single grayscale value. * When setting an image, the x and y parameters define the coordinates for * the upper-left corner of the image, regardless of the current imageMode(). *

*

* After using set(), you must call updatePixels() for your changes to appear. * This should be called once all pixels have been set, and must be called before * calling .get() or drawing the image. *

*

Setting the color of a single pixel with set(x, y) is easy, but not as * fast as putting the data directly into pixels[]. Setting the pixels[] * values directly may be complicated when working with a retina display, * but will perform better when lots of pixels need to be set directly on * every loop.

*

See the reference for pixels[] for more information.

* * @method set * @param {Number} x x-coordinate of the pixel * @param {Number} y y-coordinate of the pixel * @param {Number|Number[]|Object} c insert a grayscale value | a pixel array | * a p5.Color object | a p5.Image to copy * @example *
* * var black = color(0); * set(30, 20, black); * set(85, 20, black); * set(85, 75, black); * set(30, 75, black); * updatePixels(); * *
* *
* * for (var i = 30; i < width - 15; i++) { * for (var j = 20; j < height - 25; j++) { * var c = color(204 - j, 153 - i, 0); * set(i, j, c); * } * } * updatePixels(); * *
* *
* * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * set(0, 0, img); * updatePixels(); * line(0, 0, width, height); * line(0, height, width, 0); * } * *
* * @alt * 4 black points in the shape of a square middle-right of canvas. * square with orangey-brown gradient lightening at bottom right. * image of the rocky mountains. with lines like an 'x' through the center. */ p5.prototype.set = function(x, y, imgOrCol) { this._renderer.set(x, y, imgOrCol); }; /** * Updates the display window with the data in the pixels[] array. * Use in conjunction with loadPixels(). If you're only reading pixels from * the array, there's no need to call updatePixels() — updating is only * necessary to apply changes. updatePixels() should be called anytime the * pixels array is manipulated or set() is called, and only changes made with * set() or direct changes to pixels[] will occur. * * @method updatePixels * @param {Number} [x] x-coordinate of the upper-left corner of region * to update * @param {Number} [y] y-coordinate of the upper-left corner of region * to update * @param {Number} [w] width of region to update * @param {Number} [h] height of region to update * @example *
* * var img; * function preload() { * img = loadImage('assets/rockies.jpg'); * } * * function setup() { * image(img, 0, 0); * var d = pixelDensity(); * var halfImage = 4 * (img.width * d) * (img.height * d / 2); * loadPixels(); * for (var i = 0; i < halfImage; i++) { * pixels[i + halfImage] = pixels[i]; * } * updatePixels(); * } * *
* @alt * two images of the rocky mountains. one on top, one on bottom of canvas. */ p5.prototype.updatePixels = function(x, y, w, h) { p5._validateParameters('updatePixels', arguments); // graceful fail - if loadPixels() or set() has not been called, pixel // array will be empty, ignore call to updatePixels() if (this.pixels.length === 0) { return; } this._renderer.updatePixels(x, y, w, h); }; module.exports = p5; },{"../color/p5.Color":16,"../core/core":22,"./filters":41}],46:[function(_dereq_,module,exports){ /** * @module IO * @submodule Input * @for p5 * @requires core */ /* globals Request: false */ /* globals Headers: false */ 'use strict'; var p5 = _dereq_('../core/core'); _dereq_('whatwg-fetch'); _dereq_('es6-promise').polyfill(); var fetchJsonp = _dereq_('fetch-jsonp'); _dereq_('../core/error_helpers'); /** * Loads a JSON file from a file or a URL, and returns an Object. * Note that even if the JSON file contains an Array, an Object will be * returned with index numbers as keys. * * This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. JSONP is supported via a polyfill and you * can pass in as the second argument an object with definitions of the json * callback following the syntax specified here. * * @method loadJSON * @param {String} path name of the file or url to load * @param {Object} [jsonpOptions] options object for jsonp related settings * @param {String} [datatype] "json" or "jsonp" * @param {function} [callback] function to be executed after * loadJSON() completes, data is passed * in as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Object|Array} JSON data * @example * *

Calling loadJSON() inside preload() guarantees to complete the * operation before setup() and draw() are called.

* *
* // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * var earthquakes; * function preload() { * // Get the most recent earthquake in the database * var url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' + * 'summary/all_day.geojson'; * earthquakes = loadJSON(url); * } * * function setup() { * noLoop(); * } * * function draw() { * background(200); * // Get the magnitude and name of the earthquake out of the loaded JSON * var earthquakeMag = earthquakes.features[0].properties.mag; * var earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); * } *
* * *

Outside of preload(), you may supply a callback function to handle the * object:

*
* function setup() { * noLoop(); * var url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/' + * 'summary/all_day.geojson'; * loadJSON(url, drawEarthquake); * } * * function draw() { * background(200); * } * * function drawEarthquake(earthquakes) { * // Get the magnitude and name of the earthquake out of the loaded JSON * var earthquakeMag = earthquakes.features[0].properties.mag; * var earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); * } *
* * @alt * 50x50 ellipse that changes from black to white depending on the current humidity * 50x50 ellipse that changes from black to white depending on the current humidity * */ /** * @method loadJSON * @param {String} path * @param {String} datatype * @param {function} [callback] * @param {function} [errorCallback] * @return {Object|Array} */ /** * @method loadJSON * @param {String} path * @param {function} callback * @param {function} [errorCallback] * @return {Object|Array} */ p5.prototype.loadJSON = function() { p5._validateParameters('loadJSON', arguments); var path = arguments[0]; var callback; var errorCallback; var options; var ret = {}; // object needed for preload var t = 'json'; // check for explicit data type argument for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (typeof arg === 'string') { if (arg === 'jsonp' || arg === 'json') { t = arg; } } else if (typeof arg === 'function') { if (!callback) { callback = arg; } else { errorCallback = arg; } } else if (typeof arg === 'object' && arg.hasOwnProperty('jsonpCallback')) { t = 'jsonp'; options = arg; } } var self = this; this.httpDo( path, 'GET', options, t, function(resp) { for (var k in resp) { ret[k] = resp[k]; } if (typeof callback !== 'undefined') { callback(resp); } self._decrementPreload(); }, errorCallback ); return ret; }; /** * Reads the contents of a file and creates a String array of its individual * lines. If the name of the file is used as the parameter, as in the above * example, the file must be located in the sketch directory/folder. *

* Alternatively, the file maybe be loaded from anywhere on the local * computer using an absolute path (something that starts with / on Unix and * Linux, or a drive letter on Windows), or the filename parameter can be a * URL for a file found on a network. *

* This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. * * @method loadStrings * @param {String} filename name of the file or url to load * @param {function} [callback] function to be executed after loadStrings() * completes, Array is passed in as first * argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {String[]} Array of Strings * @example * *

Calling loadStrings() inside preload() guarantees to complete the * operation before setup() and draw() are called.

* *
* var result; * function preload() { * result = loadStrings('assets/test.txt'); * } * function setup() { * background(200); * var ind = floor(random(result.length)); * text(result[ind], 10, 10, 80, 80); * } *
* *

Outside of preload(), you may supply a callback function to handle the * object:

* *
* function setup() { * loadStrings('assets/test.txt', pickString); * } * * function pickString(result) { * background(200); * var ind = floor(random(result.length)); * text(result[ind], 10, 10, 80, 80); * } *
* * @alt * randomly generated text from a file, for example "i smell like butter" * randomly generated text from a file, for example "i have three feet" * */ p5.prototype.loadStrings = function() { p5._validateParameters('loadStrings', arguments); var ret = []; var callback, errorCallback; for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (typeof arg === 'function') { if (typeof callback === 'undefined') { callback = arg; } else if (typeof errorCallback === 'undefined') { errorCallback = arg; } } } var self = this; p5.prototype.httpDo.call( this, arguments[0], 'GET', 'text', function(data) { var arr = data.match(/[^\r\n]+/g); for (var k in arr) { ret[k] = arr[k]; } if (typeof callback !== 'undefined') { callback(ret); } self._decrementPreload(); }, errorCallback ); return ret; }; /** *

Reads the contents of a file or URL and creates a p5.Table object with * its values. If a file is specified, it must be located in the sketch's * "data" folder. The filename parameter can also be a URL to a file found * online. By default, the file is assumed to be comma-separated (in CSV * format). Table only looks for a header row if the 'header' option is * included.

* *

Possible options include: *

    *
  • csv - parse the table as comma-separated values
  • *
  • tsv - parse the table as tab-separated values
  • *
  • header - this table has a header (title) row
  • *
*

* *

When passing in multiple options, pass them in as separate parameters, * seperated by commas. For example: *

* * loadTable('my_csv_file.csv', 'csv', 'header'); * *

* *

All files loaded and saved use UTF-8 encoding.

* *

This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. Calling loadTable() inside preload() * guarantees to complete the operation before setup() and draw() are called. *

Outside of preload(), you may supply a callback function to handle the * object:

*

* * @method loadTable * @param {String} filename name of the file or URL to load * @param {String} options "header" "csv" "tsv" * @param {function} [callback] function to be executed after * loadTable() completes. On success, the * Table object is passed in as the * first argument. * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Object} Table object containing data * * @example *
* * // Given the following CSV file called "mammals.csv" * // located in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * //the file can be remote * //table = loadTable("http://p5js.org/reference/assets/mammals.csv", * // "csv", "header"); * } * * function setup() { * //count the columns * print(table.getRowCount() + ' total rows in table'); * print(table.getColumnCount() + ' total columns in table'); * * print(table.getColumn('name')); * //["Goat", "Leopard", "Zebra"] * * //cycle through the table * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) { * print(table.getString(r, c)); * } * } * *
* * @alt * randomly generated text from a file, for example "i smell like butter" * randomly generated text from a file, for example "i have three feet" * */ /** * @method loadTable * @param {String} filename * @param {function} [callback] * @param {function} [errorCallback] * @return {Object} */ p5.prototype.loadTable = function(path) { var callback; var errorCallback; var options = []; var header = false; var ext = path.substring(path.lastIndexOf('.') + 1, path.length); var sep = ','; var separatorSet = false; if (ext === 'tsv') { //Only need to check extension is tsv because csv is default sep = '\t'; } for (var i = 1; i < arguments.length; i++) { if (typeof arguments[i] === 'function') { if (typeof callback === 'undefined') { callback = arguments[i]; } else if (typeof errorCallback === 'undefined') { errorCallback = arguments[i]; } } else if (typeof arguments[i] === 'string') { options.push(arguments[i]); if (arguments[i] === 'header') { header = true; } if (arguments[i] === 'csv') { if (separatorSet) { throw new Error('Cannot set multiple separator types.'); } else { sep = ','; separatorSet = true; } } else if (arguments[i] === 'tsv') { if (separatorSet) { throw new Error('Cannot set multiple separator types.'); } else { sep = '\t'; separatorSet = true; } } } } var t = new p5.Table(); var self = this; this.httpDo( path, 'GET', 'text', function(resp) { var state = {}; // define constants var PRE_TOKEN = 0, MID_TOKEN = 1, POST_TOKEN = 2, POST_RECORD = 4; var QUOTE = '"', CR = '\r', LF = '\n'; var records = []; var offset = 0; var currentRecord = null; var currentChar; var tokenBegin = function() { state.currentState = PRE_TOKEN; state.token = ''; }; var tokenEnd = function() { currentRecord.push(state.token); tokenBegin(); }; var recordBegin = function() { state.escaped = false; currentRecord = []; tokenBegin(); }; var recordEnd = function() { state.currentState = POST_RECORD; records.push(currentRecord); currentRecord = null; }; for (;;) { currentChar = resp[offset++]; // EOF if (currentChar == null) { if (state.escaped) { throw new Error('Unclosed quote in file.'); } if (currentRecord) { tokenEnd(); recordEnd(); break; } } if (currentRecord === null) { recordBegin(); } // Handle opening quote if (state.currentState === PRE_TOKEN) { if (currentChar === QUOTE) { state.escaped = true; state.currentState = MID_TOKEN; continue; } state.currentState = MID_TOKEN; } // mid-token and escaped, look for sequences and end quote if (state.currentState === MID_TOKEN && state.escaped) { if (currentChar === QUOTE) { if (resp[offset] === QUOTE) { state.token += QUOTE; offset++; } else { state.escaped = false; state.currentState = POST_TOKEN; } } else if (currentChar === CR) { continue; } else { state.token += currentChar; } continue; } // fall-through: mid-token or post-token, not escaped if (currentChar === CR) { if (resp[offset] === LF) { offset++; } tokenEnd(); recordEnd(); } else if (currentChar === LF) { tokenEnd(); recordEnd(); } else if (currentChar === sep) { tokenEnd(); } else if (state.currentState === MID_TOKEN) { state.token += currentChar; } } // set up column names if (header) { t.columns = records.shift(); } else { for (i = 0; i < records[0].length; i++) { t.columns[i] = 'null'; } } var row; for (i = 0; i < records.length; i++) { //Handles row of 'undefined' at end of some CSVs if (records[i].length === 1) { if (records[i][0] === 'undefined' || records[i][0] === '') { continue; } } row = new p5.TableRow(); row.arr = records[i]; row.obj = makeObject(records[i], t.columns); t.addRow(row); } if (typeof callback === 'function') { callback(t); } self._decrementPreload(); }, function(err) { // Error handling p5._friendlyFileLoadError(2, path); if (errorCallback) { errorCallback(err); } else { throw err; } } ); return t; }; // helper function to turn a row into a JSON object function makeObject(row, headers) { var ret = {}; headers = headers || []; if (typeof headers === 'undefined') { for (var j = 0; j < row.length; j++) { headers[j.toString()] = j; } } for (var i = 0; i < headers.length; i++) { var key = headers[i]; var val = row[i]; ret[key] = val; } return ret; } function parseXML(two) { var one = new p5.XML(); var children = two.childNodes; if (children && children.length) { for (var i = 0; i < children.length; i++) { var node = parseXML(children[i]); one.addChild(node); } one.setName(two.nodeName); one._setCont(two.textContent); one._setAttributes(two); for (var j = 0; j < one.children.length; j++) { one.children[j].parent = one; } return one; } else { one.setName(two.nodeName); one._setCont(two.textContent); one._setAttributes(two); return one; } } /** * Reads the contents of a file and creates an XML object with its values. * If the name of the file is used as the parameter, as in the above example, * the file must be located in the sketch directory/folder. * * Alternatively, the file maybe be loaded from anywhere on the local * computer using an absolute path (something that starts with / on Unix and * Linux, or a drive letter on Windows), or the filename parameter can be a * URL for a file found on a network. * * This method is asynchronous, meaning it may not finish before the next * line in your sketch is executed. Calling loadXML() inside preload() * guarantees to complete the operation before setup() and draw() are called. * * Outside of preload(), you may supply a callback function to handle the * object. * * @method loadXML * @param {String} filename name of the file or URL to load * @param {function} [callback] function to be executed after loadXML() * completes, XML object is passed in as * first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @return {Object} XML object containing data * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var children = xml.getChildren('animal'); * * for (var i = 0; i < children.length; i++) { * var id = children[i].getNum('id'); * var coloring = children[i].getString('species'); * var name = children[i].getContent(); * print(id + ', ' + coloring + ', ' + name); * } * } * * // Sketch prints: * // 0, Capra hircus, Goat * // 1, Panthera pardus, Leopard * // 2, Equus zebra, Zebra *
* * @alt * no image displayed * */ p5.prototype.loadXML = function() { var ret = {}; var callback, errorCallback; for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (typeof arg === 'function') { if (typeof callback === 'undefined') { callback = arg; } else if (typeof errorCallback === 'undefined') { errorCallback = arg; } } } var self = this; this.httpDo( arguments[0], 'GET', 'xml', function(xml) { for (var key in xml) { ret[key] = xml[key]; } if (typeof callback !== 'undefined') { callback(ret); } self._decrementPreload(); }, errorCallback ); return ret; }; /** * @method loadBytes * @param {string} file name of the file or URL to load * @param {function} [callback] function to be executed after loadBytes() * completes * @param {function} [errorCallback] function to be executed if there * is an error * @returns {Object} an object whose 'bytes' property will be the loaded buffer * * @example *
* var data; * * function preload() { * data = loadBytes('assets/mammals.xml'); * } * * function setup() { * for (var i = 0; i < 5; i++) { * console.log(data.bytes[i].toString(16)); * } * } *
* * @alt * no image displayed * */ p5.prototype.loadBytes = function(file, callback, errorCallback) { var ret = {}; var self = this; this.httpDo( file, 'GET', 'arrayBuffer', function(arrayBuffer) { ret.bytes = new Uint8Array(arrayBuffer); if (typeof callback === 'function') { callback(ret); } self._decrementPreload(); }, errorCallback ); return ret; }; /** * Method for executing an HTTP GET request. If data type is not specified, * p5 will try to guess based on the URL, defaulting to text. This is equivalent to * calling httpDo(path, 'GET'). The 'binary' datatype will return * a Blob object, and the 'arrayBuffer' datatype will return an ArrayBuffer * which can be used to initialize typed arrays (such as Uint8Array). * * @method httpGet * @param {String} path name of the file or url to load * @param {String} [datatype] "json", "jsonp", "binary", "arrayBuffer", * "xml", or "text" * @param {Object|Boolean} [data] param data passed sent with request * @param {function} [callback] function to be executed after * httpGet() completes, data is passed in * as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * @example *
* // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * var earthquakes; * function preload() { * // Get the most recent earthquake in the database * var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?' + * 'format=geojson&limit=1&orderby=time'; * httpGet(url, 'jsonp', false, function(response) { * // when the HTTP request completes, populate the variable that holds the * // earthquake data used in the visualization. * earthquakes = response; * }); * } * * function draw() { * if (!earthquakes) { * // Wait until the earthquake data has loaded before drawing. * return; * } * background(200); * // Get the magnitude and name of the earthquake out of the loaded JSON * var earthquakeMag = earthquakes.features[0].properties.mag; * var earthquakeName = earthquakes.features[0].properties.place; * ellipse(width / 2, height / 2, earthquakeMag * 10, earthquakeMag * 10); * textAlign(CENTER); * text(earthquakeName, 0, height - 30, width, 30); * noLoop(); * } *
*/ /** * @method httpGet * @param {String} path * @param {Object|Boolean} data * @param {function} [callback] * @param {function} [errorCallback] */ /** * @method httpGet * @param {String} path * @param {function} callback * @param {function} [errorCallback] */ p5.prototype.httpGet = function() { p5._validateParameters('httpGet', arguments); var args = Array.prototype.slice.call(arguments); args.splice(1, 0, 'GET'); p5.prototype.httpDo.apply(this, args); }; /** * Method for executing an HTTP POST request. If data type is not specified, * p5 will try to guess based on the URL, defaulting to text. This is equivalent to * calling httpDo(path, 'POST'). * * @method httpPost * @param {String} path name of the file or url to load * @param {String} [datatype] "json", "jsonp", "xml", or "text". * If omitted, httpPost() will guess. * @param {Object|Boolean} [data] param data passed sent with request * @param {function} [callback] function to be executed after * httpPost() completes, data is passed in * as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * * @example *
* * // Examples use jsonplaceholder.typicode.com for a Mock Data API * * var url = 'https://jsonplaceholder.typicode.com/posts'; * var postData = { userId: 1, title: 'p5 Clicked!', body: 'p5.js is way cool.' }; * * function setup() { * createCanvas(800, 800); * } * * function mousePressed() { * // Pick new random color values * var r = random(255); * var g = random(255); * var b = random(255); * * httpPost(url, 'json', postData, function(result) { * strokeWeight(2); * stroke(r, g, b); * fill(r, g, b, 127); * ellipse(mouseX, mouseY, 200, 200); * text(result.body, mouseX, mouseY); * }); * } * *
* * *
* var url = 'https://invalidURL'; // A bad URL that will cause errors * var postData = { title: 'p5 Clicked!', body: 'p5.js is way cool.' }; * * function setup() { * createCanvas(800, 800); * } * * function mousePressed() { * // Pick new random color values * var r = random(255); * var g = random(255); * var b = random(255); * * httpPost( * url, * 'json', * postData, * function(result) { * // ... won't be called * }, * function(error) { * strokeWeight(2); * stroke(r, g, b); * fill(r, g, b, 127); * text(error.toString(), mouseX, mouseY); * } * ); * } *
* */ /** * @method httpPost * @param {String} path * @param {Object|Boolean} data * @param {function} [callback] * @param {function} [errorCallback] */ /** * @method httpPost * @param {String} path * @param {function} callback * @param {function} [errorCallback] */ p5.prototype.httpPost = function() { p5._validateParameters('httpPost', arguments); var args = Array.prototype.slice.call(arguments); args.splice(1, 0, 'POST'); p5.prototype.httpDo.apply(this, args); }; /** * Method for executing an HTTP request. If data type is not specified, * p5 will try to guess based on the URL, defaulting to text.

* For more advanced use, you may also pass in the path as the first argument * and a object as the second argument, the signature follows the one specified * in the Fetch API specification. * * @method httpDo * @param {String} path name of the file or url to load * @param {String} [method] either "GET", "POST", or "PUT", * defaults to "GET" * @param {String} [datatype] "json", "jsonp", "xml", or "text" * @param {Object} [data] param data passed sent with request * @param {function} [callback] function to be executed after * httpGet() completes, data is passed in * as first argument * @param {function} [errorCallback] function to be executed if * there is an error, response is passed * in as first argument * * * @example *
* * // Examples use USGS Earthquake API: * // https://earthquake.usgs.gov/fdsnws/event/1/#methods * * // displays an animation of all USGS earthquakes * var earthquakes; * var eqFeatureIndex = 0; * * function preload() { * var url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson'; * httpDo( * url, * { * method: 'GET', * // Other Request options, like special headers for apis * headers: { authorization: 'Bearer secretKey' } * }, * function(res) { * earthquakes = res; * } * ); * } * * function draw() { * // wait until the data is loaded * if (!earthquakes || !earthquakes.features[eqFeatureIndex]) { * return; * } * clear(); * * var feature = earthquakes.features[eqFeatureIndex]; * var mag = feature.properties.mag; * var rad = mag / 11 * ((width + height) / 2); * fill(255, 0, 0, 100); * ellipse(width / 2 + random(-2, 2), height / 2 + random(-2, 2), rad, rad); * * if (eqFeatureIndex >= earthquakes.features.length) { * eqFeatureIndex = 0; * } else { * eqFeatureIndex += 1; * } * } * *
*/ /** * @method httpDo * @param {String} path * @param {Object} options Request object options as documented in the * "fetch" API * reference * @param {function} [callback] * @param {function} [errorCallback] */ p5.prototype.httpDo = function() { var type; var callback; var errorCallback; var request; var jsonpOptions = {}; var cbCount = 0; var contentType = 'text/plain'; // Trim the callbacks off the end to get an idea of how many arguments are passed for (var i = arguments.length - 1; i > 0; i--) { if (typeof arguments[i] === 'function') { cbCount++; } else { break; } } // The number of arguments minus callbacks var argsCount = arguments.length - cbCount; var path = arguments[0]; if ( argsCount === 2 && typeof path === 'string' && typeof arguments[1] === 'object' ) { // Intended for more advanced use, pass in Request parameters directly request = new Request(path, arguments[1]); callback = arguments[2]; errorCallback = arguments[3]; } else { // Provided with arguments var method = 'GET'; var data; for (var j = 1; j < arguments.length; j++) { var a = arguments[j]; if (typeof a === 'string') { if (a === 'GET' || a === 'POST' || a === 'PUT' || a === 'DELETE') { method = a; } else if ( a === 'json' || a === 'jsonp' || a === 'binary' || a === 'arrayBuffer' || a === 'xml' || a === 'text' ) { type = a; } else { data = a; } } else if (typeof a === 'number') { data = a.toString(); } else if (typeof a === 'object') { if (a.hasOwnProperty('jsonpCallback')) { for (var attr in a) { jsonpOptions[attr] = a[attr]; } } else { data = JSON.stringify(a); contentType = 'application/json'; } } else if (typeof a === 'function') { if (!callback) { callback = a; } else { errorCallback = a; } } } request = new Request(path, { method: method, mode: 'cors', body: data, headers: new Headers({ 'Content-Type': contentType }) }); } // do some sort of smart type checking if (!type) { if (path.indexOf('json') !== -1) { type = 'json'; } else if (path.indexOf('xml') !== -1) { type = 'xml'; } else { type = 'text'; } } (type === 'jsonp' ? fetchJsonp(path, jsonpOptions) : fetch(request)) .then(function(res) { if (!res.ok) throw res; switch (type) { case 'json': return res.json(); case 'binary': return res.blob(); case 'arrayBuffer': return res.arrayBuffer(); case 'xml': return res.text().then(function(text) { var parser = new DOMParser(); var xml = parser.parseFromString(text, 'text/xml'); return parseXML(xml.documentElement); }); default: return res.text(); } }) .then(callback || function() {}) .catch(errorCallback || console.error); }; /** * @module IO * @submodule Output * @for p5 */ window.URL = window.URL || window.webkitURL; // private array of p5.PrintWriter objects p5.prototype._pWriters = []; /** * @method createWriter * @param {String} name name of the file to be created * @param {String} [extension] * @return {p5.PrintWriter} * @example *
* * createButton('save') * .position(10, 10) * .mousePressed(function() { * var writer = createWriter('squares.txt'); * for (var i = 0; i < 10; i++) { * writer.print(i * i); * } * writer.close(); * writer.clear(); * }); * *
*/ p5.prototype.createWriter = function(name, extension) { var newPW; // check that it doesn't already exist for (var i in p5.prototype._pWriters) { if (p5.prototype._pWriters[i].name === name) { // if a p5.PrintWriter w/ this name already exists... // return p5.prototype._pWriters[i]; // return it w/ contents intact. // or, could return a new, empty one with a unique name: newPW = new p5.PrintWriter(name + this.millis(), extension); p5.prototype._pWriters.push(newPW); return newPW; } } newPW = new p5.PrintWriter(name, extension); p5.prototype._pWriters.push(newPW); return newPW; }; /** * @class p5.PrintWriter * @param {String} filename * @param {String} [extension] */ p5.PrintWriter = function(filename, extension) { var self = this; this.name = filename; this.content = ''; //Changed to write because it was being overloaded by function below. /** * Writes data to the PrintWriter stream * @method write * @param {Array} data all data to be written by the PrintWriter * @example *
* * // creates a file called 'newFile.txt' * var writer = createWriter('newFile.txt'); * // write 'Hello world!'' to the file * writer.write(['Hello world!']); * // close the PrintWriter and save the file * writer.close(); * *
*
* * // creates a file called 'newFile2.txt' * var writer = createWriter('newFile2.txt'); * // write 'apples,bananas,123' to the file * writer.write(['apples', 'bananas', 123]); * // close the PrintWriter and save the file * writer.close(); * *
*
* * // creates a file called 'newFile3.txt' * var writer = createWriter('newFile3.txt'); * // write 'My name is: Teddy' to the file * writer.write('My name is:'); * writer.write(' Teddy'); * // close the PrintWriter and save the file * writer.close(); * *
*/ this.write = function(data) { this.content += data; }; /** * Writes data to the PrintWriter stream, and adds a new line at the end * @method print * @param {Array} data all data to be printed by the PrintWriter * @example *
* * // creates a file called 'newFile.txt' * var writer = createWriter('newFile.txt'); * // creates a file containing * // My name is: * // Teddy * writer.print('My name is:'); * writer.print('Teddy'); * // close the PrintWriter and save the file * writer.close(); * *
*
* * var writer; * * function setup() { * createCanvas(400, 400); * // create a PrintWriter * writer = createWriter('newFile.txt'); * } * * function draw() { * // print all mouseX and mouseY coordinates to the stream * writer.print([mouseX, mouseY]); * } * * function mouseClicked() { * // close the PrintWriter and save the file * writer.close(); * } * *
*/ this.print = function(data) { this.content += data + '\n'; }; /** * Clears the data already written to the PrintWriter object * @method clear * @example *
* // create writer object * var writer = createWriter('newFile.txt'); * writer.write(['clear me']); * // clear writer object here * writer.clear(); * // close writer * writer.close(); *
* */ this.clear = function() { this.content = ''; }; /** * Closes the PrintWriter * @method close * @example *
* * // create a file called 'newFile.txt' * var writer = createWriter('newFile.txt'); * // close the PrintWriter and save the file * writer.close(); * *
*
* * // create a file called 'newFile2.txt' * var writer = createWriter('newFile2.txt'); * // write some data to the file * writer.write([100, 101, 102]); * // close the PrintWriter and save the file * writer.close(); * *
*/ this.close = function() { // convert String to Array for the writeFile Blob var arr = []; arr.push(this.content); p5.prototype.writeFile(arr, filename, extension); // remove from _pWriters array and delete self for (var i in p5.prototype._pWriters) { if (p5.prototype._pWriters[i].name === this.name) { // remove from _pWriters array p5.prototype._pWriters.splice(i, 1); } } self.clear(); self = {}; }; }; /** * @module IO * @submodule Output * @for p5 */ // object, filename, options --> saveJSON, saveStrings, // filename, [extension] [canvas] --> saveImage /** *

Save an image, text, json, csv, wav, or html. Prompts download to * the client's computer. Note that it is not recommended to call save() * within draw if it's looping, as the save() function will open a new save * dialog every frame.

*

The default behavior is to save the canvas as an image. You can * optionally specify a filename. * For example:

*

 * save();
 * save('myCanvas.jpg'); // save a specific canvas with a filename
 * 
* *

Alternately, the first parameter can be a pointer to a canvas * p5.Element, an Array of Strings, * an Array of JSON, a JSON object, a p5.Table, a p5.Image, or a * p5.SoundFile (requires p5.sound). The second parameter is a filename * (including extension). The third parameter is for options specific * to this type of object. This method will save a file that fits the * given paramaters. For example:

* *

 * // Saves canvas as an image
 * save('myCanvas.jpg');
 *
 * // Saves pImage as a png image
 * var img = createImage(10, 10);
 * save(img, 'my.png');
 *
 * // Saves canvas as an image
 * var cnv = createCanvas(100, 100);
 * save(cnv, 'myCanvas.jpg');
 *
 * // Saves p5.Renderer object as an image
 * var gb = createGraphics(100, 100);
 * save(gb, 'myGraphics.jpg');
 *
 * var myTable = new p5.Table();
 *
 * // Saves table as html file
 * save(myTable, 'myTable.html');
 *
 * // Comma Separated Values
 * save(myTable, 'myTable.csv');
 *
 * // Tab Separated Values
 * save(myTable, 'myTable.tsv');
 *
 * var myJSON = { a: 1, b: true };
 *
 * // Saves pretty JSON
 * save(myJSON, 'my.json');
 *
 * // Optimizes JSON filesize
 * save(myJSON, 'my.json', true);
 *
 * // Saves array of strings to a text file with line breaks after each item
 * var arrayOfStrings = ['a', 'b'];
 * save(arrayOfStrings, 'my.txt');
 * 
* * @method save * @param {Object|String} [objectOrFilename] If filename is provided, will * save canvas as an image with * either png or jpg extension * depending on the filename. * If object is provided, will * save depending on the object * and filename (see examples * above). * @param {String} [filename] If an object is provided as the first * parameter, then the second parameter * indicates the filename, * and should include an appropriate * file extension (see examples above). * @param {Boolean|String} [options] Additional options depend on * filetype. For example, when saving JSON, * true indicates that the * output will be optimized for filesize, * rather than readability. */ p5.prototype.save = function(object, _filename, _options) { // parse the arguments and figure out which things we are saving var args = arguments; // ================================================= // OPTION 1: saveCanvas... // if no arguments are provided, save canvas var cnv = this._curElement.elt; if (args.length === 0) { p5.prototype.saveCanvas(cnv); return; } else if (args[0] instanceof p5.Renderer || args[0] instanceof p5.Graphics) { // otherwise, parse the arguments // if first param is a p5Graphics, then saveCanvas p5.prototype.saveCanvas(args[0].elt, args[1], args[2]); return; } else if (args.length === 1 && typeof args[0] === 'string') { // if 1st param is String and only one arg, assume it is canvas filename p5.prototype.saveCanvas(cnv, args[0]); } else { // ================================================= // OPTION 2: extension clarifies saveStrings vs. saveJSON var extension = _checkFileExtension(args[1], args[2])[1]; switch (extension) { case 'json': p5.prototype.saveJSON(args[0], args[1], args[2]); return; case 'txt': p5.prototype.saveStrings(args[0], args[1], args[2]); return; // ================================================= // OPTION 3: decide based on object... default: if (args[0] instanceof Array) { p5.prototype.saveStrings(args[0], args[1], args[2]); } else if (args[0] instanceof p5.Table) { p5.prototype.saveTable(args[0], args[1], args[2]); } else if (args[0] instanceof p5.Image) { p5.prototype.saveCanvas(args[0].canvas, args[1]); } else if (args[0] instanceof p5.SoundFile) { p5.prototype.saveSound(args[0], args[1], args[2], args[3]); } } } }; /** * Writes the contents of an Array or a JSON object to a .json file. * The file saving process and location of the saved file will * vary between web browsers. * * @method saveJSON * @param {Array|Object} json * @param {String} filename * @param {Boolean} [optimize] If true, removes line breaks * and spaces from the output * file to optimize filesize * (but not readability). * @example *
* var json = {}; // new JSON Object * * json.id = 0; * json.species = 'Panthera leo'; * json.name = 'Lion'; * * createButton('save') * .position(10, 10) * .mousePressed(function() { * saveJSON(json, 'lion.json'); * }); * * // saves the following to a file called "lion.json": * // { * // "id": 0, * // "species": "Panthera leo", * // "name": "Lion" * // } *
* * @alt * no image displayed * */ p5.prototype.saveJSON = function(json, filename, opt) { p5._validateParameters('saveJSON', arguments); var stringify; if (opt) { stringify = JSON.stringify(json); } else { stringify = JSON.stringify(json, undefined, 2); } this.saveStrings(stringify.split('\n'), filename, 'json'); }; p5.prototype.saveJSONObject = p5.prototype.saveJSON; p5.prototype.saveJSONArray = p5.prototype.saveJSON; /** * Writes an array of Strings to a text file, one line per String. * The file saving process and location of the saved file will * vary between web browsers. * * @method saveStrings * @param {String[]} list string array to be written * @param {String} filename filename for output * @param {String} [extension] the filename's extension * @example *
* var words = 'apple bear cat dog'; * * // .split() outputs an Array * var list = split(words, ' '); * * createButton('save') * .position(10, 10) * .mousePressed(function() { * saveStrings(list, 'nouns.txt'); * }); * * // Saves the following to a file called 'nouns.txt': * // * // apple * // bear * // cat * // dog *
* * @alt * no image displayed * */ p5.prototype.saveStrings = function(list, filename, extension) { p5._validateParameters('saveStrings', arguments); var ext = extension || 'txt'; var pWriter = this.createWriter(filename, ext); for (var i = 0; i < list.length; i++) { if (i < list.length - 1) { pWriter.print(list[i]); } else { pWriter.print(list[i]); } } pWriter.close(); pWriter.clear(); }; // ======= // HELPERS // ======= function escapeHelper(content) { return content .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } /** * Writes the contents of a Table object to a file. Defaults to a * text file with comma-separated-values ('csv') but can also * use tab separation ('tsv'), or generate an HTML table ('html'). * The file saving process and location of the saved file will * vary between web browsers. * * @method saveTable * @param {p5.Table} Table the Table object to save to a file * @param {String} filename the filename to which the Table should be saved * @param {String} [options] can be one of "tsv", "csv", or "html" * @example *
* var table; * * function setup() { * table = new p5.Table(); * * table.addColumn('id'); * table.addColumn('species'); * table.addColumn('name'); * * var newRow = table.addRow(); * newRow.setNum('id', table.getRowCount() - 1); * newRow.setString('species', 'Panthera leo'); * newRow.setString('name', 'Lion'); * * // To save, un-comment next line then click 'run' * // saveTable(table, 'new.csv'); * } * * // Saves the following to a file called 'new.csv': * // id,species,name * // 0,Panthera leo,Lion *
* * @alt * no image displayed * */ p5.prototype.saveTable = function(table, filename, options) { p5._validateParameters('saveTable', arguments); var ext; if (options === undefined) { ext = filename.substring(filename.lastIndexOf('.') + 1, filename.length); } else { ext = options; } var pWriter = this.createWriter(filename, ext); var header = table.columns; var sep = ','; // default to CSV if (ext === 'tsv') { sep = '\t'; } if (ext !== 'html') { // make header if it has values if (header[0] !== '0') { for (var h = 0; h < header.length; h++) { if (h < header.length - 1) { pWriter.write(header[h] + sep); } else { pWriter.write(header[h]); } } pWriter.write('\n'); } // make rows for (var i = 0; i < table.rows.length; i++) { var j; for (j = 0; j < table.rows[i].arr.length; j++) { if (j < table.rows[i].arr.length - 1) { pWriter.write(table.rows[i].arr[j] + sep); } else if (i < table.rows.length - 1) { pWriter.write(table.rows[i].arr[j]); } else { pWriter.write(table.rows[i].arr[j]); } } pWriter.write('\n'); } } else { // otherwise, make HTML pWriter.print(''); pWriter.print(''); var str = ' '); pWriter.print(''); pWriter.print(' '); // make header if it has values if (header[0] !== '0') { pWriter.print(' '); for (var k = 0; k < header.length; k++) { var e = escapeHelper(header[k]); pWriter.print(' '); } pWriter.print(' '); } // make rows for (var row = 0; row < table.rows.length; row++) { pWriter.print(' '); for (var col = 0; col < table.columns.length; col++) { var entry = table.rows[row].getString(col); var htmlEntry = escapeHelper(entry); pWriter.print(' '); } pWriter.print(' '); } pWriter.print('
' + e); pWriter.print('
' + htmlEntry); pWriter.print('
'); pWriter.print(''); pWriter.print(''); } // close and clear the pWriter pWriter.close(); pWriter.clear(); }; // end saveTable() /** * Generate a blob of file data as a url to prepare for download. * Accepts an array of data, a filename, and an extension (optional). * This is a private function because it does not do any formatting, * but it is used by saveStrings, saveJSON, saveTable etc. * * @param {Array} dataToDownload * @param {String} filename * @param {String} [extension] * @private */ p5.prototype.writeFile = function(dataToDownload, filename, extension) { var type = 'application/octet-stream'; if (p5.prototype._isSafari()) { type = 'text/plain'; } var blob = new Blob(dataToDownload, { type: type }); p5.prototype.downloadFile(blob, filename, extension); }; /** * Forces download. Accepts a url to filedata/blob, a filename, * and an extension (optional). * This is a private function because it does not do any formatting, * but it is used by saveStrings, saveJSON, saveTable etc. * * @method downloadFile * @private * @param {String|Blob} data either an href generated by createObjectURL, * or a Blob object containing the data * @param {String} [filename] * @param {String} [extension] */ p5.prototype.downloadFile = function(data, fName, extension) { var fx = _checkFileExtension(fName, extension); var filename = fx[0]; if (data instanceof Blob) { var fileSaver = _dereq_('file-saver'); fileSaver.saveAs(data, filename); return; } var a = document.createElement('a'); a.href = data; a.download = filename; // Firefox requires the link to be added to the DOM before click() a.onclick = function(e) { destroyClickedElement(e); e.stopPropagation(); }; a.style.display = 'none'; document.body.appendChild(a); // Safari will open this file in the same page as a confusing Blob. if (p5.prototype._isSafari()) { var aText = 'Hello, Safari user! To download this file...\n'; aText += '1. Go to File --> Save As.\n'; aText += '2. Choose "Page Source" as the Format.\n'; aText += '3. Name it with this extension: ."' + fx[1] + '"'; alert(aText); } a.click(); }; /** * Returns a file extension, or another string * if the provided parameter has no extension. * * @param {String} filename * @param {String} [extension] * @return {String[]} [fileName, fileExtension] * * @private */ function _checkFileExtension(filename, extension) { if (!extension || extension === true || extension === 'true') { extension = ''; } if (!filename) { filename = 'untitled'; } var ext = ''; // make sure the file will have a name, see if filename needs extension if (filename && filename.indexOf('.') > -1) { ext = filename.split('.').pop(); } // append extension if it doesn't exist if (extension) { if (ext !== extension) { ext = extension; filename = filename + '.' + ext; } } return [filename, ext]; } p5.prototype._checkFileExtension = _checkFileExtension; /** * Returns true if the browser is Safari, false if not. * Safari makes trouble for downloading files. * * @return {Boolean} [description] * @private */ p5.prototype._isSafari = function() { var x = Object.prototype.toString.call(window.HTMLElement); return x.indexOf('Constructor') > 0; }; /** * Helper function, a callback for download that deletes * an invisible anchor element from the DOM once the file * has been automatically downloaded. * * @private */ function destroyClickedElement(event) { document.body.removeChild(event.target); } module.exports = p5; },{"../core/core":22,"../core/error_helpers":25,"es6-promise":5,"fetch-jsonp":6,"file-saver":7,"whatwg-fetch":12}],47:[function(_dereq_,module,exports){ /** * @module IO * @submodule Table * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Table Options *

Generic class for handling tabular data, typically from a * CSV, TSV, or other sort of spreadsheet file.

*

CSV files are * * comma separated values, often with the data in quotes. TSV * files use tabs as separators, and usually don't bother with the * quotes.

*

File names should end with .csv if they're comma separated.

*

A rough "spec" for CSV can be found * here.

*

To load files, use the loadTable method.

*

To save tables to your computer, use the save method * or the saveTable method.

* * Possible options include: *
    *
  • csv - parse the table as comma-separated values *
  • tsv - parse the table as tab-separated values *
  • header - this table has a header (title) row *
*/ /** * Table objects store data with multiple rows and columns, much * like in a traditional spreadsheet. Tables can be generated from * scratch, dynamically, or using data from an existing file. * * @class p5.Table * @constructor * @param {p5.TableRow[]} [rows] An array of p5.TableRow objects */ p5.Table = function(rows) { /** * @property columns {String[]} */ this.columns = []; /** * @property rows {p5.TableRow[]} */ this.rows = []; }; /** * Use addRow() to add a new row of data to a p5.Table object. By default, * an empty row is created. Typically, you would store a reference to * the new row in a TableRow object (see newRow in the example above), * and then set individual values using set(). * * If a p5.TableRow object is included as a parameter, then that row is * duplicated and added to the table. * * @method addRow * @param {p5.TableRow} [row] row to be added to the table * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //add a row * var newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Canis Lupus'); * newRow.setString('name', 'Wolf'); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * *
* * @alt * no image displayed * */ p5.Table.prototype.addRow = function(row) { // make sure it is a valid TableRow var r = row || new p5.TableRow(); if (typeof r.arr === 'undefined' || typeof r.obj === 'undefined') { //r = new p5.prototype.TableRow(r); throw 'invalid TableRow: ' + r; } r.table = this; this.rows.push(r); return r; }; /** * Removes a row from the table object. * * @method removeRow * @param {Integer} id ID number of the row to remove * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //remove the first row * table.removeRow(0); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * *
* * @alt * no image displayed * */ p5.Table.prototype.removeRow = function(id) { this.rows[id].table = null; // remove reference to table var chunk = this.rows.splice(id + 1, this.rows.length); this.rows.pop(); this.rows = this.rows.concat(chunk); }; /** * Returns a reference to the specified p5.TableRow. The reference * can then be used to get and set values of the selected row. * * @method getRow * @param {Integer} rowID ID number of the row to get * @return {p5.TableRow} p5.TableRow object * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var row = table.getRow(1); * //print it column by column * //note: a row is an object, not an array * for (var c = 0; c < table.getColumnCount(); c++) { * print(row.getString(c)); * } * } * *
* *@alt * no image displayed * */ p5.Table.prototype.getRow = function(r) { return this.rows[r]; }; /** * Gets all rows from the table. Returns an array of p5.TableRows. * * @method getRows * @return {p5.TableRow[]} Array of p5.TableRows * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * * //warning: rows is an array of objects * for (var r = 0; r < rows.length; r++) { * rows[r].set('name', 'Unicorn'); * } * * //print the results * for (r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * *
* * @alt * no image displayed * */ p5.Table.prototype.getRows = function() { return this.rows; }; /** * Finds the first row in the Table that contains the value * provided, and returns a reference to that row. Even if * multiple rows are possible matches, only the first matching * row is returned. The column to search may be specified by * either its ID or title. * * @method findRow * @param {String} value The value to match * @param {Integer|String} column ID number or title of the * column to search * @return {p5.TableRow} * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //find the animal named zebra * var row = table.findRow('Zebra', 'name'); * //find the corresponding species * print(row.getString('species')); * } * *
* * @alt * no image displayed * */ p5.Table.prototype.findRow = function(value, column) { // try the Object if (typeof column === 'string') { for (var i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column] === value) { return this.rows[i]; } } } else { // try the Array for (var j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column] === value) { return this.rows[j]; } } } // otherwise... return null; }; /** * Finds the rows in the Table that contain the value * provided, and returns references to those rows. Returns an * Array, so for must be used to iterate through all the rows, * as shown in the example above. The column to search may be * specified by either its ID or title. * * @method findRows * @param {String} value The value to match * @param {Integer|String} column ID number or title of the * column to search * @return {p5.TableRow[]} An Array of TableRow objects * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //add another goat * var newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Scape Goat'); * newRow.setString('name', 'Goat'); * * //find the rows containing animals named Goat * var rows = table.findRows('Goat', 'name'); * print(rows.length + ' Goats found'); * } * *
* *@alt * no image displayed * */ p5.Table.prototype.findRows = function(value, column) { var ret = []; if (typeof column === 'string') { for (var i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column] === value) { ret.push(this.rows[i]); } } } else { // try the Array for (var j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column] === value) { ret.push(this.rows[j]); } } } return ret; }; /** * Finds the first row in the Table that matches the regular * expression provided, and returns a reference to that row. * Even if multiple rows are possible matches, only the first * matching row is returned. The column to search may be * specified by either its ID or title. * * @method matchRow * @param {String|RegExp} regexp The regular expression to match * @param {String|Integer} column The column ID (number) or * title (string) * @return {p5.TableRow} TableRow object * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //Search using specified regex on a given column, return TableRow object * var mammal = table.matchRow(new RegExp('ant'), 1); * print(mammal.getString(1)); * //Output "Panthera pardus" * } * *
* */ p5.Table.prototype.matchRow = function(regexp, column) { if (typeof column === 'number') { for (var j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column].match(regexp)) { return this.rows[j]; } } } else { for (var i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column].match(regexp)) { return this.rows[i]; } } } return null; }; /** * Finds the rows in the Table that match the regular expression provided, * and returns references to those rows. Returns an array, so for must be * used to iterate through all the rows, as shown in the example. The * column to search may be specified by either its ID or title. * * @method matchRows * @param {String} regexp The regular expression to match * @param {String|Integer} [column] The column ID (number) or * title (string) * @return {p5.TableRow[]} An Array of TableRow objects * @example *
* * var table; * * function setup() { * table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * * var newRow = table.addRow(); * newRow.setString('name', 'Lion'); * newRow.setString('type', 'Mammal'); * * newRow = table.addRow(); * newRow.setString('name', 'Snake'); * newRow.setString('type', 'Reptile'); * * newRow = table.addRow(); * newRow.setString('name', 'Mosquito'); * newRow.setString('type', 'Insect'); * * newRow = table.addRow(); * newRow.setString('name', 'Lizard'); * newRow.setString('type', 'Reptile'); * * var rows = table.matchRows('R.*', 'type'); * for (var i = 0; i < rows.length; i++) { * print(rows[i].getString('name') + ': ' + rows[i].getString('type')); * } * } * // Sketch prints: * // Snake: Reptile * // Lizard: Reptile * *
*/ p5.Table.prototype.matchRows = function(regexp, column) { var ret = []; if (typeof column === 'number') { for (var j = 0; j < this.rows.length; j++) { if (this.rows[j].arr[column].match(regexp)) { ret.push(this.rows[j]); } } } else { for (var i = 0; i < this.rows.length; i++) { if (this.rows[i].obj[column].match(regexp)) { ret.push(this.rows[i]); } } } return ret; }; /** * Retrieves all values in the specified column, and returns them * as an array. The column may be specified by either its ID or title. * * @method getColumn * @param {String|Number} column String or Number of the column to return * @return {Array} Array of column values * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //getColumn returns an array that can be printed directly * print(table.getColumn('species')); * //outputs ["Capra hircus", "Panthera pardus", "Equus zebra"] * } * *
* *@alt * no image displayed * */ p5.Table.prototype.getColumn = function(value) { var ret = []; if (typeof value === 'string') { for (var i = 0; i < this.rows.length; i++) { ret.push(this.rows[i].obj[value]); } } else { for (var j = 0; j < this.rows.length; j++) { ret.push(this.rows[j].arr[value]); } } return ret; }; /** * Removes all rows from a Table. While all rows are removed, * columns and column titles are maintained. * * @method clearRows * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.clearRows(); * print(table.getRowCount() + ' total rows in table'); * print(table.getColumnCount() + ' total columns in table'); * } * *
* *@alt * no image displayed * */ p5.Table.prototype.clearRows = function() { delete this.rows; this.rows = []; }; /** * Use addColumn() to add a new column to a Table object. * Typically, you will want to specify a title, so the column * may be easily referenced later by name. (If no title is * specified, the new column's title will be null.) * * @method addColumn * @param {String} [title] title of the given column * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.addColumn('carnivore'); * table.set(0, 'carnivore', 'no'); * table.set(1, 'carnivore', 'yes'); * table.set(2, 'carnivore', 'no'); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * *
* *@alt * no image displayed * */ p5.Table.prototype.addColumn = function(title) { var t = title || null; this.columns.push(t); }; /** * Returns the total number of columns in a Table. * * @method getColumnCount * @return {Integer} Number of columns in this table * @example *
* * // given the cvs file "blobs.csv" in /assets directory * // ID, Name, Flavor, Shape, Color * // Blob1, Blobby, Sweet, Blob, Pink * // Blob2, Saddy, Savory, Blob, Blue * * var table; * * function preload() { * table = loadTable('assets/blobs.csv'); * } * * function setup() { * createCanvas(200, 100); * textAlign(CENTER); * background(255); * } * * function draw() { * var numOfColumn = table.getColumnCount(); * text('There are ' + numOfColumn + ' columns in the table.', 100, 50); * } * *
*/ p5.Table.prototype.getColumnCount = function() { return this.columns.length; }; /** * Returns the total number of rows in a Table. * * @method getRowCount * @return {Integer} Number of rows in this table * @example *
* * // given the cvs file "blobs.csv" in /assets directory * // * // ID, Name, Flavor, Shape, Color * // Blob1, Blobby, Sweet, Blob, Pink * // Blob2, Saddy, Savory, Blob, Blue * * var table; * * function preload() { * table = loadTable('assets/blobs.csv'); * } * * function setup() { * createCanvas(200, 100); * textAlign(CENTER); * background(255); * } * * function draw() { * text('There are ' + table.getRowCount() + ' rows in the table.', 100, 50); * } * *
*/ p5.Table.prototype.getRowCount = function() { return this.rows.length; }; /** *

Removes any of the specified characters (or "tokens").

* *

If no column is specified, then the values in all columns and * rows are processed. A specific column may be referenced by * either its ID or title.

* * @method removeTokens * @param {String} chars String listing characters to be removed * @param {String|Integer} [column] Column ID (number) * or name (string) * * @example *
* function setup() { * var table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * * var newRow = table.addRow(); * newRow.setString('name', ' $Lion ,'); * newRow.setString('type', ',,,Mammal'); * * newRow = table.addRow(); * newRow.setString('name', '$Snake '); * newRow.setString('type', ',,,Reptile'); * * table.removeTokens(',$ '); * print(table.getArray()); * } * * // prints: * // 0 "Lion" "Mamal" * // 1 "Snake" "Reptile" *
*/ p5.Table.prototype.removeTokens = function(chars, column) { var escape = function(s) { return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); }; var charArray = []; for (var i = 0; i < chars.length; i++) { charArray.push(escape(chars.charAt(i))); } var regex = new RegExp(charArray.join('|'), 'g'); if (typeof column === 'undefined') { for (var c = 0; c < this.columns.length; c++) { for (var d = 0; d < this.rows.length; d++) { var s = this.rows[d].arr[c]; s = s.replace(regex, ''); this.rows[d].arr[c] = s; this.rows[d].obj[this.columns[c]] = s; } } } else if (typeof column === 'string') { for (var j = 0; j < this.rows.length; j++) { var val = this.rows[j].obj[column]; val = val.replace(regex, ''); this.rows[j].obj[column] = val; var pos = this.columns.indexOf(column); this.rows[j].arr[pos] = val; } } else { for (var k = 0; k < this.rows.length; k++) { var str = this.rows[k].arr[column]; str = str.replace(regex, ''); this.rows[k].arr[column] = str; this.rows[k].obj[this.columns[column]] = str; } } }; /** * Trims leading and trailing whitespace, such as spaces and tabs, * from String table values. If no column is specified, then the * values in all columns and rows are trimmed. A specific column * may be referenced by either its ID or title. * * @method trim * @param {String|Integer} [column] Column ID (number) * or name (string) * @example *
* function setup() { * var table = new p5.Table(); * * table.addColumn('name'); * table.addColumn('type'); * * var newRow = table.addRow(); * newRow.setString('name', ' Lion ,'); * newRow.setString('type', ' Mammal '); * * newRow = table.addRow(); * newRow.setString('name', ' Snake '); * newRow.setString('type', ' Reptile '); * * table.trim(); * print(table.getArray()); * } * * // prints: * // 0 "Lion" "Mamal" * // 1 "Snake" "Reptile" *
*/ p5.Table.prototype.trim = function(column) { var regex = new RegExp(' ', 'g'); if (typeof column === 'undefined') { for (var c = 0; c < this.columns.length; c++) { for (var d = 0; d < this.rows.length; d++) { var s = this.rows[d].arr[c]; s = s.replace(regex, ''); this.rows[d].arr[c] = s; this.rows[d].obj[this.columns[c]] = s; } } } else if (typeof column === 'string') { for (var j = 0; j < this.rows.length; j++) { var val = this.rows[j].obj[column]; val = val.replace(regex, ''); this.rows[j].obj[column] = val; var pos = this.columns.indexOf(column); this.rows[j].arr[pos] = val; } } else { for (var k = 0; k < this.rows.length; k++) { var str = this.rows[k].arr[column]; str = str.replace(regex, ''); this.rows[k].arr[column] = str; this.rows[k].obj[this.columns[column]] = str; } } }; /** * Use removeColumn() to remove an existing column from a Table * object. The column to be removed may be identified by either * its title (a String) or its index value (an int). * removeColumn(0) would remove the first column, removeColumn(1) * would remove the second column, and so on. * * @method removeColumn * @param {String|Integer} column columnName (string) or ID (number) * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.removeColumn('id'); * print(table.getColumnCount()); * } * *
* *@alt * no image displayed * */ p5.Table.prototype.removeColumn = function(c) { var cString; var cNumber; if (typeof c === 'string') { // find the position of c in the columns cString = c; cNumber = this.columns.indexOf(c); console.log('string'); } else { cNumber = c; cString = this.columns[c]; } var chunk = this.columns.splice(cNumber + 1, this.columns.length); this.columns.pop(); this.columns = this.columns.concat(chunk); for (var i = 0; i < this.rows.length; i++) { var tempR = this.rows[i].arr; var chip = tempR.splice(cNumber + 1, tempR.length); tempR.pop(); this.rows[i].arr = tempR.concat(chip); delete this.rows[i].obj[cString]; } }; /** * Stores a value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * * @method set * @param {Integer} row row ID * @param {String|Integer} column column ID (Number) * or title (String) * @param {String|Number} value value to assign * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.set(0, 'species', 'Canis Lupus'); * table.set(0, 'name', 'Wolf'); * * //print the results * for (var r = 0; r < table.getRowCount(); r++) * for (var c = 0; c < table.getColumnCount(); c++) * print(table.getString(r, c)); * } * *
* *@alt * no image displayed * */ p5.Table.prototype.set = function(row, column, value) { this.rows[row].set(column, value); }; /** * Stores a Float value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * * @method setNum * @param {Integer} row row ID * @param {String|Integer} column column ID (Number) * or title (String) * @param {Number} value value to assign * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * table.setNum(1, 'id', 1); * * print(table.getColumn(0)); * //["0", 1, "2"] * } * *
* *@alt * no image displayed */ p5.Table.prototype.setNum = function(row, column, value) { this.rows[row].setNum(column, value); }; /** * Stores a String value in the Table's specified row and column. * The row is specified by its ID, while the column may be specified * by either its ID or title. * * @method setString * @param {Integer} row row ID * @param {String|Integer} column column ID (Number) * or title (String) * @param {String} value value to assign * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * //add a row * var newRow = table.addRow(); * newRow.setString('id', table.getRowCount() - 1); * newRow.setString('species', 'Canis Lupus'); * newRow.setString('name', 'Wolf'); * * print(table.getArray()); * } *
* * @alt * no image displayed */ p5.Table.prototype.setString = function(row, column, value) { this.rows[row].setString(column, value); }; /** * Retrieves a value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * * @method get * @param {Integer} row row ID * @param {String|Integer} column columnName (string) or * ID (number) * @return {String|Number} * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * print(table.get(0, 1)); * //Capra hircus * print(table.get(0, 'species')); * //Capra hircus * } * *
* *@alt * no image displayed * */ p5.Table.prototype.get = function(row, column) { return this.rows[row].get(column); }; /** * Retrieves a Float value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * * @method getNum * @param {Integer} row row ID * @param {String|Integer} column columnName (string) or * ID (number) * @return {Number} * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * print(table.getNum(1, 0) + 100); * //id 1 + 100 = 101 * } * *
* *@alt * no image displayed * */ p5.Table.prototype.getNum = function(row, column) { return this.rows[row].getNum(column); }; /** * Retrieves a String value from the Table's specified row and column. * The row is specified by its ID, while the column may be specified by * either its ID or title. * * @method getString * @param {Integer} row row ID * @param {String|Integer} column columnName (string) or * ID (number) * @return {String} * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * // table is comma separated value "CSV" * // and has specifiying header for column labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * print(table.getString(0, 0)); // 0 * print(table.getString(0, 1)); // Capra hircus * print(table.getString(0, 2)); // Goat * print(table.getString(1, 0)); // 1 * print(table.getString(1, 1)); // Panthera pardus * print(table.getString(1, 2)); // Leopard * print(table.getString(2, 0)); // 2 * print(table.getString(2, 1)); // Equus zebra * print(table.getString(2, 2)); // Zebra * } * *
* *@alt * no image displayed * */ p5.Table.prototype.getString = function(row, column) { return this.rows[row].getString(column); }; /** * Retrieves all table data and returns as an object. If a column name is * passed in, each row object will be stored with that attribute as its * title. * * @method getObject * @param {String} [headerColumn] Name of the column which should be used to * title each row object (optional) * @return {Object} * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var tableObject = table.getObject(); * * print(tableObject); * //outputs an object * } * *
* *@alt * no image displayed * */ p5.Table.prototype.getObject = function(headerColumn) { var tableObject = {}; var obj, cPos, index; for (var i = 0; i < this.rows.length; i++) { obj = this.rows[i].obj; if (typeof headerColumn === 'string') { cPos = this.columns.indexOf(headerColumn); // index of columnID if (cPos >= 0) { index = obj[headerColumn]; tableObject[index] = obj; } else { throw 'This table has no column named "' + headerColumn + '"'; } } else { tableObject[i] = this.rows[i].obj; } } return tableObject; }; /** * Retrieves all table data and returns it as a multidimensional array. * * @method getArray * @return {Array} * * @example *
* * // Given the CSV file "mammals.csv" * // in the project's "assets" folder * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leoperd * // 2,Equus zebra,Zebra * * var table; * * function preload() { * // table is comma separated value "CSV" * // and has specifiying header for column labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var tableArray = table.getArray(); * for (var i = 0; i < tableArray.length; i++) { * print(tableArray[i]); * } * } * *
* *@alt * no image displayed * */ p5.Table.prototype.getArray = function() { var tableArray = []; for (var i = 0; i < this.rows.length; i++) { tableArray.push(this.rows[i].arr); } return tableArray; }; module.exports = p5; },{"../core/core":22}],48:[function(_dereq_,module,exports){ /** * @module IO * @submodule Table * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * A TableRow object represents a single row of data values, * stored in columns, from a table. * * A Table Row contains both an ordered array, and an unordered * JSON object. * * @class p5.TableRow * @constructor * @param {String} [str] optional: populate the row with a * string of values, separated by the * separator * @param {String} [separator] comma separated values (csv) by default */ p5.TableRow = function(str, separator) { var arr = []; var obj = {}; if (str) { separator = separator || ','; arr = str.split(separator); } for (var i = 0; i < arr.length; i++) { var key = i; var val = arr[i]; obj[key] = val; } this.arr = arr; this.obj = obj; this.table = null; }; /** * Stores a value in the TableRow's specified column. * The column may be specified by either its ID or title. * * @method set * @param {String|Integer} column Column ID (Number) * or Title (String) * @param {String|Number} value The value to be stored * * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * rows[r].set('name', 'Unicorn'); * } * * //print the results * print(table.getArray()); * } *
* * @alt * no image displayed */ p5.TableRow.prototype.set = function(column, value) { // if typeof column is string, use .obj if (typeof column === 'string') { var cPos = this.table.columns.indexOf(column); // index of columnID if (cPos >= 0) { this.obj[column] = value; this.arr[cPos] = value; } else { throw 'This table has no column named "' + column + '"'; } } else { // if typeof column is number, use .arr if (column < this.table.columns.length) { this.arr[column] = value; var cTitle = this.table.columns[column]; this.obj[cTitle] = value; } else { throw 'Column #' + column + ' is out of the range of this table'; } } }; /** * Stores a Float value in the TableRow's specified column. * The column may be specified by either its ID or title. * * @method setNum * @param {String|Integer} column Column ID (Number) * or Title (String) * @param {Number|String} value The value to be stored * as a Float * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * rows[r].setNum('id', r + 10); * } * * print(table.getArray()); * } *
* * @alt * no image displayed */ p5.TableRow.prototype.setNum = function(column, value) { var floatVal = parseFloat(value); this.set(column, floatVal); }; /** * Stores a String value in the TableRow's specified column. * The column may be specified by either its ID or title. * * @method setString * @param {String|Integer} column Column ID (Number) * or Title (String) * @param {String|Number|Boolean|Object} value The value to be stored * as a String * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * var name = rows[r].getString('name'); * rows[r].setString('name', 'A ' + name + ' named George'); * } * * print(table.getArray()); * } *
* * @alt * no image displayed */ p5.TableRow.prototype.setString = function(column, value) { var stringVal = value.toString(); this.set(column, stringVal); }; /** * Retrieves a value from the TableRow's specified column. * The column may be specified by either its ID or title. * * @method get * @param {String|Integer} column columnName (string) or * ID (number) * @return {String|Number} * * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var names = []; * var rows = table.getRows(); * for (var r = 0; r < rows.length; r++) { * names.push(rows[r].get('name')); * } * * print(names); * } *
* * @alt * no image displayed */ p5.TableRow.prototype.get = function(column) { if (typeof column === 'string') { return this.obj[column]; } else { return this.arr[column]; } }; /** * Retrieves a Float value from the TableRow's specified * column. The column may be specified by either its ID or * title. * * @method getNum * @param {String|Integer} column columnName (string) or * ID (number) * @return {Number} Float Floating point number * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * var minId = Infinity; * var maxId = -Infinity; * for (var r = 0; r < rows.length; r++) { * var id = rows[r].getNum('id'); * minId = min(minId, id); * maxId = min(maxId, id); * } * print('minimum id = ' + minId + ', maximum id = ' + maxId); * } *
* * @alt * no image displayed */ p5.TableRow.prototype.getNum = function(column) { var ret; if (typeof column === 'string') { ret = parseFloat(this.obj[column]); } else { ret = parseFloat(this.arr[column]); } if (ret.toString() === 'NaN') { throw 'Error: ' + this.obj[column] + ' is NaN (Not a Number)'; } return ret; }; /** * Retrieves an String value from the TableRow's specified * column. The column may be specified by either its ID or * title. * * @method getString * @param {String|Integer} column columnName (string) or * ID (number) * @return {String} String * @example *
* // Given the CSV file "mammals.csv" in the project's "assets" folder: * // * // id,species,name * // 0,Capra hircus,Goat * // 1,Panthera pardus,Leopard * // 2,Equus zebra,Zebra * * var table; * * function preload() { * //my table is comma separated value "csv" * //and has a header specifying the columns labels * table = loadTable('assets/mammals.csv', 'csv', 'header'); * } * * function setup() { * var rows = table.getRows(); * var longest = ''; * for (var r = 0; r < rows.length; r++) { * var species = rows[r].getString('species'); * if (longest.length < species.length) { * longest = species; * } * } * * print('longest: ' + longest); * } *
* * @alt * no image displayed */ p5.TableRow.prototype.getString = function(column) { if (typeof column === 'string') { return this.obj[column].toString(); } else { return this.arr[column].toString(); } }; module.exports = p5; },{"../core/core":22}],49:[function(_dereq_,module,exports){ /** * @module IO * @submodule XML * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * XML is a representation of an XML object, able to parse XML code. Use * loadXML() to load external XML files and create XML objects. * * @class p5.XML * @constructor * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var children = xml.getChildren('animal'); * * for (var i = 0; i < children.length; i++) { * var id = children[i].getNum('id'); * var coloring = children[i].getString('species'); * var name = children[i].getContent(); * print(id + ', ' + coloring + ', ' + name); * } * } * * // Sketch prints: * // 0, Capra hircus, Goat * // 1, Panthera pardus, Leopard * // 2, Equus zebra, Zebra *
* * @alt * no image displayed * */ p5.XML = function() { this.name = null; //done this.attributes = {}; //done this.children = []; this.parent = null; this.content = null; //done }; /** * Gets a copy of the element's parent. Returns the parent as another * p5.XML object. * * @method getParent * @return {p5.XML} element parent * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var children = xml.getChildren('animal'); * var parent = children[1].getParent(); * print(parent.getName()); * } * * // Sketch prints: * // mammals *
*/ p5.XML.prototype.getParent = function() { return this.parent; }; /** * Gets the element's full name, which is returned as a String. * * @method getName * @return {String} the name of the node * @example<animal *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.getName()); * } * * // Sketch prints: * // mammals *
*/ p5.XML.prototype.getName = function() { return this.name; }; /** * Sets the element's name, which is specified as a String. * * @method setName * @param {String} the new name of the node * @example<animal *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.getName()); * xml.setName('fish'); * print(xml.getName()); * } * * // Sketch prints: * // mammals * // fish *
*/ p5.XML.prototype.setName = function(name) { this.name = name; }; /** * Checks whether or not the element has any children, and returns the result * as a boolean. * * @method hasChildren * @return {boolean} * @example<animal *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.hasChildren()); * } * * // Sketch prints: * // true *
*/ p5.XML.prototype.hasChildren = function() { return this.children.length > 0; }; /** * Get the names of all of the element's children, and returns the names as an * array of Strings. This is the same as looping through and calling getName() * on each child element individually. * * @method listChildren * @return {String[]} names of the children of the element * @example<animal *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * print(xml.listChildren()); * } * * // Sketch prints: * // ["animal", "animal", "animal"] *
*/ p5.XML.prototype.listChildren = function() { return this.children.map(function(c) { return c.name; }); }; /** * Returns all of the element's children as an array of p5.XML objects. When * the name parameter is specified, then it will return all children that match * that name. * * @method getChildren * @param {String} [name] element name * @return {p5.XML[]} children of the element * @example<animal *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var animals = xml.getChildren('animal'); * * for (var i = 0; i < animals.length; i++) { * print(animals[i].getContent()); * } * } * * // Sketch prints: * // "Goat" * // "Leopard" * // "Zebra" *
*/ p5.XML.prototype.getChildren = function(param) { if (param) { return this.children.filter(function(c) { return c.name === param; }); } else { return this.children; } }; /** * Returns the first of the element's children that matches the name parameter * or the child of the given index.It returns undefined if no matching * child is found. * * @method getChild * @param {String|Integer} name element name or index * @return {p5.XML} * @example<animal *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * } * * // Sketch prints: * // "Goat" *
*
* var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var secondChild = xml.getChild(1); * print(secondChild.getContent()); * } * * // Sketch prints: * // "Leopard" *
*/ p5.XML.prototype.getChild = function(param) { if (typeof param === 'string') { for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (child.name === param) return child; } } else { return this.children[param]; } }; /** * Appends a new child to the element. The child can be specified with * either a String, which will be used as the new tag's name, or as a * reference to an existing p5.XML object. * A reference to the newly created child is returned as an p5.XML object. * * @method addChild * @param {p5.XML} node a p5.XML Object which will be the child to be added * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var child = new p5.XML(); * child.setAttribute('id', '3'); * child.setAttribute('species', 'Ornithorhynchus anatinus'); * child.setContent('Platypus'); * xml.addChild(child); * * var animals = xml.getChildren('animal'); * print(animals[animals.length - 1].getContent()); * } * * // Sketch prints: * // "Goat" * // "Leopard" * // "Zebra" *
*/ p5.XML.prototype.addChild = function(node) { if (node instanceof p5.XML) { this.children.push(node); } else { // PEND } }; /** * Removes the element specified by name or index. * * @method removeChild * @param {String|Integer} name element name or index * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * xml.removeChild('animal'); * var children = xml.getChildren(); * for (var i = 0; i < children.length; i++) { * print(children[i].getContent()); * } * } * * // Sketch prints: * // "Leopard" * // "Zebra" *
*
* var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * xml.removeChild(1); * var children = xml.getChildren(); * for (var i = 0; i < children.length; i++) { * print(children[i].getContent()); * } * } * * // Sketch prints: * // "Goat" * // "Zebra" *
*/ p5.XML.prototype.removeChild = function(param) { var ind = -1; if (typeof param === 'string') { for (var i = 0; i < this.children.length; i++) { if (this.children[i].name === param) { ind = i; break; } } } else { ind = param; } if (ind !== -1) { this.children.splice(ind, 1); } }; /** * Counts the specified element's number of attributes, returned as an Number. * * @method getAttributeCount * @return {Integer} * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getAttributeCount()); * } * * // Sketch prints: * // 2 *
*/ p5.XML.prototype.getAttributeCount = function() { return Object.keys(this.attributes).length; }; /** * Gets all of the specified element's attributes, and returns them as an * array of Strings. * * @method listAttributes * @return {String[]} an array of strings containing the names of attributes * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.listAttributes()); * } * * // Sketch prints: * // ["id", "species"] *
*/ p5.XML.prototype.listAttributes = function() { return Object.keys(this.attributes); }; /** * Checks whether or not an element has the specified attribute. * * @method hasAttribute * @param {String} the attribute to be checked * @return {boolean} true if attribute found else false * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.hasAttribute('species')); * print(firstChild.hasAttribute('color')); * } * * // Sketch prints: * // true * // false *
*/ p5.XML.prototype.hasAttribute = function(name) { return this.attributes[name] ? true : false; }; /** * Returns an attribute value of the element as an Number. If the defaultValue * parameter is specified and the attribute doesn't exist, then defaultValue * is returned. If no defaultValue is specified and the attribute doesn't * exist, the value 0 is returned. * * @method getNum * @param {String} name the non-null full name of the attribute * @param {Number} [defaultValue] the default value of the attribute * @return {Number} * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getNum('id')); * } * * // Sketch prints: * // 0 *
*/ p5.XML.prototype.getNum = function(name, defaultValue) { return Number(this.attributes[name]) || defaultValue || 0; }; /** * Returns an attribute value of the element as an String. If the defaultValue * parameter is specified and the attribute doesn't exist, then defaultValue * is returned. If no defaultValue is specified and the attribute doesn't * exist, null is returned. * * @method getString * @param {String} name the non-null full name of the attribute * @param {Number} [defaultValue] the default value of the attribute * @return {String} * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getString('species')); * } * * // Sketch prints: * // "Capra hircus" *
*/ p5.XML.prototype.getString = function(name, defaultValue) { return String(this.attributes[name]) || defaultValue || null; }; /** * Sets the content of an element's attribute. The first parameter specifies * the attribute name, while the second specifies the new content. * * @method setAttribute * @param {String} name the full name of the attribute * @param {Number|String|Boolean} value the value of the attribute * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getString('species')); * firstChild.setAttribute('species', 'Jamides zebra'); * print(firstChild.getString('species')); * } * * // Sketch prints: * // "Capra hircus" * // "Jamides zebra" *
*/ p5.XML.prototype.setAttribute = function(name, value) { if (this.attributes[name]) { this.attributes[name] = value; } }; /** * Returns the content of an element. If there is no such content, * defaultValue is returned if specified, otherwise null is returned. * * @method getContent * @param {String} [defaultValue] value returned if no content is found * @return {String} * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * } * * // Sketch prints: * // "Goat" *
*/ p5.XML.prototype.getContent = function(defaultValue) { return this.content || defaultValue || null; }; /** * Sets the element's content. * * @method setContent * @param {String} text the new content * @example *
* // The following short XML file called "mammals.xml" is parsed * // in the code below. * // * // * // <mammals> * // <animal id="0" species="Capra hircus">Goat</animal> * // <animal id="1" species="Panthera pardus">Leopard</animal> * // <animal id="2" species="Equus zebra">Zebra</animal> * // </mammals> * * var xml; * * function preload() { * xml = loadXML('assets/mammals.xml'); * } * * function setup() { * var firstChild = xml.getChild('animal'); * print(firstChild.getContent()); * firstChild.setContent('Mountain Goat'); * print(firstChild.getContent()); * } * * // Sketch prints: * // "Goat" * // "Mountain Goat" *
*/ p5.XML.prototype.setContent = function(content) { if (!this.children.length) { this.content = content; } }; /* HELPERS */ /** * This method is called while the parsing of XML (when loadXML() is * called). The difference between this method and the setContent() * method defined later is that this one is used to set the content * when the node in question has more nodes under it and so on and * not directly text content. While in the other one is used when * the node in question directly has text inside it. * */ p5.XML.prototype._setCont = function(content) { var str; str = content; str = str.replace(/\s\s+/g, ','); //str = str.split(','); this.content = str; }; /** * This method is called while the parsing of XML (when loadXML() is * called). The XML node is passed and its attributes are stored in the * p5.XML's attribute Object. * */ p5.XML.prototype._setAttributes = function(node) { var att = {}; var attributes = node.attributes; if (attributes) { for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; att[attribute.nodeName] = attribute.nodeValue; } } this.attributes = att; }; module.exports = p5; },{"../core/core":22}],50:[function(_dereq_,module,exports){ /** * @module Math * @submodule Calculation * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Calculates the absolute value (magnitude) of a number. Maps to Math.abs(). * The absolute value of a number is always positive. * * @method abs * @param {Number} n number to compute * @return {Number} absolute value of given number * @example *
* function setup() { * var x = -3; * var y = abs(x); * * print(x); // -3 * print(y); // 3 * } *
* * @alt * no image displayed * */ p5.prototype.abs = Math.abs; /** * Calculates the closest int value that is greater than or equal to the * value of the parameter. Maps to Math.ceil(). For example, ceil(9.03) * returns the value 10. * * @method ceil * @param {Number} n number to round up * @return {Integer} rounded up number * @example *
* function draw() { * background(200); * // map, mouseX between 0 and 5. * var ax = map(mouseX, 0, 100, 0, 5); * var ay = 66; * * //Get the ceiling of the mapped number. * var bx = ceil(map(mouseX, 0, 100, 0, 5)); * var by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. * stroke(0); * fill(0); * line(0, ay, ax * 20, ay); * line(0, by, bx * 20, by); * * // Reformat the float returned by map and draw it. * noStroke(); * text(nfc(ax, 2), ax, ay - 5); * text(nfc(bx, 1), bx, by - 5); * } *
* * @alt * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals * */ p5.prototype.ceil = Math.ceil; /** * Constrains a value between a minimum and maximum value. * * @method constrain * @param {Number} n number to constrain * @param {Number} low minimum limit * @param {Number} high maximum limit * @return {Number} constrained number * @example *
* function draw() { * background(200); * * var leftWall = 25; * var rightWall = 75; * * // xm is just the mouseX, while * // xc is the mouseX, but constrained * // between the leftWall and rightWall! * var xm = mouseX; * var xc = constrain(mouseX, leftWall, rightWall); * * // Draw the walls. * stroke(150); * line(leftWall, 0, leftWall, height); * line(rightWall, 0, rightWall, height); * * // Draw xm and xc as circles. * noStroke(); * fill(150); * ellipse(xm, 33, 9, 9); // Not Constrained * fill(0); * ellipse(xc, 66, 9, 9); // Constrained * } *
* * @alt * 2 vertical lines. 2 ellipses move with mouse X 1 does not move passed lines * */ p5.prototype.constrain = function(n, low, high) { p5._validateParameters('constrain', arguments); return Math.max(Math.min(n, high), low); }; /** * Calculates the distance between two points. * * @method dist * @param {Number} x1 x-coordinate of the first point * @param {Number} y1 y-coordinate of the first point * @param {Number} x2 x-coordinate of the second point * @param {Number} y2 y-coordinate of the second point * @return {Number} distance between the two points * * @example *
* // Move your mouse inside the canvas to see the * // change in distance between two points! * function draw() { * background(200); * fill(0); * * var x1 = 10; * var y1 = 90; * var x2 = mouseX; * var y2 = mouseY; * * line(x1, y1, x2, y2); * ellipse(x1, y1, 7, 7); * ellipse(x2, y2, 7, 7); * * // d is the length of the line * // the distance from point 1 to point 2. * var d = int(dist(x1, y1, x2, y2)); * * // Let's write d along the line we are drawing! * push(); * translate((x1 + x2) / 2, (y1 + y2) / 2); * rotate(atan2(y2 - y1, x2 - x1)); * text(nfc(d, 1), 0, -5); * pop(); * // Fancy! * } *
* * @alt * 2 ellipses joined by line. 1 ellipse moves with mouse X&Y. Distance displayed. */ /** * @method dist * @param {Number} x1 * @param {Number} y1 * @param {Number} z1 z-coordinate of the first point * @param {Number} x2 * @param {Number} y2 * @param {Number} z2 z-coordinate of the second point * @return {Number} distance between the two points */ p5.prototype.dist = function() { p5._validateParameters('dist', arguments); if (arguments.length === 4) { //2D return hypot(arguments[2] - arguments[0], arguments[3] - arguments[1]); } else if (arguments.length === 6) { //3D return hypot( arguments[3] - arguments[0], arguments[4] - arguments[1], arguments[5] - arguments[2] ); } }; /** * Returns Euler's number e (2.71828...) raised to the power of the n * parameter. Maps to Math.exp(). * * @method exp * @param {Number} n exponent to raise * @return {Number} e^n * @example *
* function draw() { * background(200); * * // Compute the exp() function with a value between 0 and 2 * var xValue = map(mouseX, 0, width, 0, 2); * var yValue = exp(xValue); * * var y = map(yValue, 0, 8, height, 0); * * var legend = 'exp (' + nfc(xValue, 3) + ')\n= ' + nf(yValue, 1, 4); * stroke(150); * line(mouseX, y, mouseX, height); * fill(0); * text(legend, 5, 15); * noStroke(); * ellipse(mouseX, y, 7, 7); * * // Draw the exp(x) curve, * // over the domain of x from 0 to 2 * noFill(); * stroke(0); * beginShape(); * for (var x = 0; x < width; x++) { * xValue = map(x, 0, width, 0, 2); * yValue = exp(xValue); * y = map(yValue, 0, 8, height, 0); * vertex(x, y); * } * * endShape(); * line(0, 0, 0, height); * line(0, height - 1, width, height - 1); * } *
* * @alt * ellipse moves along a curve with mouse x. e^n displayed. * */ p5.prototype.exp = Math.exp; /** * Calculates the closest int value that is less than or equal to the * value of the parameter. Maps to Math.floor(). * * @method floor * @param {Number} n number to round down * @return {Integer} rounded down number * @example *
* function draw() { * background(200); * //map, mouseX between 0 and 5. * var ax = map(mouseX, 0, 100, 0, 5); * var ay = 66; * * //Get the floor of the mapped number. * var bx = floor(map(mouseX, 0, 100, 0, 5)); * var by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. * stroke(0); * fill(0); * line(0, ay, ax * 20, ay); * line(0, by, bx * 20, by); * * // Reformat the float returned by map and draw it. * noStroke(); * text(nfc(ax, 2), ax, ay - 5); * text(nfc(bx, 1), bx, by - 5); * } *
* * @alt * 2 horizontal lines & number sets. increase with mouse x. bottom to 2 decimals * */ p5.prototype.floor = Math.floor; /** * Calculates a number between two numbers at a specific increment. The amt * parameter is the amount to interpolate between the two values where 0.0 * equal to the first point, 0.1 is very near the first point, 0.5 is * half-way in between, etc. The lerp function is convenient for creating * motion along a straight path and for drawing dotted lines. * * @method lerp * @param {Number} start first value * @param {Number} stop second value * @param {Number} amt number between 0.0 and 1.0 * @return {Number} lerped value * @example *
* function setup() { * background(200); * var a = 20; * var b = 80; * var c = lerp(a, b, 0.2); * var d = lerp(a, b, 0.5); * var e = lerp(a, b, 0.8); * * var y = 50; * * strokeWeight(5); * stroke(0); // Draw the original points in black * point(a, y); * point(b, y); * * stroke(100); // Draw the lerp points in gray * point(c, y); * point(d, y); * point(e, y); * } *
* * @alt * 5 points horizontally staggered mid-canvas. mid 3 are grey, outer black * */ p5.prototype.lerp = function(start, stop, amt) { p5._validateParameters('lerp', arguments); return amt * (stop - start) + start; }; /** * Calculates the natural logarithm (the base-e logarithm) of a number. This * function expects the n parameter to be a value greater than 0.0. Maps to * Math.log(). * * @method log * @param {Number} n number greater than 0 * @return {Number} natural logarithm of n * @example *
* function draw() { * background(200); * var maxX = 2.8; * var maxY = 1.5; * * // Compute the natural log of a value between 0 and maxX * var xValue = map(mouseX, 0, width, 0, maxX); * if (xValue > 0) { // Cannot take the log of a negative number. * var yValue = log(xValue); * var y = map(yValue, -maxY, maxY, height, 0); * * // Display the calculation occurring. * var legend = 'log(' + nf(xValue, 1, 2) + ')\n= ' + nf(yValue, 1, 3); * stroke(150); * line(mouseX, y, mouseX, height); * fill(0); * text(legend, 5, 15); * noStroke(); * ellipse(mouseX, y, 7, 7); * } * * // Draw the log(x) curve, * // over the domain of x from 0 to maxX * noFill(); * stroke(0); * beginShape(); * for (var x = 0; x < width; x++) { * xValue = map(x, 0, width, 0, maxX); * yValue = log(xValue); * y = map(yValue, -maxY, maxY, height, 0); * vertex(x, y); * } * endShape(); * line(0, 0, 0, height); * line(0, height / 2, width, height / 2); * } *
* * @alt * ellipse moves along a curve with mouse x. natural logarithm of n displayed. * */ p5.prototype.log = Math.log; /** * Calculates the magnitude (or length) of a vector. A vector is a direction * in space commonly used in computer graphics and linear algebra. Because it * has no "start" position, the magnitude of a vector can be thought of as * the distance from the coordinate 0,0 to its x,y value. Therefore, mag() is * a shortcut for writing dist(0, 0, x, y). * * @method mag * @param {Number} a first value * @param {Number} b second value * @return {Number} magnitude of vector from (0,0) to (a,b) * @example *
* function setup() { * var x1 = 20; * var x2 = 80; * var y1 = 30; * var y2 = 70; * * line(0, 0, x1, y1); * print(mag(x1, y1)); // Prints "36.05551275463989" * line(0, 0, x2, y1); * print(mag(x2, y1)); // Prints "85.44003745317531" * line(0, 0, x1, y2); * print(mag(x1, y2)); // Prints "72.80109889280519" * line(0, 0, x2, y2); * print(mag(x2, y2)); // Prints "106.3014581273465" * } *
* * @alt * 4 lines of different length radiate from top left of canvas. * */ p5.prototype.mag = function(x, y) { p5._validateParameters('mag', arguments); return hypot(x, y); }; /** * Re-maps a number from one range to another. *

* In the first example above, the number 25 is converted from a value in the * range of 0 to 100 into a value that ranges from the left edge of the * window (0) to the right edge (width). * * @method map * @param {Number} value the incoming value to be converted * @param {Number} start1 lower bound of the value's current range * @param {Number} stop1 upper bound of the value's current range * @param {Number} start2 lower bound of the value's target range * @param {Number} stop2 upper bound of the value's target range * @param {Boolean} [withinBounds] constrain the value to the newly mapped range * @return {Number} remapped number * @example *
* var value = 25; * var m = map(value, 0, 100, 0, width); * ellipse(m, 50, 10, 10);
* *
* function setup() { * noStroke(); * } * * function draw() { * background(204); * var x1 = map(mouseX, 0, width, 25, 75); * ellipse(x1, 25, 25, 25); * //This ellipse is constrained to the 0-100 range * //after setting withinBounds to true * var x2 = map(mouseX, 0, width, 0, 100, true); * ellipse(x2, 75, 25, 25); * }
* * @alt * 10 by 10 white ellipse with in mid left canvas * 2 25 by 25 white ellipses move with mouse x. Bottom has more range from X * */ p5.prototype.map = function(n, start1, stop1, start2, stop2, withinBounds) { p5._validateParameters('map', arguments); var newval = (n - start1) / (stop1 - start1) * (stop2 - start2) + start2; if (!withinBounds) { return newval; } if (start2 < stop2) { return this.constrain(newval, start2, stop2); } else { return this.constrain(newval, stop2, start2); } }; /** * Determines the largest value in a sequence of numbers, and then returns * that value. max() accepts any number of Number parameters, or an Array * of any length. * * @method max * @param {Number} n0 Number to compare * @param {Number} n1 Number to compare * @return {Number} maximum Number * @example *
* function setup() { * // Change the elements in the array and run the sketch * // to show how max() works! * var numArray = [2, 1, 5, 4, 8, 9]; * fill(0); * noStroke(); * text('Array Elements', 0, 10); * // Draw all numbers in the array * var spacing = 15; * var elemsY = 25; * for (var i = 0; i < numArray.length; i++) { * text(numArray[i], i * spacing, elemsY); * } * var maxX = 33; * var maxY = 80; * // Draw the Maximum value in the array. * textSize(32); * text(max(numArray), maxX, maxY); * } *
* * @alt * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 9 * */ /** * @method max * @param {Number[]} nums Numbers to compare * @return {Number} */ p5.prototype.max = function() { p5._validateParameters('max', arguments); if (arguments[0] instanceof Array) { return Math.max.apply(null, arguments[0]); } else { return Math.max.apply(null, arguments); } }; /** * Determines the smallest value in a sequence of numbers, and then returns * that value. min() accepts any number of Number parameters, or an Array * of any length. * * @method min * @param {Number} n0 Number to compare * @param {Number} n1 Number to compare * @return {Number} minimum Number * @example *
* function setup() { * // Change the elements in the array and run the sketch * // to show how min() works! * var numArray = [2, 1, 5, 4, 8, 9]; * fill(0); * noStroke(); * text('Array Elements', 0, 10); * // Draw all numbers in the array * var spacing = 15; * var elemsY = 25; * for (var i = 0; i < numArray.length; i++) { * text(numArray[i], i * spacing, elemsY); * } * var maxX = 33; * var maxY = 80; * // Draw the Minimum value in the array. * textSize(32); * text(min(numArray), maxX, maxY); * } *
* * @alt * Small text at top reads: Array Elements 2 1 5 4 8 9. Large text at center: 1 * */ /** * @method min * @param {Number[]} nums Numbers to compare * @return {Number} */ p5.prototype.min = function() { p5._validateParameters('min', arguments); if (arguments[0] instanceof Array) { return Math.min.apply(null, arguments[0]); } else { return Math.min.apply(null, arguments); } }; /** * Normalizes a number from another range into a value between 0 and 1. * Identical to map(value, low, high, 0, 1). * Numbers outside of the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. (See the second * example above.) * * @method norm * @param {Number} value incoming value to be normalized * @param {Number} start lower bound of the value's current range * @param {Number} stop upper bound of the value's current range * @return {Number} normalized number * @example *
* function draw() { * background(200); * var currentNum = mouseX; * var lowerBound = 0; * var upperBound = width; //100; * var normalized = norm(currentNum, lowerBound, upperBound); * var lineY = 70; * line(0, lineY, width, lineY); * //Draw an ellipse mapped to the non-normalized value. * noStroke(); * fill(50); * var s = 7; // ellipse size * ellipse(currentNum, lineY, s, s); * * // Draw the guide * var guideY = lineY + 15; * text('0', 0, guideY); * textAlign(RIGHT); * text('100', width, guideY); * * // Draw the normalized value * textAlign(LEFT); * fill(0); * textSize(32); * var normalY = 40; * var normalX = 20; * text(normalized, normalX, normalY); * } *
* * @alt * ellipse moves with mouse. 0 shown left & 100 right and updating values center * */ p5.prototype.norm = function(n, start, stop) { p5._validateParameters('norm', arguments); return this.map(n, start, stop, 0, 1); }; /** * Facilitates exponential expressions. The pow() function is an efficient * way of multiplying numbers by themselves (or their reciprocals) in large * quantities. For example, pow(3, 5) is equivalent to the expression * 3*3*3*3*3 and pow(3, -5) is equivalent to 1 / 3*3*3*3*3. Maps to * Math.pow(). * * @method pow * @param {Number} n base of the exponential expression * @param {Number} e power by which to raise the base * @return {Number} n^e * @example *
* function setup() { * //Exponentially increase the size of an ellipse. * var eSize = 3; // Original Size * var eLoc = 10; // Original Location * * ellipse(eLoc, eLoc, eSize, eSize); * * ellipse(eLoc * 2, eLoc * 2, pow(eSize, 2), pow(eSize, 2)); * * ellipse(eLoc * 4, eLoc * 4, pow(eSize, 3), pow(eSize, 3)); * * ellipse(eLoc * 8, eLoc * 8, pow(eSize, 4), pow(eSize, 4)); * } *
* * @alt * small to large ellipses radiating from top left of canvas * */ p5.prototype.pow = Math.pow; /** * Calculates the integer closest to the n parameter. For example, * round(133.8) returns the value 134. Maps to Math.round(). * * @method round * @param {Number} n number to round * @return {Integer} rounded number * @example *
* function draw() { * background(200); * //map, mouseX between 0 and 5. * var ax = map(mouseX, 0, 100, 0, 5); * var ay = 66; * * // Round the mapped number. * var bx = round(map(mouseX, 0, 100, 0, 5)); * var by = 33; * * // Multiply the mapped numbers by 20 to more easily * // see the changes. * stroke(0); * fill(0); * line(0, ay, ax * 20, ay); * line(0, by, bx * 20, by); * * // Reformat the float returned by map and draw it. * noStroke(); * text(nfc(ax, 2), ax, ay - 5); * text(nfc(bx, 1), bx, by - 5); * } *
* * @alt * horizontal center line squared values displayed on top and regular on bottom. * */ p5.prototype.round = Math.round; /** * Squares a number (multiplies a number by itself). The result is always a * positive number, as multiplying two negative numbers always yields a * positive result. For example, -1 * -1 = 1. * * @method sq * @param {Number} n number to square * @return {Number} squared number * @example *
* function draw() { * background(200); * var eSize = 7; * var x1 = map(mouseX, 0, width, 0, 10); * var y1 = 80; * var x2 = sq(x1); * var y2 = 20; * * // Draw the non-squared. * line(0, y1, width, y1); * ellipse(x1, y1, eSize, eSize); * * // Draw the squared. * line(0, y2, width, y2); * ellipse(x2, y2, eSize, eSize); * * // Draw dividing line. * stroke(100); * line(0, height / 2, width, height / 2); * * // Draw text. * var spacing = 15; * noStroke(); * fill(0); * text('x = ' + x1, 0, y1 + spacing); * text('sq(x) = ' + x2, 0, y2 + spacing); * } *
* * @alt * horizontal center line squared values displayed on top and regular on bottom. * */ p5.prototype.sq = function(n) { return n * n; }; /** * Calculates the square root of a number. The square root of a number is * always positive, even though there may be a valid negative root. The * square root s of number a is such that s*s = a. It is the opposite of * squaring. Maps to Math.sqrt(). * * @method sqrt * @param {Number} n non-negative number to square root * @return {Number} square root of number * @example *
* function draw() { * background(200); * var eSize = 7; * var x1 = mouseX; * var y1 = 80; * var x2 = sqrt(x1); * var y2 = 20; * * // Draw the non-squared. * line(0, y1, width, y1); * ellipse(x1, y1, eSize, eSize); * * // Draw the squared. * line(0, y2, width, y2); * ellipse(x2, y2, eSize, eSize); * * // Draw dividing line. * stroke(100); * line(0, height / 2, width, height / 2); * * // Draw text. * noStroke(); * fill(0); * var spacing = 15; * text('x = ' + x1, 0, y1 + spacing); * text('sqrt(x) = ' + x2, 0, y2 + spacing); * } *
* * @alt * horizontal center line squareroot values displayed on top and regular on bottom. * */ p5.prototype.sqrt = Math.sqrt; // Calculate the length of the hypotenuse of a right triangle // This won't under- or overflow in intermediate steps // https://en.wikipedia.org/wiki/Hypot function hypot(x, y, z) { // Use the native implementation if it's available if (typeof Math.hypot === 'function') { return Math.hypot.apply(null, arguments); } // Otherwise use the V8 implementation // https://github.com/v8/v8/blob/8cd3cf297287e581a49e487067f5cbd991b27123/src/js/math.js#L217 var length = arguments.length; var args = []; var max = 0; for (var i = 0; i < length; i++) { var n = arguments[i]; n = +n; if (n === Infinity || n === -Infinity) { return Infinity; } n = Math.abs(n); if (n > max) { max = n; } args[i] = n; } if (max === 0) { max = 1; } var sum = 0; var compensation = 0; for (var j = 0; j < length; j++) { var m = args[j] / max; var summand = m * m - compensation; var preliminary = sum + summand; compensation = preliminary - sum - summand; sum = preliminary; } return Math.sqrt(sum) * max; } module.exports = p5; },{"../core/core":22}],51:[function(_dereq_,module,exports){ /** * @module Math * @submodule Math * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Creates a new p5.Vector (the datatype for storing vectors). This provides a * two or three dimensional vector, specifically a Euclidean (also known as * geometric) vector. A vector is an entity that has both magnitude and * direction. * * @method createVector * @param {Number} [x] x component of the vector * @param {Number} [y] y component of the vector * @param {Number} [z] z component of the vector * @return {p5.Vector} * @example *
* function setup() { * createCanvas(100, 100, WEBGL); * noStroke(); * fill(255, 102, 204); * } * * function draw() { * background(255); * pointLight(color(255), createVector(sin(millis() / 1000) * 20, -40, -10)); * scale(0.75); * sphere(); * } *
* * @alt * a purple sphere lit by a point light oscillating horizontally */ p5.prototype.createVector = function(x, y, z) { if (this instanceof p5) { return new p5.Vector(this, arguments); } else { return new p5.Vector(x, y, z); } }; module.exports = p5; },{"../core/core":22}],52:[function(_dereq_,module,exports){ ////////////////////////////////////////////////////////////// // http://mrl.nyu.edu/~perlin/noise/ // Adapting from PApplet.java // which was adapted from toxi // which was adapted from the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip // someday we might consider using "improved noise" // http://mrl.nyu.edu/~perlin/paper445.pdf // See: https://github.com/shiffman/The-Nature-of-Code-Examples-p5.js/ // blob/master/introduction/Noise1D/noise.js /** * @module Math * @submodule Noise * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var PERLIN_YWRAPB = 4; var PERLIN_YWRAP = 1 << PERLIN_YWRAPB; var PERLIN_ZWRAPB = 8; var PERLIN_ZWRAP = 1 << PERLIN_ZWRAPB; var PERLIN_SIZE = 4095; var perlin_octaves = 4; // default to medium smooth var perlin_amp_falloff = 0.5; // 50% reduction/octave var scaled_cosine = function(i) { return 0.5 * (1.0 - Math.cos(i * Math.PI)); }; var perlin; // will be initialized lazily by noise() or noiseSeed() /** * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard random() function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.

The main difference to the * random() function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program; see * the noiseSeed() function). p5.js can compute 1D, 2D and 3D noise, * depending on the number of coordinates given. The resulting value will * always be between 0.0 and 1.0. The noise value can be animated by moving * through the noise space as demonstrated in the example above. The 2nd * and 3rd dimension can also be interpreted as time.

The actual * noise is structured similar to an audio signal, in respect to the * function's use of frequencies. Similar to the concept of harmonics in * physics, perlin noise is computed over several octaves which are added * together for the final result.

Another way to adjust the * character of the resulting sequence is the scale of the input * coordinates. As the function works within an infinite space the value of * the coordinates doesn't matter as such, only the distance between * successive coordinates does (eg. when using noise() within a * loop). As a general rule the smaller the difference between coordinates, * the smoother the resulting noise sequence will be. Steps of 0.005-0.03 * work best for most applications, but this will differ depending on use. * * * @method noise * @param {Number} x x-coordinate in noise space * @param {Number} [y] y-coordinate in noise space * @param {Number} [z] z-coordinate in noise space * @return {Number} Perlin noise value (between 0 and 1) at specified * coordinates * @example *
* * var xoff = 0.0; * * function draw() { * background(204); * xoff = xoff + 0.01; * var n = noise(xoff) * width; * line(n, 0, n, height); * } * *
*
* var noiseScale=0.02; * * function draw() { * background(0); * for (var x=0; x < width; x++) { * var noiseVal = noise((mouseX+x)*noiseScale, mouseY*noiseScale); * stroke(noiseVal*255); * line(x, mouseY+noiseVal*80, x, height); * } * } * *
* * @alt * vertical line moves left to right with updating noise values. * horizontal wave pattern effected by mouse x-position & updating noise values. * */ p5.prototype.noise = function(x, y, z) { y = y || 0; z = z || 0; if (perlin == null) { perlin = new Array(PERLIN_SIZE + 1); for (var i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = Math.random(); } } if (x < 0) { x = -x; } if (y < 0) { y = -y; } if (z < 0) { z = -z; } var xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z); var xf = x - xi; var yf = y - yi; var zf = z - zi; var rxf, ryf; var r = 0; var ampl = 0.5; var n1, n2, n3; for (var o = 0; o < perlin_octaves; o++) { var of = xi + (yi << PERLIN_YWRAPB) + (zi << PERLIN_ZWRAPB); rxf = scaled_cosine(xf); ryf = scaled_cosine(yf); n1 = perlin[of & PERLIN_SIZE]; n1 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n1); n2 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE]; n2 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n2); n1 += ryf * (n2 - n1); of += PERLIN_ZWRAP; n2 = perlin[of & PERLIN_SIZE]; n2 += rxf * (perlin[(of + 1) & PERLIN_SIZE] - n2); n3 = perlin[(of + PERLIN_YWRAP) & PERLIN_SIZE]; n3 += rxf * (perlin[(of + PERLIN_YWRAP + 1) & PERLIN_SIZE] - n3); n2 += ryf * (n3 - n2); n1 += scaled_cosine(zf) * (n2 - n1); r += n1 * ampl; ampl *= perlin_amp_falloff; xi <<= 1; xf *= 2; yi <<= 1; yf *= 2; zi <<= 1; zf *= 2; if (xf >= 1.0) { xi++; xf--; } if (yf >= 1.0) { yi++; yf--; } if (zf >= 1.0) { zi++; zf--; } } return r; }; /** * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overall intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. *

* By default, noise is computed over 4 octaves with each octave contributing * exactly half than its predecessor, starting at 50% strength for the 1st * octave. This falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by noise(). *

* By changing these parameters, the signal created by the noise() * function can be adapted to fit very specific needs and characteristics. * * @method noiseDetail * @param {Number} lod number of octaves to be used by the noise * @param {Number} falloff falloff factor for each octave * @example *
* * var noiseVal; * var noiseScale = 0.02; * * function setup() { * createCanvas(100, 100); * } * * function draw() { * background(0); * for (var y = 0; y < height; y++) { * for (var x = 0; x < width / 2; x++) { * noiseDetail(2, 0.2); * noiseVal = noise((mouseX + x) * noiseScale, (mouseY + y) * noiseScale); * stroke(noiseVal * 255); * point(x, y); * noiseDetail(8, 0.65); * noiseVal = noise( * (mouseX + x + width / 2) * noiseScale, * (mouseY + y) * noiseScale * ); * stroke(noiseVal * 255); * point(x + width / 2, y); * } * } * } * *
* * @alt * 2 vertical grey smokey patterns affected my mouse x-position and noise. * */ p5.prototype.noiseDetail = function(lod, falloff) { if (lod > 0) { perlin_octaves = lod; } if (falloff > 0) { perlin_amp_falloff = falloff; } }; /** * Sets the seed value for noise(). By default, noise() * produces different results each time the program is run. Set the * value parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * @method noiseSeed * @param {Number} seed the seed value * @example *
* var xoff = 0.0; * * function setup() { * noiseSeed(99); * stroke(0, 10); * } * * function draw() { * xoff = xoff + .01; * var n = noise(xoff) * width; * line(n, 0, n, height); * } * *
* * @alt * vertical grey lines drawing in pattern affected by noise. * */ p5.prototype.noiseSeed = function(seed) { // Linear Congruential Generator // Variant of a Lehman Generator var lcg = (function() { // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c var m = 4294967296; // a - 1 should be divisible by m's prime factors var a = 1664525; // c and m should be co-prime var c = 1013904223; var seed, z; return { setSeed: function(val) { // pick a random seed if val is undefined or null // the >>> 0 casts the seed to an unsigned 32-bit integer z = seed = (val == null ? Math.random() * m : val) >>> 0; }, getSeed: function() { return seed; }, rand: function() { // define the recurrence relationship z = (a * z + c) % m; // return a float in [0, 1) // if z = m then z / m = 0 therefore (z % m) / m < 1 always return z / m; } }; })(); lcg.setSeed(seed); perlin = new Array(PERLIN_SIZE + 1); for (var i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = lcg.rand(); } }; module.exports = p5; },{"../core/core":22}],53:[function(_dereq_,module,exports){ /** * @module Math * @submodule Math * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); /** * A class to describe a two or three dimensional vector, specifically * a Euclidean (also known as geometric) vector. A vector is an entity * that has both magnitude and direction. The datatype, however, stores * the components of the vector (x, y for 2D, and x, y, z for 3D). The magnitude * and direction can be accessed via the methods mag() and heading(). *

* In many of the p5.js examples, you will see p5.Vector used to describe a * position, velocity, or acceleration. For example, if you consider a rectangle * moving across the screen, at any given instant it has a position (a vector * that points from the origin to its location), a velocity (the rate at which * the object's position changes per time unit, expressed as a vector), and * acceleration (the rate at which the object's velocity changes per time * unit, expressed as a vector). *

* Since vectors represent groupings of values, we cannot simply use * traditional addition/multiplication/etc. Instead, we'll need to do some * "vector" math, which is made easy by the methods inside the p5.Vector class. * * @class p5.Vector * @param {Number} [x] x component of the vector * @param {Number} [y] y component of the vector * @param {Number} [z] z component of the vector * @example *
* * var v1 = createVector(40, 50); * var v2 = createVector(40, 50); * * ellipse(v1.x, v1.y, 50, 50); * ellipse(v2.x, v2.y, 50, 50); * v1.add(v2); * ellipse(v1.x, v1.y, 50, 50); * *
* * @alt * 2 white ellipses. One center-left the other bottom right and off canvas * */ p5.Vector = function Vector() { var x, y, z; // This is how it comes in with createVector() if (arguments[0] instanceof p5) { // save reference to p5 if passed in this.p5 = arguments[0]; x = arguments[1][0] || 0; y = arguments[1][1] || 0; z = arguments[1][2] || 0; // This is what we'll get with new p5.Vector() } else { x = arguments[0] || 0; y = arguments[1] || 0; z = arguments[2] || 0; } /** * The x component of the vector * @property x {Number} */ this.x = x; /** * The y component of the vector * @property y {Number} */ this.y = y; /** * The z component of the vector * @property z {Number} */ this.z = z; }; /** * Returns a string representation of a vector v by calling String(v) * or v.toString(). This method is useful for logging vectors in the * console. * @method toString * @return {String} * @example *
* * function setup() { * var v = createVector(20, 30); * print(String(v)); // prints "p5.Vector Object : [20, 30, 0]" * } * *
* *
* * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); * text(v1.toString(), 10, 25, 90, 75); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.toString = function p5VectorToString() { return 'p5.Vector Object : [' + this.x + ', ' + this.y + ', ' + this.z + ']'; }; /** * Sets the x, y, and z component of the vector using two or three separate * variables, the data from a p5.Vector, or the values from a float array. * @method set * @param {Number} [x] the x component of the vector * @param {Number} [y] the y component of the vector * @param {Number} [z] the z component of the vector * @chainable * @example *
* * function setup() { * var v = createVector(1, 2, 3); * v.set(4, 5, 6); // Sets vector to [4, 5, 6] * * var v1 = createVector(0, 0, 0); * var arr = [1, 2, 3]; * v1.set(arr); // Sets vector to [1, 2, 3] * } * *
* *
* * var v0, v1; * function setup() { * createCanvas(100, 100); * * v0 = createVector(0, 0); * v1 = createVector(50, 50); * } * * function draw() { * background(240); * * drawArrow(v0, v1, 'black'); * v1.set(v1.x + random(-1, 1), v1.y + random(-1, 1)); * * noStroke(); * text('x: ' + round(v1.x) + ' y: ' + round(v1.y), 20, 90); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ /** * @method set * @param {p5.Vector|Number[]} value the vector to set * @chainable */ p5.Vector.prototype.set = function set(x, y, z) { if (x instanceof p5.Vector) { this.x = x.x || 0; this.y = x.y || 0; this.z = x.z || 0; return this; } if (x instanceof Array) { this.x = x[0] || 0; this.y = x[1] || 0; this.z = x[2] || 0; return this; } this.x = x || 0; this.y = y || 0; this.z = z || 0; return this; }; /** * Gets a copy of the vector, returns a p5.Vector object. * * @method copy * @return {p5.Vector} the copy of the p5.Vector object * @example *
* * var v1 = createVector(1, 2, 3); * var v2 = v1.copy(); * print(v1.x === v2.x && v1.y === v2.y && v1.z === v2.z); * // Prints "true" * *
*/ p5.Vector.prototype.copy = function copy() { if (this.p5) { return new p5.Vector(this.p5, [this.x, this.y, this.z]); } else { return new p5.Vector(this.x, this.y, this.z); } }; /** * Adds x, y, and z components to a vector, adds one vector to another, or * adds two independent vectors together. The version of the method that adds * two vectors together is a static method and returns a p5.Vector, the others * acts directly on the vector. See the examples for more context. * * @method add * @param {Number} x the x component of the vector to be added * @param {Number} [y] the y component of the vector to be added * @param {Number} [z] the z component of the vector to be added * @chainable * @example *
* * var v = createVector(1, 2, 3); * v.add(4, 5, 6); * // v's components are set to [5, 7, 9] * *
* *
* * // Static method * var v1 = createVector(1, 2, 3); * var v2 = createVector(2, 3, 4); * * var v3 = p5.Vector.add(v1, v2); * // v3 has components [3, 5, 7] * print(v3); * *
* *
* * // red vector + blue vector = purple vector * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(-30, 20); * drawArrow(v1, v2, 'blue'); * * var v3 = p5.Vector.add(v1, v2); * drawArrow(v0, v3, 'purple'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ /** * @method add * @param {p5.Vector|Number[]} value the vector to add * @chainable */ p5.Vector.prototype.add = function add(x, y, z) { if (x instanceof p5.Vector) { this.x += x.x || 0; this.y += x.y || 0; this.z += x.z || 0; return this; } if (x instanceof Array) { this.x += x[0] || 0; this.y += x[1] || 0; this.z += x[2] || 0; return this; } this.x += x || 0; this.y += y || 0; this.z += z || 0; return this; }; /** * Subtracts x, y, and z components from a vector, subtracts one vector from * another, or subtracts two independent vectors. The version of the method * that subtracts two vectors is a static method and returns a p5.Vector, the * other acts directly on the vector. See the examples for more context. * * @method sub * @param {Number} x the x component of the vector to subtract * @param {Number} [y] the y component of the vector to subtract * @param {Number} [z] the z component of the vector to subtract * @chainable * @example *
* * var v = createVector(4, 5, 6); * v.sub(1, 1, 1); * // v's components are set to [3, 4, 5] * *
* *
* * // Static method * var v1 = createVector(2, 3, 4); * var v2 = createVector(1, 2, 3); * * var v3 = p5.Vector.sub(v1, v2); * // v3 has components [1, 1, 1] * print(v3); * *
* *
* * // red vector - blue vector = purple vector * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(70, 50); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(mouseX, mouseY); * drawArrow(v0, v2, 'blue'); * * var v3 = p5.Vector.sub(v1, v2); * drawArrow(v2, v3, 'purple'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ /** * @method sub * @param {p5.Vector|Number[]} value the vector to subtract * @chainable */ p5.Vector.prototype.sub = function sub(x, y, z) { if (x instanceof p5.Vector) { this.x -= x.x || 0; this.y -= x.y || 0; this.z -= x.z || 0; return this; } if (x instanceof Array) { this.x -= x[0] || 0; this.y -= x[1] || 0; this.z -= x[2] || 0; return this; } this.x -= x || 0; this.y -= y || 0; this.z -= z || 0; return this; }; /** * Multiply the vector by a scalar. The static version of this method * creates a new p5.Vector while the non static version acts on the vector * directly. See the examples for more context. * * @method mult * @param {Number} n the number to multiply with the vector * @chainable * @example *
* * var v = createVector(1, 2, 3); * v.mult(2); * // v's components are set to [2, 4, 6] * *
* *
* * // Static method * var v1 = createVector(1, 2, 3); * var v2 = p5.Vector.mult(v1, 2); * // v2 has components [2, 4, 6] * print(v2); * *
* *
* * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(25, -25); * drawArrow(v0, v1, 'red'); * * var num = map(mouseX, 0, width, -2, 2, true); * var v2 = p5.Vector.mult(v1, num); * drawArrow(v0, v2, 'blue'); * * noStroke(); * text('multiplied by ' + num.toFixed(2), 5, 90); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.mult = function mult(n) { if (!(typeof n === 'number' && isFinite(n))) { console.warn( 'p5.Vector.prototype.mult:', 'n is undefined or not a finite number' ); return this; } this.x *= n; this.y *= n; this.z *= n; return this; }; /** * Divide the vector by a scalar. The static version of this method creates a * new p5.Vector while the non static version acts on the vector directly. * See the examples for more context. * * @method div * @param {number} n the number to divide the vector by * @chainable * @example *
* * var v = createVector(6, 4, 2); * v.div(2); //v's components are set to [3, 2, 1] * *
* *
* * // Static method * var v1 = createVector(6, 4, 2); * var v2 = p5.Vector.div(v1, 2); * // v2 has components [3, 2, 1] * print(v2); * *
* *
* * function draw() { * background(240); * * var v0 = createVector(0, 100); * var v1 = createVector(50, -50); * drawArrow(v0, v1, 'red'); * * var num = map(mouseX, 0, width, 10, 0.5, true); * var v2 = p5.Vector.div(v1, num); * drawArrow(v0, v2, 'blue'); * * noStroke(); * text('divided by ' + num.toFixed(2), 10, 90); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.div = function div(n) { if (!(typeof n === 'number' && isFinite(n))) { console.warn( 'p5.Vector.prototype.div:', 'n is undefined or not a finite number' ); return this; } if (n === 0) { console.warn('p5.Vector.prototype.div:', 'divide by 0'); return this; } this.x /= n; this.y /= n; this.z /= n; return this; }; /** * Calculates the magnitude (length) of the vector and returns the result as * a float (this is simply the equation sqrt(x*x + y*y + z*z).) * * @method mag * @return {Number} magnitude of the vector * @example *
* * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); * text('vector length: ' + v1.mag().toFixed(2), 10, 70, 90, 30); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*
* * var v = createVector(20.0, 30.0, 40.0); * var m = v.mag(); * print(m); // Prints "53.85164807134504" * *
*/ p5.Vector.prototype.mag = function mag() { return Math.sqrt(this.magSq()); }; /** * Calculates the squared magnitude of the vector and returns the result * as a float (this is simply the equation (x*x + y*y + z*z).) * Faster if the real length is not required in the * case of comparing vectors, etc. * * @method magSq * @return {number} squared magnitude of the vector * @example *
* * // Static method * var v1 = createVector(6, 4, 2); * print(v1.magSq()); // Prints "56" * *
* *
* * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'black'); * * noStroke(); * text('vector length squared: ' + v1.magSq().toFixed(2), 10, 45, 90, 55); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.magSq = function magSq() { var x = this.x; var y = this.y; var z = this.z; return x * x + y * y + z * z; }; /** * Calculates the dot product of two vectors. The version of the method * that computes the dot product of two independent vectors is a static * method. See the examples for more context. * * * @method dot * @param {Number} x x component of the vector * @param {Number} [y] y component of the vector * @param {Number} [z] z component of the vector * @return {Number} the dot product * * @example *
* * var v1 = createVector(1, 2, 3); * var v2 = createVector(2, 3, 4); * * print(v1.dot(v2)); // Prints "20" * *
* *
* * //Static method * var v1 = createVector(1, 2, 3); * var v2 = createVector(3, 2, 1); * print(p5.Vector.dot(v1, v2)); // Prints "10" * *
*/ /** * @method dot * @param {p5.Vector} value value component of the vector or a p5.Vector * @return {Number} */ p5.Vector.prototype.dot = function dot(x, y, z) { if (x instanceof p5.Vector) { return this.dot(x.x, x.y, x.z); } return this.x * (x || 0) + this.y * (y || 0) + this.z * (z || 0); }; /** * Calculates and returns a vector composed of the cross product between * two vectors. Both the static and non static methods return a new p5.Vector. * See the examples for more context. * * @method cross * @param {p5.Vector} v p5.Vector to be crossed * @return {p5.Vector} p5.Vector composed of cross product * @example *
* * var v1 = createVector(1, 2, 3); * var v2 = createVector(1, 2, 3); * * v1.cross(v2); // v's components are [0, 0, 0] * *
* *
* * // Static method * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var crossProduct = p5.Vector.cross(v1, v2); * // crossProduct has components [0, 0, 1] * print(crossProduct); * *
*/ p5.Vector.prototype.cross = function cross(v) { var x = this.y * v.z - this.z * v.y; var y = this.z * v.x - this.x * v.z; var z = this.x * v.y - this.y * v.x; if (this.p5) { return new p5.Vector(this.p5, [x, y, z]); } else { return new p5.Vector(x, y, z); } }; /** * Calculates the Euclidean distance between two points (considering a * point as a vector object). * * @method dist * @param {p5.Vector} v the x, y, and z coordinates of a p5.Vector * @return {Number} the distance * @example *
* * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var distance = v1.dist(v2); // distance is 1.4142... * print(distance); * *
* *
* * // Static method * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var distance = p5.Vector.dist(v1, v2); * // distance is 1.4142... * print(distance); * *
* *
* * function draw() { * background(240); * * var v0 = createVector(0, 0); * * var v1 = createVector(70, 50); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(mouseX, mouseY); * drawArrow(v0, v2, 'blue'); * * noStroke(); * text('distance between vectors: ' + v2.dist(v1).toFixed(2), 5, 50, 95, 50); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.dist = function dist(v) { return v .copy() .sub(this) .mag(); }; /** * Normalize the vector to length 1 (make it a unit vector). * * @method normalize * @return {p5.Vector} normalized p5.Vector * @example *
* * var v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.normalize(); * // v's components are set to * // [0.4454354, 0.8908708, 0.089087084] * *
*
* * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'red'); * v1.normalize(); * drawArrow(v0, v1.mult(35), 'blue'); * * noFill(); * ellipse(50, 50, 35 * 2); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.normalize = function normalize() { var len = this.mag(); // here we multiply by the reciprocal instead of calling 'div()' // since div duplicates this zero check. if (len !== 0) this.mult(1 / len); return this; }; /** * Limit the magnitude of this vector to the value used for the max * parameter. * * @method limit * @param {Number} max the maximum magnitude for the vector * @chainable * @example *
* * var v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.limit(5); * // v's components are set to * // [2.2271771, 4.4543543, 0.4454354] * *
*
* * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'red'); * drawArrow(v0, v1.limit(35), 'blue'); * * noFill(); * ellipse(50, 50, 35 * 2); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.limit = function limit(max) { var mSq = this.magSq(); if (mSq > max * max) { this.div(Math.sqrt(mSq)) //normalize it .mult(max); } return this; }; /** * Set the magnitude of this vector to the value used for the len * parameter. * * @method setMag * @param {number} len the new length for this vector * @chainable * @example *
* * var v = createVector(10, 20, 2); * // v has components [10.0, 20.0, 2.0] * v.setMag(10); * // v's components are set to [6.0, 8.0, 0.0] * *
* *
* * function draw() { * background(240); * * var v0 = createVector(0, 0); * var v1 = createVector(50, 50); * * drawArrow(v0, v1, 'red'); * * var length = map(mouseX, 0, width, 0, 141, true); * v1.setMag(length); * drawArrow(v0, v1, 'blue'); * * noStroke(); * text('magnitude set to: ' + length.toFixed(2), 10, 70, 90, 30); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.setMag = function setMag(n) { return this.normalize().mult(n); }; /** * Calculate the angle of rotation for this vector (only 2D vectors) * * @method heading * @return {Number} the angle of rotation * @example *
* * function setup() { * var v1 = createVector(30, 50); * print(v1.heading()); // 1.0303768265243125 * * v1 = createVector(40, 50); * print(v1.heading()); // 0.8960553845713439 * * v1 = createVector(30, 70); * print(v1.heading()); // 1.1659045405098132 * } * *
* *
* * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(mouseX - 50, mouseY - 50); * * drawArrow(v0, v1, 'black'); * * var myHeading = v1.heading(); * noStroke(); * text( * 'vector heading: ' + * myHeading.toFixed(2) + * ' radians or ' + * degrees(myHeading).toFixed(2) + * ' degrees', * 10, * 50, * 90, * 50 * ); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.heading = function heading() { var h = Math.atan2(this.y, this.x); if (this.p5) return this.p5._fromRadians(h); return h; }; /** * Rotate the vector by an angle (only 2D vectors), magnitude remains the * same * * @method rotate * @param {number} angle the angle of rotation * @chainable * @example *
* * var v = createVector(10.0, 20.0); * // v has components [10.0, 20.0, 0.0] * v.rotate(HALF_PI); * // v's components are set to [-20.0, 9.999999, 0.0] * *
* *
* * var angle = 0; * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = createVector(50, 0); * * drawArrow(v0, v1.rotate(angle), 'black'); * angle += 0.01; * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.rotate = function rotate(a) { var newHeading = this.heading() + a; if (this.p5) newHeading = this.p5._toRadians(newHeading); var mag = this.mag(); this.x = Math.cos(newHeading) * mag; this.y = Math.sin(newHeading) * mag; return this; }; /** * Calculates and returns the angle (in radians) between two vectors. * @method angleBetween * @param {p5.Vector} the x, y, and z components of a p5.Vector * @return {Number} the angle between (in radians) * @example *
* * var v1 = createVector(1, 0, 0); * var v2 = createVector(0, 1, 0); * * var angle = v1.angleBetween(v2); * // angle is PI/2 * print(angle); * *
* *
* * function draw() { * background(240); * var v0 = createVector(50, 50); * * var v1 = createVector(50, 0); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(mouseX - 50, mouseY - 50); * drawArrow(v0, v2, 'blue'); * * var angleBetween = v1.angleBetween(v2); * noStroke(); * text( * 'angle between: ' + * angleBetween.toFixed(2) + * ' radians or ' + * degrees(angleBetween).toFixed(2) + * ' degrees', * 10, * 50, * 90, * 50 * ); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.prototype.angleBetween = function angleBetween(v) { var dotmagmag = this.dot(v) / (this.mag() * v.mag()); // Mathematically speaking: the dotmagmag variable will be between -1 and 1 // inclusive. Practically though it could be slightly outside this range due // to floating-point rounding issues. This can make Math.acos return NaN. // // Solution: we'll clamp the value to the -1,1 range var angle = Math.acos(Math.min(1, Math.max(-1, dotmagmag))); if (this.p5) return this.p5._fromRadians(angle); return angle; }; /** * Linear interpolate the vector to another vector * * @method lerp * @param {Number} x the x component * @param {Number} y the y component * @param {Number} z the z component * @param {Number} amt the amount of interpolation; some value between 0.0 * (old vector) and 1.0 (new vector). 0.9 is very near * the new vector. 0.5 is halfway in between. * @chainable * * @example *
* * var v = createVector(1, 1, 0); * * v.lerp(3, 3, 0, 0.5); // v now has components [2,2,0] * *
* *
* * var v1 = createVector(0, 0, 0); * var v2 = createVector(100, 100, 0); * * var v3 = p5.Vector.lerp(v1, v2, 0.5); * // v3 has components [50,50,0] * print(v3); * *
* *
* * var step = 0.01; * var amount = 0; * * function draw() { * background(240); * var v0 = createVector(0, 0); * * var v1 = createVector(mouseX, mouseY); * drawArrow(v0, v1, 'red'); * * var v2 = createVector(90, 90); * drawArrow(v0, v2, 'blue'); * * if (amount > 1 || amount < 0) { * step *= -1; * } * amount += step; * var v3 = p5.Vector.lerp(v1, v2, amount); * * drawArrow(v0, v3, 'purple'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ /** * @method lerp * @param {p5.Vector} v the p5.Vector to lerp to * @param {Number} amt * @chainable */ p5.Vector.prototype.lerp = function lerp(x, y, z, amt) { if (x instanceof p5.Vector) { return this.lerp(x.x, x.y, x.z, y); } this.x += (x - this.x) * amt || 0; this.y += (y - this.y) * amt || 0; this.z += (z - this.z) * amt || 0; return this; }; /** * Return a representation of this vector as a float array. This is only * for temporary use. If used in any other fashion, the contents should be * copied by using the p5.Vector.copy() method to copy into your own * array. * * @method array * @return {Number[]} an Array with the 3 values * @example *
* * function setup() { * var v = createVector(20, 30); * print(v.array()); // Prints : Array [20, 30, 0] * } * *
* *
* * var v = createVector(10.0, 20.0, 30.0); * var f = v.array(); * print(f[0]); // Prints "10.0" * print(f[1]); // Prints "20.0" * print(f[2]); // Prints "30.0" * *
*/ p5.Vector.prototype.array = function array() { return [this.x || 0, this.y || 0, this.z || 0]; }; /** * Equality check against a p5.Vector * * @method equals * @param {Number} [x] the x component of the vector * @param {Number} [y] the y component of the vector * @param {Number} [z] the z component of the vector * @return {Boolean} whether the vectors are equals * @example *
* * var v1 = createVector(5, 10, 20); * var v2 = createVector(5, 10, 20); * var v3 = createVector(13, 10, 19); * * print(v1.equals(v2.x, v2.y, v2.z)); // true * print(v1.equals(v3.x, v3.y, v3.z)); // false * *
* *
* * var v1 = createVector(10.0, 20.0, 30.0); * var v2 = createVector(10.0, 20.0, 30.0); * var v3 = createVector(0.0, 0.0, 0.0); * print(v1.equals(v2)); // true * print(v1.equals(v3)); // false * *
*/ /** * @method equals * @param {p5.Vector|Array} value the vector to compare * @return {Boolean} */ p5.Vector.prototype.equals = function equals(x, y, z) { var a, b, c; if (x instanceof p5.Vector) { a = x.x || 0; b = x.y || 0; c = x.z || 0; } else if (x instanceof Array) { a = x[0] || 0; b = x[1] || 0; c = x[2] || 0; } else { a = x || 0; b = y || 0; c = z || 0; } return this.x === a && this.y === b && this.z === c; }; // Static Methods /** * Make a new 2D vector from an angle * * @method fromAngle * @static * @param {Number} angle the desired angle, in radians * @param {Number} [length] the length of the new vector (defaults to 1) * @return {p5.Vector} the new p5.Vector object * @example *
* * function draw() { * background(200); * * // Create a variable, proportional to the mouseX, * // varying from 0-360, to represent an angle in degrees. * angleMode(DEGREES); * var myDegrees = map(mouseX, 0, width, 0, 360); * * // Display that variable in an onscreen text. * // (Note the nfc() function to truncate additional decimal places, * // and the "\xB0" character for the degree symbol.) * var readout = 'angle = ' + nfc(myDegrees, 1) + '\xB0'; * noStroke(); * fill(0); * text(readout, 5, 15); * * // Create a p5.Vector using the fromAngle function, * // and extract its x and y components. * var v = p5.Vector.fromAngle(radians(myDegrees), 30); * var vx = v.x; * var vy = v.y; * * push(); * translate(width / 2, height / 2); * noFill(); * stroke(150); * line(0, 0, 30, 0); * stroke(0); * line(0, 0, vx, vy); * pop(); * } * *
*/ p5.Vector.fromAngle = function fromAngle(angle, length) { if (typeof length === 'undefined') { length = 1; } return new p5.Vector(length * Math.cos(angle), length * Math.sin(angle), 0); }; /** * Make a new 3D vector from a pair of ISO spherical angles * * @method fromAngles * @static * @param {Number} theta the polar angle, in radians (zero is up) * @param {Number} phi the azimuthal angle, in radians * (zero is out of the screen) * @param {Number} [length] the length of the new vector (defaults to 1) * @return {p5.Vector} the new p5.Vector object * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * fill(255); * noStroke(); * } * function draw() { * background(255); * * var t = millis() / 1000; * * // add three point lights * pointLight(color('#f00'), p5.Vector.fromAngles(t * 1.0, t * 1.3, 100)); * pointLight(color('#0f0'), p5.Vector.fromAngles(t * 1.1, t * 1.2, 100)); * pointLight(color('#00f'), p5.Vector.fromAngles(t * 1.2, t * 1.1, 100)); * * sphere(35); * } * *
*/ p5.Vector.fromAngles = function(theta, phi, length) { if (typeof length === 'undefined') { length = 1; } var cosPhi = Math.cos(phi); var sinPhi = Math.sin(phi); var cosTheta = Math.cos(theta); var sinTheta = Math.sin(theta); return new p5.Vector( length * sinTheta * sinPhi, -length * cosTheta, length * sinTheta * cosPhi ); }; /** * Make a new 2D unit vector from a random angle * * @method random2D * @static * @return {p5.Vector} the new p5.Vector object * @example *
* * var v = p5.Vector.random2D(); * // May make v's attributes something like: * // [0.61554617, -0.51195765, 0.0] or * // [-0.4695841, -0.14366731, 0.0] or * // [0.6091097, -0.22805278, 0.0] * print(v); * *
* *
* * function setup() { * frameRate(1); * } * * function draw() { * background(240); * * var v0 = createVector(50, 50); * var v1 = p5.Vector.random2D(); * drawArrow(v0, v1.mult(50), 'black'); * } * * // draw an arrow for a vector at a given base position * function drawArrow(base, vec, myColor) { * push(); * stroke(myColor); * strokeWeight(3); * fill(myColor); * translate(base.x, base.y); * line(0, 0, vec.x, vec.y); * rotate(vec.heading()); * var arrowSize = 7; * translate(vec.mag() - arrowSize, 0); * triangle(0, arrowSize / 2, 0, -arrowSize / 2, arrowSize, 0); * pop(); * } * *
*/ p5.Vector.random2D = function random2D() { return this.fromAngle(Math.random() * constants.TWO_PI); }; /** * Make a new random 3D unit vector. * * @method random3D * @static * @return {p5.Vector} the new p5.Vector object * @example *
* * var v = p5.Vector.random3D(); * // May make v's attributes something like: * // [0.61554617, -0.51195765, 0.599168] or * // [-0.4695841, -0.14366731, -0.8711202] or * // [0.6091097, -0.22805278, -0.7595902] * print(v); * *
*/ p5.Vector.random3D = function random3D() { var angle = Math.random() * constants.TWO_PI; var vz = Math.random() * 2 - 1; var vzBase = Math.sqrt(1 - vz * vz); var vx = vzBase * Math.cos(angle); var vy = vzBase * Math.sin(angle); return new p5.Vector(vx, vy, vz); }; // Adds two vectors together and returns a new one. /** * @method add * @static * @param {p5.Vector} v1 a p5.Vector to add * @param {p5.Vector} v2 a p5.Vector to add * @param {p5.Vector} target the vector to receive the result */ /** * @method add * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @return {p5.Vector} the resulting p5.Vector * */ p5.Vector.add = function add(v1, v2, target) { if (!target) { target = v1.copy(); } else { target.set(v1); } target.add(v2); return target; }; /* * Subtracts one p5.Vector from another and returns a new one. The second * vector (v2) is subtracted from the first (v1), resulting in v1-v2. */ /** * @method sub * @static * @param {p5.Vector} v1 a p5.Vector to subtract from * @param {p5.Vector} v2 a p5.Vector to subtract * @param {p5.Vector} target if undefined a new vector will be created */ /** * @method sub * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @return {p5.Vector} the resulting p5.Vector */ p5.Vector.sub = function sub(v1, v2, target) { if (!target) { target = v1.copy(); } else { target.set(v1); } target.sub(v2); return target; }; /** * Multiplies a vector by a scalar and returns a new vector. */ /** * @method mult * @static * @param {p5.Vector} v the vector to multiply * @param {Number} n * @param {p5.Vector} target if undefined a new vector will be created */ /** * @method mult * @static * @param {p5.Vector} v * @param {Number} n * @return {p5.Vector} the resulting new p5.Vector */ p5.Vector.mult = function mult(v, n, target) { if (!target) { target = v.copy(); } else { target.set(v); } target.mult(n); return target; }; /** * Divides a vector by a scalar and returns a new vector. */ /** * @method div * @static * @param {p5.Vector} v the vector to divide * @param {Number} n * @param {p5.Vector} target if undefined a new vector will be created */ /** * @method div * @static * @param {p5.Vector} v * @param {Number} n * @return {p5.Vector} the resulting new p5.Vector */ p5.Vector.div = function div(v, n, target) { if (!target) { target = v.copy(); } else { target.set(v); } target.div(n); return target; }; /** * Calculates the dot product of two vectors. */ /** * @method dot * @static * @param {p5.Vector} v1 the first p5.Vector * @param {p5.Vector} v2 the second p5.Vector * @return {Number} the dot product */ p5.Vector.dot = function dot(v1, v2) { return v1.dot(v2); }; /** * Calculates the cross product of two vectors. */ /** * @method cross * @static * @param {p5.Vector} v1 the first p5.Vector * @param {p5.Vector} v2 the second p5.Vector * @return {Number} the cross product */ p5.Vector.cross = function cross(v1, v2) { return v1.cross(v2); }; /** * Calculates the Euclidean distance between two points (considering a * point as a vector object). */ /** * @method dist * @static * @param {p5.Vector} v1 the first p5.Vector * @param {p5.Vector} v2 the second p5.Vector * @return {Number} the distance */ p5.Vector.dist = function dist(v1, v2) { return v1.dist(v2); }; /** * Linear interpolate a vector to another vector and return the result as a * new vector. */ /** * @method lerp * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @param {Number} amt * @param {p5.Vector} target if undefined a new vector will be created */ /** * @method lerp * @static * @param {p5.Vector} v1 * @param {p5.Vector} v2 * @param {Number} amt * @return {Number} the lerped value */ p5.Vector.lerp = function lerp(v1, v2, amt, target) { if (!target) { target = v1.copy(); } else { target.set(v1); } target.lerp(v2, amt); return target; }; /** * @method mag * @param {p5.Vector} vecT the vector to return the magnitude of * @return {Number} the magnitude of vecT * @static */ p5.Vector.mag = function mag(vecT) { var x = vecT.x, y = vecT.y, z = vecT.z; var magSq = x * x + y * y + z * z; return Math.sqrt(magSq); }; module.exports = p5.Vector; },{"../core/constants":21,"../core/core":22}],54:[function(_dereq_,module,exports){ /** * @module Math * @submodule Random * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var seeded = false; var previous = false; var y2 = 0; // Linear Congruential Generator // Variant of a Lehman Generator var lcg = (function() { // Set to values from http://en.wikipedia.org/wiki/Numerical_Recipes // m is basically chosen to be large (as it is the max period) // and for its relationships to a and c var m = 4294967296, // a - 1 should be divisible by m's prime factors a = 1664525, // c and m should be co-prime c = 1013904223, seed, z; return { setSeed: function(val) { // pick a random seed if val is undefined or null // the >>> 0 casts the seed to an unsigned 32-bit integer z = seed = (val == null ? Math.random() * m : val) >>> 0; }, getSeed: function() { return seed; }, rand: function() { // define the recurrence relationship z = (a * z + c) % m; // return a float in [0, 1) // if z = m then z / m = 0 therefore (z % m) / m < 1 always return z / m; } }; })(); /** * Sets the seed value for random(). * * By default, random() produces different results each time the program * is run. Set the seed parameter to a constant to return the same * pseudo-random numbers each time the software is run. * * @method randomSeed * @param {Number} seed the seed value * @example *
* * randomSeed(99); * for (var i = 0; i < 100; i++) { * var r = random(0, 255); * stroke(r); * line(i, 0, i, 100); * } * *
* * @alt * many vertical lines drawn in white, black or grey. * */ p5.prototype.randomSeed = function(seed) { lcg.setSeed(seed); seeded = true; previous = false; }; /** * Return a random floating-point number. * * Takes either 0, 1 or 2 arguments. * * If no argument is given, returns a random number from 0 * up to (but not including) 1. * * If one argument is given and it is a number, returns a random number from 0 * up to (but not including) the number. * * If one argument is given and it is an array, returns a random element from * that array. * * If two arguments are given, returns a random number from the * first argument up to (but not including) the second argument. * * @method random * @param {Number} [min] the lower bound (inclusive) * @param {Number} [max] the upper bound (exclusive) * @return {Number} the random number * @example *
* * for (var i = 0; i < 100; i++) { * var r = random(50); * stroke(r * 5); * line(50, i, 50 + r, i); * } * *
*
* * for (var i = 0; i < 100; i++) { * var r = random(-50, 50); * line(50, i, 50 + r, i); * } * *
*
* * // Get a random element from an array using the random(Array) syntax * var words = ['apple', 'bear', 'cat', 'dog']; * var word = random(words); // select random word * text(word, 10, 50); // draw the word * *
* * @alt * 100 horizontal lines from center canvas to right. size+fill change each time * 100 horizontal lines from center of canvas. height & side change each render * word displayed at random. Either apple, bear, cat, or dog * */ /** * @method random * @param {Array} choices the array to choose from * @return {*} the random element from the array * @example */ p5.prototype.random = function(min, max) { var rand; if (seeded) { rand = lcg.rand(); } else { rand = Math.random(); } if (typeof min === 'undefined') { return rand; } else if (typeof max === 'undefined') { if (min instanceof Array) { return min[Math.floor(rand * min.length)]; } else { return rand * min; } } else { if (min > max) { var tmp = min; min = max; max = tmp; } return rand * (max - min) + min; } }; /** * * Returns a random number fitting a Gaussian, or * normal, distribution. There is theoretically no minimum or maximum * value that randomGaussian() might return. Rather, there is * just a very low probability that values far from the mean will be * returned; and a higher probability that numbers near the mean will * be returned. *

* Takes either 0, 1 or 2 arguments.
* If no args, returns a mean of 0 and standard deviation of 1.
* If one arg, that arg is the mean (standard deviation is 1).
* If two args, first is mean, second is standard deviation. * * @method randomGaussian * @param {Number} mean the mean * @param {Number} sd the standard deviation * @return {Number} the random number * @example *
* * for (var y = 0; y < 100; y++) { * var x = randomGaussian(50, 15); * line(50, y, x, y); * } * *
*
* * var distribution = new Array(360); * * function setup() { * createCanvas(100, 100); * for (var i = 0; i < distribution.length; i++) { * distribution[i] = floor(randomGaussian(0, 15)); * } * } * * function draw() { * background(204); * * translate(width / 2, width / 2); * * for (var i = 0; i < distribution.length; i++) { * rotate(TWO_PI / distribution.length); * stroke(0); * var dist = abs(distribution[i]); * line(0, 0, dist, 0); * } * } * *
* @alt * 100 horizontal lines from center of canvas. height & side change each render * black lines radiate from center of canvas. size determined each render */ p5.prototype.randomGaussian = function(mean, sd) { var y1, x1, x2, w; if (previous) { y1 = y2; previous = false; } else { do { x1 = this.random(2) - 1; x2 = this.random(2) - 1; w = x1 * x1 + x2 * x2; } while (w >= 1); w = Math.sqrt(-2 * Math.log(w) / w); y1 = x1 * w; y2 = x2 * w; previous = true; } var m = mean || 0; var s = sd || 1; return y1 * s + m; }; module.exports = p5; },{"../core/core":22}],55:[function(_dereq_,module,exports){ /** * @module Math * @submodule Trigonometry * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); /* * all DEGREES/RADIANS conversion should be done in the p5 instance * if possible, using the p5._toRadians(), p5._fromRadians() methods. */ p5.prototype._angleMode = constants.RADIANS; /** * The inverse of cos(), returns the arc cosine of a value. This function * expects the values in the range of -1 to 1 and values are returned in * the range 0 to PI (3.1415927). * * @method acos * @param {Number} value the value whose arc cosine is to be returned * @return {Number} the arc cosine of the given value * * @example *
* * var a = PI; * var c = cos(a); * var ac = acos(c); * // Prints: "3.1415927 : -1.0 : 3.1415927" * print(a + ' : ' + c + ' : ' + ac); * *
* *
* * var a = PI + PI / 4.0; * var c = cos(a); * var ac = acos(c); * // Prints: "3.926991 : -0.70710665 : 2.3561943" * print(a + ' : ' + c + ' : ' + ac); * *
*/ p5.prototype.acos = function(ratio) { return this._fromRadians(Math.acos(ratio)); }; /** * The inverse of sin(), returns the arc sine of a value. This function * expects the values in the range of -1 to 1 and values are returned * in the range -PI/2 to PI/2. * * @method asin * @param {Number} value the value whose arc sine is to be returned * @return {Number} the arc sine of the given value * * @example *
* * var a = PI + PI / 3; * var s = sin(a); * var as = asin(s); * // Prints: "1.0471976 : 0.86602545 : 1.0471976" * print(a + ' : ' + s + ' : ' + as); * *
* *
* * var a = PI + PI / 3.0; * var s = sin(a); * var as = asin(s); * // Prints: "4.1887903 : -0.86602545 : -1.0471976" * print(a + ' : ' + s + ' : ' + as); * *
* */ p5.prototype.asin = function(ratio) { return this._fromRadians(Math.asin(ratio)); }; /** * The inverse of tan(), returns the arc tangent of a value. This function * expects the values in the range of -Infinity to Infinity (exclusive) and * values are returned in the range -PI/2 to PI/2. * * @method atan * @param {Number} value the value whose arc tangent is to be returned * @return {Number} the arc tangent of the given value * * @example *
* * var a = PI + PI / 3; * var t = tan(a); * var at = atan(t); * // Prints: "1.0471976 : 1.7320509 : 1.0471976" * print(a + ' : ' + t + ' : ' + at); * *
* *
* * var a = PI + PI / 3.0; * var t = tan(a); * var at = atan(t); * // Prints: "4.1887903 : 1.7320513 : 1.0471977" * print(a + ' : ' + t + ' : ' + at); * *
* */ p5.prototype.atan = function(ratio) { return this._fromRadians(Math.atan(ratio)); }; /** * Calculates the angle (in radians) from a specified point to the coordinate * origin as measured from the positive x-axis. Values are returned as a * float in the range from PI to -PI. The atan2() function is most often used * for orienting geometry to the position of the cursor. *

* Note: The y-coordinate of the point is the first parameter, and the * x-coordinate is the second parameter, due the the structure of calculating * the tangent. * * @method atan2 * @param {Number} y y-coordinate of the point * @param {Number} x x-coordinate of the point * @return {Number} the arc tangent of the given point * * @example *
* * function draw() { * background(204); * translate(width / 2, height / 2); * var a = atan2(mouseY - height / 2, mouseX - width / 2); * rotate(a); * rect(-30, -5, 60, 10); * } * *
* * @alt * 60 by 10 rect at center of canvas rotates with mouse movements * */ p5.prototype.atan2 = function(y, x) { return this._fromRadians(Math.atan2(y, x)); }; /** * Calculates the cosine of an angle. This function takes into account the * current angleMode. Values are returned in the range -1 to 1. * * @method cos * @param {Number} angle the angle * @return {Number} the cosine of the angle * * @example *
* * var a = 0.0; * var inc = TWO_PI / 25.0; * for (var i = 0; i < 25; i++) { * line(i * 4, 50, i * 4, 50 + cos(a) * 40.0); * a = a + inc; * } * *
* * @alt * vertical black lines form wave patterns, extend-down on left and right side * */ p5.prototype.cos = function(angle) { return Math.cos(this._toRadians(angle)); }; /** * Calculates the sine of an angle. This function takes into account the * current angleMode. Values are returned in the range -1 to 1. * * @method sin * @param {Number} angle the angle * @return {Number} the sine of the angle * * @example *
* * var a = 0.0; * var inc = TWO_PI / 25.0; * for (var i = 0; i < 25; i++) { * line(i * 4, 50, i * 4, 50 + sin(a) * 40.0); * a = a + inc; * } * *
* * @alt * vertical black lines extend down and up from center to form wave pattern * */ p5.prototype.sin = function(angle) { return Math.sin(this._toRadians(angle)); }; /** * Calculates the tangent of an angle. This function takes into account * the current angleMode. Values are returned in the range -1 to 1. * * @method tan * @param {Number} angle the angle * @return {Number} the tangent of the angle * * @example *
* * var a = 0.0; * var inc = TWO_PI / 50.0; * for (var i = 0; i < 100; i = i + 2) { * line(i, 50, i, 50 + tan(a) * 2.0); * a = a + inc; * } * * * * @alt * vertical black lines end down and up from center to form spike pattern * */ p5.prototype.tan = function(angle) { return Math.tan(this._toRadians(angle)); }; /** * Converts a radian measurement to its corresponding value in degrees. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90° = PI/2 = 1.5707964. This function does not take into account the * current angleMode. * * @method degrees * @param {Number} radians the radians value to convert to degrees * @return {Number} the converted angle * * * @example *
* * var rad = PI / 4; * var deg = degrees(rad); * print(rad + ' radians is ' + deg + ' degrees'); * // Prints: 0.7853981633974483 radians is 45 degrees * *
* */ p5.prototype.degrees = function(angle) { return angle * constants.RAD_TO_DEG; }; /** * Converts a degree measurement to its corresponding value in radians. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90° = PI/2 = 1.5707964. This function does not take into account the * current angleMode. * * @method radians * @param {Number} degrees the degree value to convert to radians * @return {Number} the converted angle * * @example *
* * var deg = 45.0; * var rad = radians(deg); * print(deg + ' degrees is ' + rad + ' radians'); * // Prints: 45 degrees is 0.7853981633974483 radians * *
*/ p5.prototype.radians = function(angle) { return angle * constants.DEG_TO_RAD; }; /** * Sets the current mode of p5 to given mode. Default mode is RADIANS. * * @method angleMode * @param {Constant} mode either RADIANS or DEGREES * * @example *
* * function draw() { * background(204); * angleMode(DEGREES); // Change the mode to DEGREES * var a = atan2(mouseY - height / 2, mouseX - width / 2); * translate(width / 2, height / 2); * push(); * rotate(a); * rect(-20, -5, 40, 10); // Larger rectangle is rotating in degrees * pop(); * angleMode(RADIANS); // Change the mode to RADIANS * rotate(a); // var a stays the same * rect(-40, -5, 20, 10); // Smaller rectangle is rotating in radians * } * *
* * @alt * 40 by 10 rect in center rotates with mouse moves. 20 by 10 rect moves faster. * * */ p5.prototype.angleMode = function(mode) { if (mode === constants.DEGREES || mode === constants.RADIANS) { this._angleMode = mode; } }; /** * converts angles from the current angleMode to RADIANS * * @method _toRadians * @private * @param {Number} angle * @returns {Number} */ p5.prototype._toRadians = function(angle) { if (this._angleMode === constants.DEGREES) { return angle * constants.DEG_TO_RAD; } return angle; }; /** * converts angles from the current angleMode to DEGREES * * @method _toDegrees * @private * @param {Number} angle * @returns {Number} */ p5.prototype._toDegrees = function(angle) { if (this._angleMode === constants.RADIANS) { return angle * constants.RAD_TO_DEG; } return angle; }; /** * converts angles from RADIANS into the current angleMode * * @method _fromRadians * @private * @param {Number} angle * @returns {Number} */ p5.prototype._fromRadians = function(angle) { if (this._angleMode === constants.DEGREES) { return angle * constants.RAD_TO_DEG; } return angle; }; module.exports = p5; },{"../core/constants":21,"../core/core":22}],56:[function(_dereq_,module,exports){ /** * @module Typography * @submodule Attributes * @for p5 * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Sets the current alignment for drawing text. Accepts two * arguments: horizAlign (LEFT, CENTER, or RIGHT) and * vertAlign (TOP, BOTTOM, CENTER, or BASELINE). * * The horizAlign parameter is in reference to the x value * of the text() function, while the vertAlign parameter is * in reference to the y value. * * So if you write textAlign(LEFT), you are aligning the left * edge of your text to the x value you give in text(). If you * write textAlign(RIGHT, TOP), you are aligning the right edge * of your text to the x value and the top of edge of the text * to the y value. * * @method textAlign * @param {Constant} horizAlign horizontal alignment, either LEFT, * CENTER, or RIGHT * @param {Constant} [vertAlign] vertical alignment, either TOP, * BOTTOM, CENTER, or BASELINE * @chainable * @example *
* * textSize(16); * textAlign(RIGHT); * text('ABCD', 50, 30); * textAlign(CENTER); * text('EFGH', 50, 50); * textAlign(LEFT); * text('IJKL', 50, 70); * *
* * @alt *Letters ABCD displayed at top right, EFGH at center and IJKL at bottom left. * */ /** * @method textAlign * @return {Object} */ p5.prototype.textAlign = function(horizAlign, vertAlign) { p5._validateParameters('textAlign', arguments); return this._renderer.textAlign.apply(this._renderer, arguments); }; /** * Sets/gets the spacing, in pixels, between lines of text. This * setting will be used in all subsequent calls to the text() function. * * @method textLeading * @param {Number} leading the size in pixels for spacing between lines * @chainable * * @example *
* * // Text to display. The "\n" is a "new line" character * var lines = 'L1\nL2\nL3'; * textSize(12); * * textLeading(10); // Set leading to 10 * text(lines, 10, 25); * * textLeading(20); // Set leading to 20 * text(lines, 40, 25); * * textLeading(30); // Set leading to 30 * text(lines, 70, 25); * *
* * @alt *set L1 L2 & L3 displayed vertically 3 times. spacing increases for each set */ /** * @method textLeading * @return {Number} */ p5.prototype.textLeading = function(theLeading) { p5._validateParameters('textLeading', arguments); return this._renderer.textLeading.apply(this._renderer, arguments); }; /** * Sets/gets the current font size. This size will be used in all subsequent * calls to the text() function. Font size is measured in pixels. * * @method textSize * @param {Number} theSize the size of the letters in units of pixels * @chainable * * @example *
* * textSize(12); * text('Font Size 12', 10, 30); * textSize(14); * text('Font Size 14', 10, 60); * textSize(16); * text('Font Size 16', 10, 90); * *
* * @alt *Font Size 12 displayed small, Font Size 14 medium & Font Size 16 large */ /** * @method textSize * @return {Number} */ p5.prototype.textSize = function(theSize) { p5._validateParameters('textSize', arguments); return this._renderer.textSize.apply(this._renderer, arguments); }; /** * Sets/gets the style of the text for system fonts to NORMAL, ITALIC, or BOLD. * Note: this may be is overridden by CSS styling. For non-system fonts * (opentype, truetype, etc.) please load styled fonts instead. * * @method textStyle * @param {Constant} theStyle styling for text, either NORMAL, * ITALIC, or BOLD * @chainable * @example *
* * strokeWeight(0); * textSize(12); * textStyle(NORMAL); * text('Font Style Normal', 10, 30); * textStyle(ITALIC); * text('Font Style Italic', 10, 60); * textStyle(BOLD); * text('Font Style Bold', 10, 90); * *
* * @alt *words Font Style Normal displayed normally, Italic in italic and bold in bold */ /** * @method textStyle * @return {String} */ p5.prototype.textStyle = function(theStyle) { p5._validateParameters('textStyle', arguments); return this._renderer.textStyle.apply(this._renderer, arguments); }; /** * Calculates and returns the width of any character or text string. * * @method textWidth * @param {String} theText the String of characters to measure * @return {Number} * @example *
* * textSize(28); * * var aChar = 'P'; * var cWidth = textWidth(aChar); * text(aChar, 0, 40); * line(cWidth, 0, cWidth, 50); * * var aString = 'p5.js'; * var sWidth = textWidth(aString); * text(aString, 0, 85); * line(sWidth, 50, sWidth, 100); * *
* * @alt *Letter P and p5.js are displayed with vertical lines at end. P is wide * */ p5.prototype.textWidth = function(theText) { p5._validateParameters('textWidth', arguments); if (theText.length === 0) { return 0; } return this._renderer.textWidth.apply(this._renderer, arguments); }; /** * Returns the ascent of the current font at its current size. The ascent * represents the distance, in pixels, of the tallest character above * the baseline. * @method textAscent * @return {Number} * @example *
* * var base = height * 0.75; * var scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size * var asc = textAscent() * scalar; // Calc ascent * line(0, base - asc, width, base - asc); * text('dp', 0, base); // Draw text on baseline * * textSize(64); // Increase text size * asc = textAscent() * scalar; // Recalc ascent * line(40, base - asc, width, base - asc); * text('dp', 40, base); // Draw text on baseline * *
*/ p5.prototype.textAscent = function() { p5._validateParameters('textAscent', arguments); return this._renderer.textAscent(); }; /** * Returns the descent of the current font at its current size. The descent * represents the distance, in pixels, of the character with the longest * descender below the baseline. * @method textDescent * @return {Number} * @example *
* * var base = height * 0.75; * var scalar = 0.8; // Different for each font * * textSize(32); // Set initial text size * var desc = textDescent() * scalar; // Calc ascent * line(0, base + desc, width, base + desc); * text('dp', 0, base); // Draw text on baseline * * textSize(64); // Increase text size * desc = textDescent() * scalar; // Recalc ascent * line(40, base + desc, width, base + desc); * text('dp', 40, base); // Draw text on baseline * *
*/ p5.prototype.textDescent = function() { p5._validateParameters('textDescent', arguments); return this._renderer.textDescent(); }; /** * Helper function to measure ascent and descent. */ p5.prototype._updateTextMetrics = function() { return this._renderer._updateTextMetrics(); }; module.exports = p5; },{"../core/core":22}],57:[function(_dereq_,module,exports){ /** * @module Typography * @submodule Loading & Displaying * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); var opentype = _dereq_('opentype.js'); _dereq_('../core/error_helpers'); /** * Loads an opentype font file (.otf, .ttf) from a file or a URL, * and returns a PFont Object. This method is asynchronous, * meaning it may not finish before the next line in your sketch * is executed. *

* The path to the font should be relative to the HTML file * that links in your sketch. Loading an from a URL or other * remote location may be blocked due to your browser's built-in * security. * * @method loadFont * @param {String} path name of the file or url to load * @param {Function} [callback] function to be executed after * loadFont() completes * @param {Function} [onError] function to be executed if * an error occurs * @return {p5.Font} p5.Font object * @example * *

Calling loadFont() inside preload() guarantees that the load * operation will have completed before setup() and draw() are called.

* *
* var myFont; * function preload() { * myFont = loadFont('assets/AvenirNextLTPro-Demi.otf'); * } * * function setup() { * fill('#ED225D'); * textFont(myFont); * textSize(36); * text('p5*js', 10, 50); * } *
* * Outside of preload(), you may supply a callback function to handle the * object: * *
* function setup() { * loadFont('assets/AvenirNextLTPro-Demi.otf', drawText); * } * * function drawText(font) { * fill('#ED225D'); * textFont(font, 36); * text('p5*js', 10, 50); * } *
* *

You can also use the string name of the font to style other HTML * elements.

* *
* function preload() { * loadFont('assets/Avenir.otf'); * } * * function setup() { * var myDiv = createDiv('hello there'); * myDiv.style('font-family', 'Avenir'); * } *
* * @alt * p5*js in p5's theme dark pink * p5*js in p5's theme dark pink * */ p5.prototype.loadFont = function(path, onSuccess, onError) { p5._validateParameters('loadFont', arguments); var p5Font = new p5.Font(this); var self = this; opentype.load(path, function(err, font) { if (err) { if (typeof onError !== 'undefined') { return onError(err); } p5._friendlyFileLoadError(4, path); console.error(err, path); return; } p5Font.font = font; if (typeof onSuccess !== 'undefined') { onSuccess(p5Font); } self._decrementPreload(); // check that we have an acceptable font type var validFontTypes = ['ttf', 'otf', 'woff', 'woff2'], fileNoPath = path .split('\\') .pop() .split('/') .pop(), lastDotIdx = fileNoPath.lastIndexOf('.'), fontFamily, newStyle, fileExt = lastDotIdx < 1 ? null : fileNoPath.substr(lastDotIdx + 1); // if so, add it to the DOM (name-only) for use with p5.dom if (validFontTypes.indexOf(fileExt) > -1) { fontFamily = fileNoPath.substr(0, lastDotIdx); newStyle = document.createElement('style'); newStyle.appendChild( document.createTextNode( '\n@font-face {' + '\nfont-family: ' + fontFamily + ';\nsrc: url(' + path + ');\n}\n' ) ); document.head.appendChild(newStyle); } }); return p5Font; }; /** * Draws text to the screen. Displays the information specified in the first * parameter on the screen in the position specified by the additional * parameters. A default font will be used unless a font is set with the * textFont() function and a default size will be used unless a font is set * with textSize(). Change the color of the text with the fill() function. * Change the outline of the text with the stroke() and strokeWeight() * functions. *

* The text displays in relation to the textAlign() function, which gives the * option to draw to the left, right, and center of the coordinates. *

* The x2 and y2 parameters define a rectangular area to display within and * may only be used with string data. When these parameters are specified, * they are interpreted based on the current rectMode() setting. Text that * does not fit completely within the rectangle specified will not be drawn * to the screen. * * @method text * @param {String|Object|Array|Number|Boolean} str the alphanumeric * symbols to be displayed * @param {Number} x x-coordinate of text * @param {Number} y y-coordinate of text * @param {Number} [x2] by default, the width of the text box, * see rectMode() for more info * @param {Number} [y2] by default, the height of the text box, * see rectMode() for more info * @chainable * @example *
* * textSize(32); * text('word', 10, 30); * fill(0, 102, 153); * text('word', 10, 60); * fill(0, 102, 153, 51); * text('word', 10, 90); * *
*
* * var s = 'The quick brown fox jumped over the lazy dog.'; * fill(50); * text(s, 10, 10, 70, 80); // Text wraps within text box * *
* * @alt *'word' displayed 3 times going from black, blue to translucent blue * The quick brown fox jumped over the lazy dog. * */ p5.prototype.text = function(str, x, y, maxWidth, maxHeight) { p5._validateParameters('text', arguments); return !(this._renderer._doFill || this._renderer._doStroke) ? this : this._renderer.text.apply(this._renderer, arguments); }; /** * Sets the current font that will be drawn with the text() function. * * @method textFont * @return {Object} the current font * * @example *
* * fill(0); * textSize(12); * textFont('Georgia'); * text('Georgia', 12, 30); * textFont('Helvetica'); * text('Helvetica', 12, 60); * *
*
* * var fontRegular, fontItalic, fontBold; * function preload() { * fontRegular = loadFont('assets/Regular.otf'); * fontItalic = loadFont('assets/Italic.ttf'); * fontBold = loadFont('assets/Bold.ttf'); * } * function setup() { * background(210); * fill(0) .strokeWeight(0) .textSize(10); * textFont(fontRegular); * text('Font Style Normal', 10, 30); * textFont(fontItalic); * text('Font Style Italic', 10, 50); * textFont(fontBold); * text('Font Style Bold', 10, 70); * } * *
* * @alt *words Font Style Normal displayed normally, Italic in italic and bold in bold */ /** * @method textFont * @param {Object|String} font a font loaded via loadFont(), or a String * representing a web safe font (a font * that is generally available across all systems) * @param {Number} [size] the font size to use * @chainable */ p5.prototype.textFont = function(theFont, theSize) { p5._validateParameters('textFont', arguments); if (arguments.length) { if (!theFont) { throw Error('null font passed to textFont'); } this._renderer._setProperty('_textFont', theFont); if (theSize) { this._renderer._setProperty('_textSize', theSize); this._renderer._setProperty( '_textLeading', theSize * constants._DEFAULT_LEADMULT ); } return this._renderer._applyTextProperties(); } return this._renderer._textFont; }; module.exports = p5; },{"../core/constants":21,"../core/core":22,"../core/error_helpers":25,"opentype.js":10}],58:[function(_dereq_,module,exports){ /** * This module defines the p5.Font class and functions for * drawing text to the display canvas. * @module Typography * @submodule Font * @requires core * @requires constants */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); /* * TODO: * -- kerning * -- alignment: justified? */ /** * Base class for font handling * @class p5.Font * @param {p5} [pInst] pointer to p5 instance */ p5.Font = function(p) { this.parent = p; this.cache = {}; /** * Underlying opentype font implementation * @property font */ this.font = undefined; }; p5.Font.prototype.list = function() { // TODO throw 'not yet implemented'; }; /** * Returns a tight bounding box for the given text string using this * font (currently only supports single lines) * * @method textBounds * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Number} [fontSize] font size to use (optional) * @param {Object} [options] opentype options (optional) * * @return {Object} a rectangle object with properties: x, y, w, h * * @example *
* * var font; * var textString = 'Lorem ipsum dolor sit amet.'; * function preload() { * font = loadFont('./assets/Regular.otf'); * } * function setup() { * background(210); * * var bbox = font.textBounds(textString, 10, 30, 12); * fill(255); * stroke(0); * rect(bbox.x, bbox.y, bbox.w, bbox.h); * fill(0); * noStroke(); * * textFont(font); * textSize(12); * text(textString, 10, 30); * } * *
* * @alt *words Lorem ipsum dol go off canvas and contained by white bounding box * */ p5.Font.prototype.textBounds = function(str, x, y, fontSize, options) { x = x !== undefined ? x : 0; y = y !== undefined ? y : 0; fontSize = fontSize || this.parent._renderer._textSize; // Check cache for existing bounds. Take into consideration the text alignment // settings. Default alignment should match opentype's origin: left-aligned & // alphabetic baseline. var p = (options && options.renderer && options.renderer._pInst) || this.parent, ctx = p._renderer.drawingContext, alignment = ctx.textAlign || constants.LEFT, baseline = ctx.textBaseline || constants.BASELINE, key = cacheKey('textBounds', str, x, y, fontSize, alignment, baseline), result = this.cache[key]; if (!result) { var minX, minY, maxX, maxY, pos, xCoords = [], yCoords = [], scale = this._scale(fontSize); this.font.forEachGlyph(str, x, y, fontSize, options, function( glyph, gX, gY, gFontSize ) { var gm = glyph.getMetrics(); xCoords.push(gX + gm.xMin * scale); xCoords.push(gX + gm.xMax * scale); yCoords.push(gY + -gm.yMin * scale); yCoords.push(gY + -gm.yMax * scale); }); minX = Math.min.apply(null, xCoords); minY = Math.min.apply(null, yCoords); maxX = Math.max.apply(null, xCoords); maxY = Math.max.apply(null, yCoords); result = { x: minX, y: minY, h: maxY - minY, w: maxX - minX, advance: minX - x }; // Bounds are now calculated, so shift the x & y to match alignment settings pos = this._handleAlignment( p, ctx, str, result.x, result.y, result.w + result.advance ); result.x = pos.x; result.y = pos.y; this.cache[ cacheKey('textBounds', str, x, y, fontSize, alignment, baseline) ] = result; } return result; }; /** * Computes an array of points following the path for specified text * * @method textToPoints * @param {String} txt a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Number} fontSize font size to use (optional) * @param {Object} [options] an (optional) object that can contain: * *
sampleFactor - the ratio of path-length to number of samples * (default=.25); higher values yield more points and are therefore * more precise * *
simplifyThreshold - if set to a non-zero value, collinear points will be * be removed from the polygon; the value represents the threshold angle to use * when determining whether two edges are collinear * * @return {Array} an array of points, each with x, y, alpha (the path angle) * @example *
* * var font; * function preload() { * font = loadFont('./assets/Avenir.otf'); * } * * var points; * var bounds; * function setup() { * createCanvas(100, 100); * stroke(0); * fill(255, 104, 204); * * points = font.textToPoints('p5', 0, 0, 10, { * sampleFactor: 5, * simplifyThreshold: 0 * }); * bounds = font.textBounds(' p5 ', 0, 0, 10); * } * * function draw() { * background(255); * beginShape(); * translate(-bounds.x * width / bounds.w, -bounds.y * height / bounds.h); * for (var i = 0; i < points.length; i++) { * var p = points[i]; * vertex( * p.x * width / bounds.w + * sin(20 * p.y / bounds.h + millis() / 1000) * width / 30, * p.y * height / bounds.h * ); * } * endShape(CLOSE); * } * *
* */ p5.Font.prototype.textToPoints = function(txt, x, y, fontSize, options) { var xoff = 0, result = [], glyphs = this._getGlyphs(txt); function isSpace(i) { return ( (glyphs[i].name && glyphs[i].name === 'space') || (txt.length === glyphs.length && txt[i] === ' ') || (glyphs[i].index && glyphs[i].index === 3) ); } fontSize = fontSize || this.parent._renderer._textSize; for (var i = 0; i < glyphs.length; i++) { if (!isSpace(i)) { // fix to #1817, #2069 var gpath = glyphs[i].getPath(x, y, fontSize), paths = splitPaths(gpath.commands); for (var j = 0; j < paths.length; j++) { var pts = pathToPoints(paths[j], options); for (var k = 0; k < pts.length; k++) { pts[k].x += xoff; result.push(pts[k]); } } } xoff += glyphs[i].advanceWidth * this._scale(fontSize); } return result; }; // ----------------------------- End API ------------------------------ /** * Returns the set of opentype glyphs for the supplied string. * * Note that there is not a strict one-to-one mapping between characters * and glyphs, so the list of returned glyphs can be larger or smaller * than the length of the given string. * * @private * @param {String} str the string to be converted * @return {Array} the opentype glyphs */ p5.Font.prototype._getGlyphs = function(str) { return this.font.stringToGlyphs(str); }; /** * Returns an opentype path for the supplied string and position. * * @private * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional) * @return {Object} the opentype path */ p5.Font.prototype._getPath = function(line, x, y, options) { var p = (options && options.renderer && options.renderer._pInst) || this.parent, ctx = p._renderer.drawingContext, pos = this._handleAlignment(p, ctx, line, x, y); return this.font.getPath(line, pos.x, pos.y, p._renderer._textSize, options); }; /* * Creates an SVG-formatted path-data string * (See http://www.w3.org/TR/SVG/paths.html#PathData) * from the given opentype path or string/position * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional), set options.decimals * to set the decimal precision of the path-data * * @return {Object} this p5.Font object */ p5.Font.prototype._getPathData = function(line, x, y, options) { var decimals = 3; // create path from string/position if (typeof line === 'string' && arguments.length > 2) { line = this._getPath(line, x, y, options); } else if (typeof x === 'object') { // handle options specified in 2nd arg options = x; } // handle svg arguments if (options && typeof options.decimals === 'number') { decimals = options.decimals; } return line.toPathData(decimals); }; /* * Creates an SVG element, as a string, * from the given opentype path or string/position * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional), set options.decimals * to set the decimal precision of the path-data in the element, * options.fill to set the fill color for the element, * options.stroke to set the stroke color for the element, * options.strokeWidth to set the strokeWidth for the element. * * @return {Object} this p5.Font object */ p5.Font.prototype._getSVG = function(line, x, y, options) { var decimals = 3; // create path from string/position if (typeof line === 'string' && arguments.length > 2) { line = this._getPath(line, x, y, options); } else if (typeof x === 'object') { // handle options specified in 2nd arg options = x; } // handle svg arguments if (options) { if (typeof options.decimals === 'number') { decimals = options.decimals; } if (typeof options.strokeWidth === 'number') { line.strokeWidth = options.strokeWidth; } if (typeof options.fill !== 'undefined') { line.fill = options.fill; } if (typeof options.stroke !== 'undefined') { line.stroke = options.stroke; } } return line.toSVG(decimals); }; /* * Renders an opentype path or string/position * to the current graphics context * * @param {Object} path an opentype path, OR the following: * * @param {String} line a line of text * @param {Number} x x-position * @param {Number} y y-position * @param {Object} options opentype options (optional) * * @return {p5.Font} this p5.Font object */ p5.Font.prototype._renderPath = function(line, x, y, options) { var pdata, pg = (options && options.renderer) || this.parent._renderer, ctx = pg.drawingContext; if (typeof line === 'object' && line.commands) { pdata = line.commands; } else { //pos = handleAlignment(p, ctx, line, x, y); pdata = this._getPath(line, x, y, options).commands; } ctx.beginPath(); for (var i = 0; i < pdata.length; i += 1) { var cmd = pdata[i]; if (cmd.type === 'M') { ctx.moveTo(cmd.x, cmd.y); } else if (cmd.type === 'L') { ctx.lineTo(cmd.x, cmd.y); } else if (cmd.type === 'C') { ctx.bezierCurveTo(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { ctx.quadraticCurveTo(cmd.x1, cmd.y1, cmd.x, cmd.y); } else if (cmd.type === 'Z') { ctx.closePath(); } } // only draw stroke if manually set by user if (pg._doStroke && pg._strokeSet) { ctx.stroke(); } if (pg._doFill) { // if fill hasn't been set by user, use default-text-fill if (!pg._fillSet) { pg._setFill(constants._DEFAULT_TEXT_FILL); } ctx.fill(); } return this; }; p5.Font.prototype._textWidth = function(str, fontSize) { return this.font.getAdvanceWidth(str, fontSize); }; p5.Font.prototype._textAscent = function(fontSize) { return this.font.ascender * this._scale(fontSize); }; p5.Font.prototype._textDescent = function(fontSize) { return -this.font.descender * this._scale(fontSize); }; p5.Font.prototype._scale = function(fontSize) { return ( 1 / this.font.unitsPerEm * (fontSize || this.parent._renderer._textSize) ); }; p5.Font.prototype._handleAlignment = function(p, ctx, line, x, y, textWidth) { var fontSize = p._renderer._textSize, textAscent = this._textAscent(fontSize), textDescent = this._textDescent(fontSize); textWidth = textWidth !== undefined ? textWidth : this._textWidth(line, fontSize); if (ctx.textAlign === constants.CENTER) { x -= textWidth / 2; } else if (ctx.textAlign === constants.RIGHT) { x -= textWidth; } if (ctx.textBaseline === constants.TOP) { y += textAscent; } else if (ctx.textBaseline === constants._CTX_MIDDLE) { y += textAscent / 2; } else if (ctx.textBaseline === constants.BOTTOM) { y -= textDescent; } return { x: x, y: y }; }; // path-utils function pathToPoints(cmds, options) { var opts = parseOpts(options, { sampleFactor: 0.1, simplifyThreshold: 0 }); var len = pointAtLength(cmds, 0, 1), // total-length t = len / (len * opts.sampleFactor), pts = []; for (var i = 0; i < len; i += t) { pts.push(pointAtLength(cmds, i)); } if (opts.simplifyThreshold) { /*var count = */ simplify(pts, opts.simplifyThreshold); //console.log('Simplify: removed ' + count + ' pts'); } return pts; } function simplify(pts, angle) { angle = typeof angle === 'undefined' ? 0 : angle; var num = 0; for (var i = pts.length - 1; pts.length > 3 && i >= 0; --i) { if (collinear(at(pts, i - 1), at(pts, i), at(pts, i + 1), angle)) { // Remove the middle point pts.splice(i % pts.length, 1); num++; } } return num; } function splitPaths(cmds) { var paths = [], current; for (var i = 0; i < cmds.length; i++) { if (cmds[i].type === 'M') { if (current) { paths.push(current); } current = []; } current.push(cmdToArr(cmds[i])); } paths.push(current); return paths; } function cmdToArr(cmd) { var arr = [cmd.type]; if (cmd.type === 'M' || cmd.type === 'L') { // moveto or lineto arr.push(cmd.x, cmd.y); } else if (cmd.type === 'C') { arr.push(cmd.x1, cmd.y1, cmd.x2, cmd.y2, cmd.x, cmd.y); } else if (cmd.type === 'Q') { arr.push(cmd.x1, cmd.y1, cmd.x, cmd.y); } // else if (cmd.type === 'Z') { /* no-op */ } return arr; } function parseOpts(options, defaults) { if (typeof options !== 'object') { options = defaults; } else { for (var key in defaults) { if (typeof options[key] === 'undefined') { options[key] = defaults[key]; } } } return options; } //////////////////////// Helpers //////////////////////////// function at(v, i) { var s = v.length; return v[i < 0 ? i % s + s : i % s]; } function collinear(a, b, c, thresholdAngle) { if (!thresholdAngle) { return areaTriangle(a, b, c) === 0; } if (typeof collinear.tmpPoint1 === 'undefined') { collinear.tmpPoint1 = []; collinear.tmpPoint2 = []; } var ab = collinear.tmpPoint1, bc = collinear.tmpPoint2; ab.x = b.x - a.x; ab.y = b.y - a.y; bc.x = c.x - b.x; bc.y = c.y - b.y; var dot = ab.x * bc.x + ab.y * bc.y, magA = Math.sqrt(ab.x * ab.x + ab.y * ab.y), magB = Math.sqrt(bc.x * bc.x + bc.y * bc.y), angle = Math.acos(dot / (magA * magB)); return angle < thresholdAngle; } function areaTriangle(a, b, c) { return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]); } // Portions of below code copyright 2008 Dmitry Baranovskiy (via MIT license) function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t, t13 = Math.pow(t1, 3), t12 = Math.pow(t1, 2), t2 = t * t, t3 = t2 * t, x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y, mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x), my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y), nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x), ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y), ax = t1 * p1x + t * c1x, ay = t1 * p1y + t * c1y, cx = t1 * c2x + t * p2x, cy = t1 * c2y + t * p2y, alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; if (mx > nx || my < ny) { alpha += 180; } return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; } function getPointAtSegmentLength( p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length ) { return length == null ? bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) : findDotsAtSegment( p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) ); } function pointAtLength(path, length, istotal) { path = path2curve(path); var x, y, p, l, sp = '', subpaths = {}, point, len = 0; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] === 'M') { x = +p[1]; y = +p[2]; } else { l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); if (len + l > length) { if (!istotal) { point = getPointAtSegmentLength( x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len ); return { x: point.x, y: point.y, alpha: point.alpha }; } } len += l; x = +p[5]; y = +p[6]; } sp += p.shift() + p; } subpaths.end = sp; point = istotal ? len : findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1); if (point.alpha) { point = { x: point.x, y: point.y, alpha: point.alpha }; } return point; } function pathToAbsolute(pathArray) { var res = [], x = 0, y = 0, mx = 0, my = 0, start = 0; if (!pathArray) { // console.warn("Unexpected state: undefined pathArray"); // shouldn't happen return res; } if (pathArray[0][0] === 'M') { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ['M', x, y]; } var dots, crz = pathArray.length === 3 && pathArray[0][0] === 'M' && pathArray[1][0].toUpperCase() === 'R' && pathArray[2][0].toUpperCase() === 'Z'; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push((r = [])); pa = pathArray[i]; if (pa[0] !== String.prototype.toUpperCase.call(pa[0])) { r[0] = String.prototype.toUpperCase.call(pa[0]); switch (r[0]) { case 'A': r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] + x); r[7] = +(pa[7] + y); break; case 'V': r[1] = +pa[1] + y; break; case 'H': r[1] = +pa[1] + x; break; case 'R': dots = [x, y].concat(pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); break; case 'M': mx = +pa[1] + x; my = +pa[2] + y; break; default: for (j = 1, jj = pa.length; j < jj; j++) { r[j] = +pa[j] + (j % 2 ? x : y); } } } else if (pa[0] === 'R') { dots = [x, y].concat(pa.slice(1)); res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); r = ['R'].concat(pa.slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } switch (r[0]) { case 'Z': x = mx; y = my; break; case 'H': x = r[1]; break; case 'V': y = r[1]; break; case 'M': mx = r[r.length - 2]; my = r[r.length - 1]; break; default: x = r[r.length - 2]; y = r[r.length - 1]; } } return res; } function path2curve(path, path2) { var p = pathToAbsolute(path), p2 = path2 && pathToAbsolute(path2); var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var pcoms1 = []; // path commands of original path p var pcoms2 = []; // path commands of original path p2 var ii; var processPath = function(path, d, pcom) { var nx, ny, tq = { T: 1, Q: 1 }; if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; } if (!(path[0] in tq)) { d.qx = d.qy = null; } switch (path[0]) { case 'M': d.X = path[1]; d.Y = path[2]; break; case 'A': path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))); break; case 'S': if (pcom === 'C' || pcom === 'S') { nx = d.x * 2 - d.bx; ny = d.y * 2 - d.by; } else { nx = d.x; ny = d.y; } path = ['C', nx, ny].concat(path.slice(1)); break; case 'T': if (pcom === 'Q' || pcom === 'T') { d.qx = d.x * 2 - d.qx; d.qy = d.y * 2 - d.qy; } else { d.qx = d.x; d.qy = d.y; } path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case 'Q': d.qx = path[1]; d.qy = path[2]; path = ['C'].concat( q2c(d.x, d.y, path[1], path[2], path[3], path[4]) ); break; case 'L': path = ['C'].concat(l2c(d.x, d.y, path[1], path[2])); break; case 'H': path = ['C'].concat(l2c(d.x, d.y, path[1], d.y)); break; case 'V': path = ['C'].concat(l2c(d.x, d.y, d.x, path[1])); break; case 'Z': path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y)); break; } return path; }, fixArc = function(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pcoms1[i] = 'A'; if (p2) { pcoms2[i] = 'A'; } pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); } pp.splice(i, 1); ii = Math.max(p.length, (p2 && p2.length) || 0); } }, fixM = function(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { path2.splice(i, 0, ['M', a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = Math.max(p.length, (p2 && p2.length) || 0); } }; var pfirst = ''; // temporary holder for original path command var pcom = ''; // holder for previous path command of original path ii = Math.max(p.length, (p2 && p2.length) || 0); for (var i = 0; i < ii; i++) { if (p[i]) { pfirst = p[i][0]; } // save current path command if (pfirst !== 'C') { pcoms1[i] = pfirst; // Save current path command if (i) { pcom = pcoms1[i - 1]; } // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); if (pcoms1[i] !== 'A' && pfirst === 'C') { pcoms1[i] = 'C'; } fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 if (p2) { // the same procedures is done to p2 if (p2[i]) { pfirst = p2[i][0]; } if (pfirst !== 'C') { pcoms2[i] = pfirst; if (i) { pcom = pcoms2[i - 1]; } } p2[i] = processPath(p2[i], attrs2, pcom); if (pcoms2[i] !== 'A' && pfirst === 'C') { pcoms2[i] = 'C'; } fixArc(p2, i); } fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i], seg2 = p2 && p2[i], seglen = seg.length, seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } return p2 ? [p, p2] : p; } function a2c(x1, y1, rx, ry, angle, lac, sweep_flag, x2, y2, recursive) { // for more information of where this Math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes var PI = Math.PI, _120 = PI * 120 / 180, f1, f2, cx, cy, rad = PI / 180 * (+angle || 0), res = [], xy, rotate = function(x, y, rad) { var X = x * Math.cos(rad) - y * Math.sin(rad), Y = x * Math.sin(rad) + y * Math.cos(rad); return { x: X, y: Y }; }; if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; var x = (x1 - x2) / 2, y = (y1 - y2) / 2, h = x * x / (rx * rx) + y * y / (ry * ry); if (h > 1) { h = Math.sqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx, ry2 = ry * ry; var k = (lac === sweep_flag ? -1 : 1) * Math.sqrt( Math.abs( (rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x) ) ); cx = k * rx * y / ry + (x1 + x2) / 2; cy = k * -ry * x / rx + (y1 + y2) / 2; f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? PI - f1 : f1; f2 = x2 < cx ? PI - f2 : f2; if (f1 < 0) { f1 = PI * 2 + f1; } if (f2 < 0) { f2 = PI * 2 + f2; } if (sweep_flag && f1 > f2) { f1 = f1 - PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (Math.abs(df) > _120) { var f2old = f2, x2old = x2, y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * Math.cos(f2); y2 = cy + ry * Math.sin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [ f2, f2old, cx, cy ]); } df = f2 - f1; var c1 = Math.cos(f1), s1 = Math.sin(f1), c2 = Math.cos(f2), s2 = Math.sin(f2), t = Math.tan(df / 4), hx = 4 / 3 * rx * t, hy = 4 / 3 * ry * t, m1 = [x1, y1], m2 = [x1 + hx * s1, y1 - hy * c1], m3 = [x2 + hx * s2, y2 - hy * c2], m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4].concat(res); } else { res = [m2, m3, m4] .concat(res) .join() .split(','); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; } } // http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ { x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] } ]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 === i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 === i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 === i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push([ 'C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); } return d; } function l2c(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; } function q2c(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3, _23 = 2 / 3; return [ _13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2 ]; } function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2; var n = 12; var Tvalues = [ -0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816 ]; var sum = 0; var Cvalues = [ 0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472 ]; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, xbase = base3(ct, x1, x2, x3, x4), ybase = base3(ct, y1, y2, y3, y4), comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; } function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } var t = 1, step = t / 2, t2 = t - step, l, e = 0.01; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); while (Math.abs(l - ll) > e) { step /= 2; t2 += (l < ll ? 1 : -1) * step; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); } return t2; } function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function cacheKey() { var hash = ''; for (var i = arguments.length - 1; i >= 0; --i) { var v = arguments[i]; hash += v === Object(v) ? JSON.stringify(v) : v; } return hash; } module.exports = p5; },{"../core/constants":21,"../core/core":22}],59:[function(_dereq_,module,exports){ /** * @module Data * @submodule Array Functions * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Adds a value to the end of an array. Extends the length of * the array by one. Maps to Array.push(). * * @method append * @deprecated Use array.push(value) instead. * @param {Array} array Array to append * @param {any} value to be added to the Array * @example *
* function setup() { * var myArray = ['Mango', 'Apple', 'Papaya']; * print(myArray); // ['Mango', 'Apple', 'Papaya'] * * append(myArray, 'Peach'); * print(myArray); // ['Mango', 'Apple', 'Papaya', 'Peach'] * } *
*/ p5.prototype.append = function(array, value) { array.push(value); return array; }; /** * Copies an array (or part of an array) to another array. The src array is * copied to the dst array, beginning at the position specified by * srcPosition and into the position specified by dstPosition. The number of * elements to copy is determined by length. Note that copying values * overwrites existing values in the destination array. To append values * instead of overwriting them, use concat(). *

* The simplified version with only two arguments, arrayCopy(src, dst), * copies an entire array to another of the same size. It is equivalent to * arrayCopy(src, 0, dst, 0, src.length). *

* Using this function is far more efficient for copying array data than * iterating through a for() loop and copying each element individually. * * @method arrayCopy * @deprecated * @param {Array} src the source Array * @param {Integer} srcPosition starting position in the source Array * @param {Array} dst the destination Array * @param {Integer} dstPosition starting position in the destination Array * @param {Integer} length number of Array elements to be copied * * @example *
* var src = ['A', 'B', 'C']; * var dst = [1, 2, 3]; * var srcPosition = 1; * var dstPosition = 0; * var length = 2; * * print(src); // ['A', 'B', 'C'] * print(dst); // [ 1 , 2 , 3 ] * * arrayCopy(src, srcPosition, dst, dstPosition, length); * print(dst); // ['B', 'C', 3] *
*/ /** * @method arrayCopy * @deprecated Use arr1.copyWithin(arr2) instead. * @param {Array} src * @param {Array} dst * @param {Integer} [length] */ p5.prototype.arrayCopy = function(src, srcPosition, dst, dstPosition, length) { // the index to begin splicing from dst array var start; var end; if (typeof length !== 'undefined') { end = Math.min(length, src.length); start = dstPosition; src = src.slice(srcPosition, end + srcPosition); } else { if (typeof dst !== 'undefined') { // src, dst, length // rename so we don't get confused end = dst; end = Math.min(end, src.length); } else { // src, dst end = src.length; } start = 0; // rename so we don't get confused dst = srcPosition; src = src.slice(0, end); } // Since we are not returning the array and JavaScript is pass by reference // we must modify the actual values of the array // instead of reassigning arrays Array.prototype.splice.apply(dst, [start, end].concat(src)); }; /** * Concatenates two arrays, maps to Array.concat(). Does not modify the * input arrays. * * @method concat * @deprecated Use arr1.concat(arr2) instead. * @param {Array} a first Array to concatenate * @param {Array} b second Array to concatenate * @return {Array} concatenated array * * @example *
* function setup() { * var arr1 = ['A', 'B', 'C']; * var arr2 = [1, 2, 3]; * * print(arr1); // ['A','B','C'] * print(arr2); // [1,2,3] * * var arr3 = concat(arr1, arr2); * * print(arr1); // ['A','B','C'] * print(arr2); // [1, 2, 3] * print(arr3); // ['A','B','C', 1, 2, 3] * } *
*/ p5.prototype.concat = function(list0, list1) { return list0.concat(list1); }; /** * Reverses the order of an array, maps to Array.reverse() * * @method reverse * @deprecated Use array.reverse() instead. * @param {Array} list Array to reverse * @example *
* function setup() { * var myArray = ['A', 'B', 'C']; * print(myArray); // ['A','B','C'] * * reverse(myArray); * print(myArray); // ['C','B','A'] * } *
*/ p5.prototype.reverse = function(list) { return list.reverse(); }; /** * Decreases an array by one element and returns the shortened array, * maps to Array.pop(). * * @method shorten * @deprecated Use array.pop() instead. * @param {Array} list Array to shorten * @return {Array} shortened Array * @example *
* function setup() { * var myArray = ['A', 'B', 'C']; * print(myArray); // ['A', 'B', 'C'] * var newArray = shorten(myArray); * print(myArray); // ['A','B','C'] * print(newArray); // ['A','B'] * } *
*/ p5.prototype.shorten = function(list) { list.pop(); return list; }; /** * Randomizes the order of the elements of an array. Implements * * Fisher-Yates Shuffle Algorithm. * * @method shuffle * @deprecated See shuffling an array with JS instead. * @param {Array} array Array to shuffle * @param {Boolean} [bool] modify passed array * @return {Array} shuffled Array * @example *
* function setup() { * var regularArr = ['ABC', 'def', createVector(), TAU, Math.E]; * print(regularArr); * shuffle(regularArr, true); // force modifications to passed array * print(regularArr); * * // By default shuffle() returns a shuffled cloned array: * var newArr = shuffle(regularArr); * print(regularArr); * print(newArr); * } *
*/ p5.prototype.shuffle = function(arr, bool) { var isView = ArrayBuffer && ArrayBuffer.isView && ArrayBuffer.isView(arr); arr = bool || isView ? arr : arr.slice(); var rnd, tmp, idx = arr.length; while (idx > 1) { rnd = (Math.random() * idx) | 0; tmp = arr[--idx]; arr[idx] = arr[rnd]; arr[rnd] = tmp; } return arr; }; /** * Sorts an array of numbers from smallest to largest, or puts an array of * words in alphabetical order. The original array is not modified; a * re-ordered array is returned. The count parameter states the number of * elements to sort. For example, if there are 12 elements in an array and * count is set to 5, only the first 5 elements in the array will be sorted. * * @method sort * @deprecated Use array.sort() instead. * @param {Array} list Array to sort * @param {Integer} [count] number of elements to sort, starting from 0 * * @example *
* function setup() { * var words = ['banana', 'apple', 'pear', 'lime']; * print(words); // ['banana', 'apple', 'pear', 'lime'] * var count = 4; // length of array * * words = sort(words, count); * print(words); // ['apple', 'banana', 'lime', 'pear'] * } *
*
* function setup() { * var numbers = [2, 6, 1, 5, 14, 9, 8, 12]; * print(numbers); // [2, 6, 1, 5, 14, 9, 8, 12] * var count = 5; // Less than the length of the array * * numbers = sort(numbers, count); * print(numbers); // [1,2,5,6,14,9,8,12] * } *
*/ p5.prototype.sort = function(list, count) { var arr = count ? list.slice(0, Math.min(count, list.length)) : list; var rest = count ? list.slice(Math.min(count, list.length)) : []; if (typeof arr[0] === 'string') { arr = arr.sort(); } else { arr = arr.sort(function(a, b) { return a - b; }); } return arr.concat(rest); }; /** * Inserts a value or an array of values into an existing array. The first * parameter specifies the initial array to be modified, and the second * parameter defines the data to be inserted. The third parameter is an index * value which specifies the array position from which to insert data. * (Remember that array index numbering starts at zero, so the first position * is 0, the second position is 1, and so on.) * * @method splice * @deprecated Use array.splice() instead. * @param {Array} list Array to splice into * @param {any} value value to be spliced in * @param {Integer} position in the array from which to insert data * * @example *
* function setup() { * var myArray = [0, 1, 2, 3, 4]; * var insArray = ['A', 'B', 'C']; * print(myArray); // [0, 1, 2, 3, 4] * print(insArray); // ['A','B','C'] * * splice(myArray, insArray, 3); * print(myArray); // [0,1,2,'A','B','C',3,4] * } *
*/ p5.prototype.splice = function(list, value, index) { // note that splice returns spliced elements and not an array Array.prototype.splice.apply(list, [index, 0].concat(value)); return list; }; /** * Extracts an array of elements from an existing array. The list parameter * defines the array from which the elements will be copied, and the start * and count parameters specify which elements to extract. If no count is * given, elements will be extracted from the start to the end of the array. * When specifying the start, remember that the first array element is 0. * This function does not change the source array. * * @method subset * @deprecated Use array.slice() instead. * @param {Array} list Array to extract from * @param {Integer} start position to begin * @param {Integer} [count] number of values to extract * @return {Array} Array of extracted elements * * @example *
* function setup() { * var myArray = [1, 2, 3, 4, 5]; * print(myArray); // [1, 2, 3, 4, 5] * * var sub1 = subset(myArray, 0, 3); * var sub2 = subset(myArray, 2, 2); * print(sub1); // [1,2,3] * print(sub2); // [3,4] * } *
*/ p5.prototype.subset = function(list, start, count) { if (typeof count !== 'undefined') { return list.slice(start, start + count); } else { return list.slice(start, list.length); } }; module.exports = p5; },{"../core/core":22}],60:[function(_dereq_,module,exports){ /** * @module Data * @submodule Conversion * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Converts a string to its floating point representation. The contents of a * string must resemble a number, or NaN (not a number) will be returned. * For example, float("1234.56") evaluates to 1234.56, but float("giraffe") * will return NaN. * * When an array of values is passed in, then an array of floats of the same * length is returned. * * @method float * @param {String} str float string to parse * @return {Number} floating point representation of string * @example *
* var str = '20'; * var diameter = float(str); * ellipse(width / 2, height / 2, diameter, diameter); *
* * @alt * 20 by 20 white ellipse in the center of the canvas * */ p5.prototype.float = function(str) { if (str instanceof Array) { return str.map(parseFloat); } return parseFloat(str); }; /** * Converts a boolean, string, or float to its integer representation. * When an array of values is passed in, then an int array of the same length * is returned. * * @method int * @param {String|Boolean|Number} n value to parse * @param {Integer} [radix] the radix to convert to (default: 10) * @return {Number} integer representation of value * * @example *
* print(int('10')); // 10 * print(int(10.31)); // 10 * print(int(-10)); // -10 * print(int(true)); // 1 * print(int(false)); // 0 * print(int([false, true, '10.3', 9.8])); // [0, 1, 10, 9] *
*/ /** * @method int * @param {Array} ns values to parse * @return {Number[]} integer representation of values */ p5.prototype.int = function(n, radix) { radix = radix || 10; if (typeof n === 'string') { return parseInt(n, radix); } else if (typeof n === 'number') { return n | 0; } else if (typeof n === 'boolean') { return n ? 1 : 0; } else if (n instanceof Array) { return n.map(function(n) { return p5.prototype.int(n, radix); }); } }; /** * Converts a boolean, string or number to its string representation. * When an array of values is passed in, then an array of strings of the same * length is returned. * * @method str * @param {String|Boolean|Number|Array} n value to parse * @return {String} string representation of value * @example *
* print(str('10')); // "10" * print(str(10.31)); // "10.31" * print(str(-10)); // "-10" * print(str(true)); // "true" * print(str(false)); // "false" * print(str([true, '10.3', 9.8])); // [ "true", "10.3", "9.8" ] *
*/ p5.prototype.str = function(n) { if (n instanceof Array) { return n.map(p5.prototype.str); } else { return String(n); } }; /** * Converts a number or string to its boolean representation. * For a number, any non-zero value (positive or negative) evaluates to true, * while zero evaluates to false. For a string, the value "true" evaluates to * true, while any other value evaluates to false. When an array of number or * string values is passed in, then a array of booleans of the same length is * returned. * * @method boolean * @param {String|Boolean|Number|Array} n value to parse * @return {Boolean} boolean representation of value * @example *
* print(boolean(0)); // false * print(boolean(1)); // true * print(boolean('true')); // true * print(boolean('abcd')); // false * print(boolean([0, 12, 'true'])); // [false, true, false] *
*/ p5.prototype.boolean = function(n) { if (typeof n === 'number') { return n !== 0; } else if (typeof n === 'string') { return n.toLowerCase() === 'true'; } else if (typeof n === 'boolean') { return n; } else if (n instanceof Array) { return n.map(p5.prototype.boolean); } }; /** * Converts a number, string representation of a number, or boolean to its byte * representation. A byte can be only a whole number between -128 and 127, so * when a value outside of this range is converted, it wraps around to the * corresponding byte representation. When an array of number, string or boolean * values is passed in, then an array of bytes the same length is returned. * * @method byte * @param {String|Boolean|Number} n value to parse * @return {Number} byte representation of value * * @example *
* print(byte(127)); // 127 * print(byte(128)); // -128 * print(byte(23.4)); // 23 * print(byte('23.4')); // 23 * print(byte('hello')); // NaN * print(byte(true)); // 1 * print(byte([0, 255, '100'])); // [0, -1, 100] *
*/ /** * @method byte * @param {Array} ns values to parse * @return {Number[]} array of byte representation of values */ p5.prototype.byte = function(n) { var nn = p5.prototype.int(n, 10); if (typeof nn === 'number') { return (nn + 128) % 256 - 128; } else if (nn instanceof Array) { return nn.map(p5.prototype.byte); } }; /** * Converts a number or string to its corresponding single-character * string representation. If a string parameter is provided, it is first * parsed as an integer and then translated into a single-character string. * When an array of number or string values is passed in, then an array of * single-character strings of the same length is returned. * * @method char * @param {String|Number} n value to parse * @return {String} string representation of value * * @example *
* print(char(65)); // "A" * print(char('65')); // "A" * print(char([65, 66, 67])); // [ "A", "B", "C" ] * print(join(char([65, 66, 67]), '')); // "ABC" *
*/ /** * @method char * @param {Array} ns values to parse * @return {String[]} array of string representation of values */ p5.prototype.char = function(n) { if (typeof n === 'number' && !isNaN(n)) { return String.fromCharCode(n); } else if (n instanceof Array) { return n.map(p5.prototype.char); } else if (typeof n === 'string') { return p5.prototype.char(parseInt(n, 10)); } }; /** * Converts a single-character string to its corresponding integer * representation. When an array of single-character string values is passed * in, then an array of integers of the same length is returned. * * @method unchar * @param {String} n value to parse * @return {Number} integer representation of value * * @example *
* print(unchar('A')); // 65 * print(unchar(['A', 'B', 'C'])); // [ 65, 66, 67 ] * print(unchar(split('ABC', ''))); // [ 65, 66, 67 ] *
*/ /** * @method unchar * @param {Array} ns values to parse * @return {Number[]} integer representation of values */ p5.prototype.unchar = function(n) { if (typeof n === 'string' && n.length === 1) { return n.charCodeAt(0); } else if (n instanceof Array) { return n.map(p5.prototype.unchar); } }; /** * Converts a number to a string in its equivalent hexadecimal notation. If a * second parameter is passed, it is used to set the number of characters to * generate in the hexadecimal notation. When an array is passed in, an * array of strings in hexadecimal notation of the same length is returned. * * @method hex * @param {Number} n value to parse * @param {Number} [digits] * @return {String} hexadecimal string representation of value * * @example *
* print(hex(255)); // "000000FF" * print(hex(255, 6)); // "0000FF" * print(hex([0, 127, 255], 6)); // [ "000000", "00007F", "0000FF" ] *
*/ /** * @method hex * @param {Number[]} ns array of values to parse * @param {Number} [digits] * @return {String[]} hexadecimal string representation of values */ p5.prototype.hex = function(n, digits) { digits = digits === undefined || digits === null ? (digits = 8) : digits; if (n instanceof Array) { return n.map(function(n) { return p5.prototype.hex(n, digits); }); } else if (typeof n === 'number') { if (n < 0) { n = 0xffffffff + n + 1; } var hex = Number(n) .toString(16) .toUpperCase(); while (hex.length < digits) { hex = '0' + hex; } if (hex.length >= digits) { hex = hex.substring(hex.length - digits, hex.length); } return hex; } }; /** * Converts a string representation of a hexadecimal number to its equivalent * integer value. When an array of strings in hexadecimal notation is passed * in, an array of integers of the same length is returned. * * @method unhex * @param {String} n value to parse * @return {Number} integer representation of hexadecimal value * * @example *
* print(unhex('A')); // 10 * print(unhex('FF')); // 255 * print(unhex(['FF', 'AA', '00'])); // [ 255, 170, 0 ] *
*/ /** * @method unhex * @param {Array} ns values to parse * @return {Number[]} integer representations of hexadecimal value */ p5.prototype.unhex = function(n) { if (n instanceof Array) { return n.map(p5.prototype.unhex); } else { return parseInt('0x' + n, 16); } }; module.exports = p5; },{"../core/core":22}],61:[function(_dereq_,module,exports){ /** * @module Data * @submodule String Functions * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); _dereq_('../core/error_helpers'); //return p5; //LM is this a mistake? /** * Combines an array of Strings into one String, each separated by the * character(s) used for the separator parameter. To join arrays of ints or * floats, it's necessary to first convert them to Strings using nf() or * nfs(). * * @method join * @param {Array} list array of Strings to be joined * @param {String} separator String to be placed between each item * @return {String} joined String * @example *
* * var array = ['Hello', 'world!']; * var separator = ' '; * var message = join(array, separator); * text(message, 5, 50); * *
* * @alt * "hello world!" displayed middle left of canvas. * */ p5.prototype.join = function(list, separator) { p5._validateParameters('join', arguments); return list.join(separator); }; /** * This function is used to apply a regular expression to a piece of text, * and return matching groups (elements found inside parentheses) as a * String array. If there are no matches, a null value will be returned. * If no groups are specified in the regular expression, but the sequence * matches, an array of length 1 (with the matched text as the first element * of the array) will be returned. *

* To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, an array is returned. *

* If there are groups (specified by sets of parentheses) in the regular * expression, then the contents of each will be returned in the array. * Element [0] of a regular expression match returns the entire matching * string, and the match groups start at element [1] (the first group is [1], * the second [2], and so on). * * @method match * @param {String} str the String to be searched * @param {String} regexp the regexp to be used for matching * @return {String[]} Array of Strings found * @example *
* * var string = 'Hello p5js*!'; * var regexp = 'p5js\\*'; * var m = match(string, regexp); * text(m, 5, 50); * *
* * @alt * "p5js*" displayed middle left of canvas. * */ p5.prototype.match = function(str, reg) { p5._validateParameters('match', arguments); return str.match(reg); }; /** * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. If there are no matches, a null value * will be returned. If no groups are specified in the regular expression, * but the sequence matches, a two dimensional array is still returned, but * the second dimension is only of length one. *

* To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. *

* If there are groups (specified by sets of parentheses) in the regular * expression, then the contents of each will be returned in the array. * Assuming a loop with counter variable i, element [i][0] of a regular * expression match returns the entire matching string, and the match groups * start at element [i][1] (the first group is [i][1], the second [i][2], * and so on). * * @method matchAll * @param {String} str the String to be searched * @param {String} regexp the regexp to be used for matching * @return {String[]} 2d Array of Strings found * @example *
* * var string = 'Hello p5js*! Hello world!'; * var regexp = 'Hello'; * matchAll(string, regexp); * *
*/ p5.prototype.matchAll = function(str, reg) { p5._validateParameters('matchAll', arguments); var re = new RegExp(reg, 'g'); var match = re.exec(str); var matches = []; while (match !== null) { matches.push(match); // matched text: match[0] // match start: match.index // capturing group n: match[n] match = re.exec(str); } return matches; }; /** * Utility function for formatting numbers into strings. There are two * versions: one for formatting floats, and one for formatting ints. * The values for the digits, left, and right parameters should always * be positive integers. * * @method nf * @param {Number|String} num the Number to format * @param {Integer|String} [left] number of digits to the left of the * decimal point * @param {Integer|String} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example *
* * function setup() { * background(200); * var num = 112.53106115; * * noStroke(); * fill(0); * textSize(14); * // Draw formatted numbers * text(nf(num, 5, 2), 10, 20); * * text(nf(num, 4, 3), 10, 55); * * text(nf(num, 3, 6), 10, 85); * * // Draw dividing lines * stroke(120); * line(0, 30, width, 30); * line(0, 65, width, 65); * } * *
* * @alt * "0011253" top left, "0112.531" mid left, "112.531061" bottom left canvas */ /** * @method nf * @param {Array} nums the Numbers to format * @param {Integer|String} [left] * @param {Integer|String} [right] * @return {String[]} formatted Strings */ p5.prototype.nf = function(nums, left, right) { p5._validateParameters('nf', arguments); if (nums instanceof Array) { return nums.map(function(x) { return doNf(x, left, right); }); } else { var typeOfFirst = Object.prototype.toString.call(nums); if (typeOfFirst === '[object Arguments]') { if (nums.length === 3) { return this.nf(nums[0], nums[1], nums[2]); } else if (nums.length === 2) { return this.nf(nums[0], nums[1]); } else { return this.nf(nums[0]); } } else { return doNf(nums, left, right); } } }; function doNf(num, left, right) { var neg = num < 0; var n = neg ? num.toString().substring(1) : num.toString(); var decimalInd = n.indexOf('.'); var intPart = decimalInd !== -1 ? n.substring(0, decimalInd) : n; var decPart = decimalInd !== -1 ? n.substring(decimalInd + 1) : ''; var str = neg ? '-' : ''; if (typeof right !== 'undefined') { var decimal = ''; if (decimalInd !== -1 || right - decPart.length > 0) { decimal = '.'; } if (decPart.length > right) { decPart = decPart.substring(0, right); } for (var i = 0; i < left - intPart.length; i++) { str += '0'; } str += intPart; str += decimal; str += decPart; for (var j = 0; j < right - decPart.length; j++) { str += '0'; } return str; } else { for (var k = 0; k < Math.max(left - intPart.length, 0); k++) { str += '0'; } str += n; return str; } } /** * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions: one * for formatting ints, and one for formatting an array of ints. The value * for the right parameter should always be a positive integer. * * @method nfc * @param {Number|String} num the Number to format * @param {Integer|String} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example *
* * function setup() { * background(200); * var num = 11253106.115; * var numArr = [1, 1, 2]; * * noStroke(); * fill(0); * textSize(12); * * // Draw formatted numbers * text(nfc(num, 4), 10, 30); * text(nfc(numArr, 2), 10, 80); * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); * } * *
* * @alt * "11,253,106.115" top middle and "1.00,1.00,2.00" displayed bottom mid */ /** * @method nfc * @param {Array} nums the Numbers to format * @param {Integer|String} [right] * @return {String[]} formatted Strings */ p5.prototype.nfc = function(num, right) { p5._validateParameters('nfc', arguments); if (num instanceof Array) { return num.map(function(x) { return doNfc(x, right); }); } else { return doNfc(num, right); } }; function doNfc(num, right) { num = num.toString(); var dec = num.indexOf('.'); var rem = dec !== -1 ? num.substring(dec) : ''; var n = dec !== -1 ? num.substring(0, dec) : num; n = n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); if (right === 0) { rem = ''; } else if (typeof right !== 'undefined') { if (right > rem.length) { rem += dec === -1 ? '.' : ''; var len = right - rem.length + 1; for (var i = 0; i < len; i++) { rem += '0'; } } else { rem = rem.substring(0, right + 1); } } return n + rem; } /** * Utility function for formatting numbers into strings. Similar to nf() but * puts a "+" in front of positive numbers and a "-" in front of negative * numbers. There are two versions: one for formatting floats, and one for * formatting ints. The values for left, and right parameters * should always be positive integers. * * @method nfp * @param {Number} num the Number to format * @param {Integer} [left] number of digits to the left of the decimal * point * @param {Integer} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example *
* * function setup() { * background(200); * var num1 = 11253106.115; * var num2 = -11253106.115; * * noStroke(); * fill(0); * textSize(12); * * // Draw formatted numbers * text(nfp(num1, 4, 2), 10, 30); * text(nfp(num2, 4, 2), 10, 80); * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); * } * *
* * @alt * "+11253106.11" top middle and "-11253106.11" displayed bottom middle */ /** * @method nfp * @param {Number[]} nums the Numbers to format * @param {Integer} [left] * @param {Integer} [right] * @return {String[]} formatted Strings */ p5.prototype.nfp = function() { p5._validateParameters('nfp', arguments); var nfRes = p5.prototype.nf.apply(this, arguments); if (nfRes instanceof Array) { return nfRes.map(addNfp); } else { return addNfp(nfRes); } }; function addNfp(num) { return parseFloat(num) > 0 ? '+' + num.toString() : num.toString(); } /** * Utility function for formatting numbers into strings. Similar to nf() but * puts a " " (space) in front of positive numbers and a "-" in front of * negative numbers. There are two versions: one for formatting floats, and * one for formatting ints. The values for the digits, left, and right * parameters should always be positive integers. * * @method nfs * @param {Number} num the Number to format * @param {Integer} [left] number of digits to the left of the decimal * point * @param {Integer} [right] number of digits to the right of the * decimal point * @return {String} formatted String * * @example *
* * function setup() { * background(200); * var num1 = 11253106.115; * var num2 = -11253106.115; * * noStroke(); * fill(0); * textSize(12); * // Draw formatted numbers * text(nfs(num1, 4, 2), 10, 30); * * text(nfs(num2, 4, 2), 10, 80); * * // Draw dividing line * stroke(120); * line(0, 50, width, 50); * } * *
* * @alt * "11253106.11" top middle and "-11253106.11" displayed bottom middle */ /** * @method nfs * @param {Array} nums the Numbers to format * @param {Integer} [left] * @param {Integer} [right] * @return {String[]} formatted Strings */ p5.prototype.nfs = function() { p5._validateParameters('nfs', arguments); var nfRes = p5.prototype.nf.apply(this, arguments); if (nfRes instanceof Array) { return nfRes.map(addNfs); } else { return addNfs(nfRes); } }; function addNfs(num) { return parseFloat(num) > 0 ? ' ' + num.toString() : num.toString(); } /** * The split() function maps to String.split(), it breaks a String into * pieces using a character or string as the delimiter. The delim parameter * specifies the character or characters that mark the boundaries between * each piece. A String[] array is returned that contains each of the pieces. * * The splitTokens() function works in a similar fashion, except that it * splits using a range of characters instead of a specific character or * sequence. * * @method split * @param {String} value the String to be split * @param {String} delim the String used to separate the data * @return {String[]} Array of Strings * @example *
* * var names = 'Pat,Xio,Alex'; * var splitString = split(names, ','); * text(splitString[0], 5, 30); * text(splitString[1], 5, 50); * text(splitString[2], 5, 70); * *
* * @alt * "pat" top left, "Xio" mid left and "Alex" displayed bottom left * */ p5.prototype.split = function(str, delim) { p5._validateParameters('split', arguments); return str.split(delim); }; /** * The splitTokens() function splits a String at one or many character * delimiters or "tokens." The delim parameter specifies the character or * characters to be used as a boundary. *

* If no delim characters are specified, any whitespace character is used to * split. Whitespace characters include tab (\t), line feed (\n), carriage * return (\r), form feed (\f), and space. * * @method splitTokens * @param {String} value the String to be split * @param {String} [delim] list of individual Strings that will be used as * separators * @return {String[]} Array of Strings * @example *
* * function setup() { * var myStr = 'Mango, Banana, Lime'; * var myStrArr = splitTokens(myStr, ','); * * print(myStrArr); // prints : ["Mango"," Banana"," Lime"] * } * *
*/ p5.prototype.splitTokens = function(value, delims) { p5._validateParameters('splitTokens', arguments); var d; if (typeof delims !== 'undefined') { var str = delims; var sqc = /\]/g.exec(str); var sqo = /\[/g.exec(str); if (sqo && sqc) { str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); sqo = /\[/g.exec(str); str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); d = new RegExp('[\\[' + str + '\\]]', 'g'); } else if (sqc) { str = str.slice(0, sqc.index) + str.slice(sqc.index + 1); d = new RegExp('[' + str + '\\]]', 'g'); } else if (sqo) { str = str.slice(0, sqo.index) + str.slice(sqo.index + 1); d = new RegExp('[' + str + '\\[]', 'g'); } else { d = new RegExp('[' + str + ']', 'g'); } } else { d = /\s/g; } return value.split(d).filter(function(n) { return n; }); }; /** * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage return, * and tab, this function also removes the Unicode "nbsp" character. * * @method trim * @param {String} str a String to be trimmed * @return {String} a trimmed String * * @example *
* * var string = trim(' No new lines\n '); * text(string + ' here', 2, 50); * *
* * @alt * "No new lines here" displayed center canvas */ /** * @method trim * @param {Array} strs an Array of Strings to be trimmed * @return {String[]} an Array of trimmed Strings */ p5.prototype.trim = function(str) { p5._validateParameters('trim', arguments); if (str instanceof Array) { return str.map(this.trim); } else { return str.trim(); } }; module.exports = p5; },{"../core/core":22,"../core/error_helpers":25}],62:[function(_dereq_,module,exports){ /** * @module IO * @submodule Time & Date * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * p5.js communicates with the clock on your computer. The day() function * returns the current day as a value from 1 - 31. * * @method day * @return {Integer} the current day * @example *
* * var d = day(); * text('Current day: \n' + d, 5, 50); * *
* * @alt * Current day is displayed * */ p5.prototype.day = function() { return new Date().getDate(); }; /** * p5.js communicates with the clock on your computer. The hour() function * returns the current hour as a value from 0 - 23. * * @method hour * @return {Integer} the current hour * @example *
* * var h = hour(); * text('Current hour:\n' + h, 5, 50); * *
* * @alt * Current hour is displayed * */ p5.prototype.hour = function() { return new Date().getHours(); }; /** * p5.js communicates with the clock on your computer. The minute() function * returns the current minute as a value from 0 - 59. * * @method minute * @return {Integer} the current minute * @example *
* * var m = minute(); * text('Current minute: \n' + m, 5, 50); * *
* * @alt * Current minute is displayed * */ p5.prototype.minute = function() { return new Date().getMinutes(); }; /** * Returns the number of milliseconds (thousandths of a second) since * starting the program. This information is often used for timing events and * animation sequences. * * @method millis * @return {Number} the number of milliseconds since starting the program * @example *
* * var millisecond = millis(); * text('Milliseconds \nrunning: \n' + millisecond, 5, 40); * *
* * @alt * number of milliseconds since program has started displayed * */ p5.prototype.millis = function() { return window.performance.now(); }; /** * p5.js communicates with the clock on your computer. The month() function * returns the current month as a value from 1 - 12. * * @method month * @return {Integer} the current month * @example *
* * var m = month(); * text('Current month: \n' + m, 5, 50); * *
* * @alt * Current month is displayed * */ p5.prototype.month = function() { return new Date().getMonth() + 1; //January is 0! }; /** * p5.js communicates with the clock on your computer. The second() function * returns the current second as a value from 0 - 59. * * @method second * @return {Integer} the current second * @example *
* * var s = second(); * text('Current second: \n' + s, 5, 50); * *
* * @alt * Current second is displayed * */ p5.prototype.second = function() { return new Date().getSeconds(); }; /** * p5.js communicates with the clock on your computer. The year() function * returns the current year as an integer (2014, 2015, 2016, etc). * * @method year * @return {Integer} the current year * @example *
* * var y = year(); * text('Current year: \n' + y, 5, 50); * *
* * @alt * Current year is displayed * */ p5.prototype.year = function() { return new Date().getFullYear(); }; module.exports = p5; },{"../core/core":22}],63:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Camera * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Sets camera position for a 3D sketch. The function behaves similarly * gluLookAt, except that it replaces the existing modelview matrix instead * of applying any transformations calculated here on top of the existing * model view. * When called with no arguments, this function * sets a default camera equivalent to calling * camera(0, 0, (height/2.0) / tan(PI*30.0 / 180.0), 0, 0, 0, 0, 1, 0); * @method camera * @param {Number} [x] camera position value on x axis * @param {Number} [y] camera position value on y axis * @param {Number} [z] camera position value on z axis * @param {Number} [centerX] x coordinate representing center of the sketch * @param {Number} [centerY] y coordinate representing center of the sketch * @param {Number} [centerZ] z coordinate representing center of the sketch * @param {Number} [upX] x component of direction 'up' from camera * @param {Number} [upY] y component of direction 'up' from camera * @param {Number} [upZ] z component of direction 'up' from camera * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * //move the camera away from the plane by a sin wave * camera(0, 0, sin(frameCount * 0.01) * 100, 0, 0, 0, 0, 1, 0); * plane(120, 120); * } * *
* * @alt * blue square shrinks in size grows to fill canvas. disappears then loops. * */ p5.prototype.camera = function() { this._assert3d('camera'); p5._validateParameters('camera', arguments); this._renderer.camera.apply(this._renderer, arguments); return this; }; p5.RendererGL.prototype.camera = function( eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ ) { if (typeof eyeX === 'undefined') { eyeX = this.defaultCameraX; eyeY = this.defaultCameraY; eyeZ = this.defaultCameraZ; centerX = eyeX; centerY = eyeY; centerZ = 0; upX = 0; upY = 1; upZ = 0; } this.cameraX = eyeX; this.cameraY = eyeY; this.cameraZ = eyeZ; // calculate camera Z vector var z0 = eyeX - centerX; var z1 = eyeY - centerY; var z2 = eyeZ - centerZ; this.eyeDist = Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); if (this.eyeDist !== 0) { z0 /= this.eyeDist; z1 /= this.eyeDist; z2 /= this.eyeDist; } // calculate camera Y vector var y0 = upX; var y1 = upY; var y2 = upZ; // computer x vector as y cross z var x0 = y1 * z2 - y2 * z1; var x1 = -y0 * z2 + y2 * z0; var x2 = y0 * z1 - y1 * z0; // recomputer y = z cross x y0 = z1 * x2 - z2 * x1; y1 = -z0 * x2 + z2 * x0; y2 = z0 * x1 - z1 * x0; // cross product gives area of parallelogram, which is < 1.0 for // non-perpendicular unit-length vectors; so normalize x, y here: var xmag = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); if (xmag !== 0) { x0 /= xmag; x1 /= xmag; x2 /= xmag; } var ymag = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); if (ymag !== 0) { y0 /= ymag; y1 /= ymag; y2 /= ymag; } // the camera affects the model view matrix, insofar as it // inverse translates the world to the eye position of the camera // and rotates it. // prettier-ignore this.cameraMatrix.set(x0, y0, z0, 0, x1, y1, z1, 0, x2, y2, z2, 0, 0, 0, 0, 1); var tx = -eyeX; var ty = -eyeY; var tz = -eyeZ; this.cameraMatrix.translate([tx, ty, tz]); this.uMVMatrix.set( this.cameraMatrix.mat4[0], this.cameraMatrix.mat4[1], this.cameraMatrix.mat4[2], this.cameraMatrix.mat4[3], this.cameraMatrix.mat4[4], this.cameraMatrix.mat4[5], this.cameraMatrix.mat4[6], this.cameraMatrix.mat4[7], this.cameraMatrix.mat4[8], this.cameraMatrix.mat4[9], this.cameraMatrix.mat4[10], this.cameraMatrix.mat4[11], this.cameraMatrix.mat4[12], this.cameraMatrix.mat4[13], this.cameraMatrix.mat4[14], this.cameraMatrix.mat4[15] ); return this; }; /** * Sets perspective camera. When called with no arguments, the defaults * provided are equivalent to * perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0) * where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * @method perspective * @param {Number} [fovy] camera frustum vertical field of view, * from bottom to top of view, in angleMode units * @param {Number} [aspect] camera frustum aspect ratio * @param {Number} [near] frustum near plane length * @param {Number} [far] frustum far plane length * @chainable * @example *
* * //drag mouse to toggle the world! * //you will see there's a vanish point * function setup() { * createCanvas(100, 100, WEBGL); * var fov = 60 / 180 * PI; * var cameraZ = height / 2.0 / tan(fov / 2.0); * perspective(60 / 180 * PI, width / height, cameraZ * 0.1, cameraZ * 10); * } * function draw() { * background(200); * orbitControl(); * for (var i = -1; i < 2; i++) { * for (var j = -2; j < 3; j++) { * push(); * translate(i * 160, 0, j * 160); * box(40, 40, 40); * pop(); * } * } * } * *
* * @alt * colored 3d boxes toggleable with mouse position * */ p5.prototype.perspective = function() { this._assert3d('perspective'); p5._validateParameters('perspective', arguments); this._renderer.perspective.apply(this._renderer, arguments); return this; }; p5.RendererGL.prototype.perspective = function(fovy, aspect, near, far) { if (typeof fovy === 'undefined') { fovy = this.defaultCameraFOV; } if (typeof aspect === 'undefined') { aspect = this.defaultCameraAspect; } if (typeof near === 'undefined') { near = this.defaultCameraNear; } if (typeof far === 'undefined') { far = this.defaultCameraFar; } this.cameraFOV = this._pInst._toRadians(fovy); this.cameraAspect = aspect; this.cameraNear = near; this.cameraFar = far; this.uPMatrix = p5.Matrix.identity(); var f = 1.0 / Math.tan(this.cameraFOV / 2); var nf = 1.0 / (this.cameraNear - this.cameraFar); // prettier-ignore this.uPMatrix.set(f / aspect, 0, 0, 0, 0, -f, 0, 0, 0, 0, (far + near) * nf, -1, 0, 0, (2 * far * near) * nf, 0); this._curCamera = 'custom'; }; /** * Setup ortho camera * @method ortho * @param {Number} [left] camera frustum left plane * @param {Number} [right] camera frustum right plane * @param {Number} [bottom] camera frustum bottom plane * @param {Number} [top] camera frustum top plane * @param {Number} [near] camera frustum near plane * @param {Number} [far] camera frustum far plane * @chainable * @example *
* * //drag mouse to toggle the world! * //there's no vanish point * function setup() { * createCanvas(100, 100, WEBGL); * ortho(-width / 2, width / 2, height / 2, -height / 2, 0, 500); * } * function draw() { * background(200); * orbitControl(); * strokeWeight(0.1); * for (var i = -1; i < 2; i++) { * for (var j = -2; j < 3; j++) { * push(); * translate(i * 160, 0, j * 160); * box(40, 40, 40); * pop(); * } * } * } * *
* * @alt * 3 3d boxes, reveal several more boxes on 3d plane when mouse used to toggle * */ p5.prototype.ortho = function() { this._assert3d('ortho'); p5._validateParameters('ortho', arguments); this._renderer.ortho.apply(this._renderer, arguments); return this; }; p5.RendererGL.prototype.ortho = function(left, right, bottom, top, near, far) { if (left === undefined) left = -this.width / 2; if (right === undefined) right = +this.width / 2; if (bottom === undefined) bottom = -this.height / 2; if (top === undefined) top = +this.height / 2; if (near === undefined) near = 0; if (far === undefined) far = Math.max(this.width, this.height); var w = right - left; var h = top - bottom; var d = far - near; var x = +2.0 / w; var y = +2.0 / h; var z = -2.0 / d; var tx = -(right + left) / w; var ty = -(top + bottom) / h; var tz = -(far + near) / d; this.uPMatrix = p5.Matrix.identity(); // prettier-ignore this.uPMatrix.set( x, 0, 0, 0, 0, -y, 0, 0, 0, 0, z, 0, tx, ty, tz, 1); this._curCamera = 'custom'; }; module.exports = p5; },{"../core/core":22}],64:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/core'); /** * @method orbitControl * @for p5 * @chainable * * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(50); * // Orbit control allows the camera to orbit around a target. * orbitControl(); * box(30, 50); * } * *
* * @alt * Camera orbits around box when mouse is hold-clicked & then moved. */ //@TODO: implement full orbit controls including //pan, zoom, quaternion rotation, etc. p5.prototype.orbitControl = function() { this._assert3d('orbitControl'); p5._validateParameters('orbitControl', arguments); if (this.mouseIsPressed) { this.rotateY((this.mouseX - this.width / 2) / (this.width / 2)); this.rotateX((this.mouseY - this.height / 2) / (this.width / 2)); } return this; }; module.exports = p5; },{"../core/core":22}],65:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Lights * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Creates an ambient light with a color * * @method ambientLight * @param {Number} v1 red or hue value relative to * the current color range * @param {Number} v2 green or saturation value * relative to the current color range * @param {Number} v3 blue or brightness value * relative to the current color range * @param {Number} [alpha] * @chainable * * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * ambientLight(150); * ambientMaterial(250); * noStroke(); * sphere(25); * } * *
* * @alt * evenly distributed light across a sphere * */ /** * @method ambientLight * @param {String} value a color string * @chainable */ /** * @method ambientLight * @param {Number} gray a gray value * @param {Number} [alpha] * @chainable */ /** * @method ambientLight * @param {Number[]} values an array containing the red,green,blue & * and alpha components of the color * @chainable */ /** * @method ambientLight * @param {p5.Color} color the ambient light color * @chainable */ p5.prototype.ambientLight = function(v1, v2, v3, a) { this._assert3d('ambientLight'); p5._validateParameters('ambientLight', arguments); var color = this.color.apply(this, arguments); var shader = this._renderer._useLightShader(); //@todo this is a bit icky. array uniforms have //to be multiples of the type 3(rgb) in this case. //a preallocated Float32Array(24) that we copy into //would be better shader.setUniform('uUseLighting', true); //in case there's no material color for the geometry shader.setUniform('uMaterialColor', this._renderer.curFillColor); this._renderer.ambientLightColors.push( color._array[0], color._array[1], color._array[2] ); shader.setUniform('uAmbientColor', this._renderer.ambientLightColors); shader.setUniform( 'uAmbientLightCount', this._renderer.ambientLightColors.length / 3 ); return this; }; /** * Creates a directional light with a color and a direction * @method directionalLight * @param {Number} v1 red or hue value (depending on the current * color mode), * @param {Number} v2 green or saturation value * @param {Number} v3 blue or brightness value * @param {p5.Vector} position the direction of the light * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * //move your mouse to change light direction * var dirX = (mouseX / width - 0.5) * 2; * var dirY = (mouseY / height - 0.5) * 2; * directionalLight(250, 250, 250, -dirX, -dirY, 0.25); * ambientMaterial(250); * noStroke(); * sphere(25); * } * *
* * @alt * light source on canvas changeable with mouse position * */ /** * @method directionalLight * @param {Number[]|String|p5.Color} color color Array, CSS color string, * or p5.Color value * @param {Number} x x axis direction * @param {Number} y y axis direction * @param {Number} z z axis direction * @chainable */ /** * @method directionalLight * @param {Number[]|String|p5.Color} color * @param {p5.Vector} position * @chainable */ /** * @method directionalLight * @param {Number} v1 * @param {Number} v2 * @param {Number} v3 * @param {Number} x * @param {Number} y * @param {Number} z * @chainable */ p5.prototype.directionalLight = function(v1, v2, v3, x, y, z) { this._assert3d('directionalLight'); p5._validateParameters('directionalLight', arguments); var shader = this._renderer._useLightShader(); //@TODO: check parameters number var color = this.color.apply(this, [v1, v2, v3]); var _x, _y, _z; var v = arguments[arguments.length - 1]; if (typeof v === 'number') { _x = arguments[arguments.length - 3]; _y = arguments[arguments.length - 2]; _z = arguments[arguments.length - 1]; } else { _x = v.x; _y = v.y; _z = v.z; } shader.setUniform('uUseLighting', true); //in case there's no material color for the geometry shader.setUniform('uMaterialColor', this._renderer.curFillColor); // normalize direction var l = Math.sqrt(_x * _x + _y * _y + _z * _z); this._renderer.directionalLightDirections.push(_x / l, _y / l, _z / l); shader.setUniform( 'uLightingDirection', this._renderer.directionalLightDirections ); this._renderer.directionalLightColors.push( color._array[0], color._array[1], color._array[2] ); shader.setUniform('uDirectionalColor', this._renderer.directionalLightColors); shader.setUniform( 'uDirectionalLightCount', this._renderer.directionalLightColors.length / 3 ); return this; }; /** * Creates a point light with a color and a light position * @method pointLight * @param {Number} v1 red or hue value (depending on the current * color mode), * @param {Number} v2 green or saturation value * @param {Number} v3 blue or brightness value * @param {Number} x x axis position * @param {Number} y y axis position * @param {Number} z z axis position * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * //move your mouse to change light position * var locX = mouseX - width / 2; * var locY = mouseY - height / 2; * // to set the light position, * // think of the world's coordinate as: * // -width/2,-height/2 -------- width/2,-height/2 * // | | * // | 0,0 | * // | | * // -width/2,height/2--------width/2,height/2 * pointLight(250, 250, 250, locX, locY, 50); * ambientMaterial(250); * noStroke(); * sphere(25); * } * *
* * @alt * spot light on canvas changes position with mouse * */ /** * @method pointLight * @param {Number} v1 * @param {Number} v2 * @param {Number} v3 * @param {p5.Vector} position the position of the light * @chainable */ /** * @method pointLight * @param {Number[]|String|p5.Color} color color Array, CSS color string, * or p5.Color value * @param {Number} x * @param {Number} y * @param {Number} z * @chainable */ /** * @method pointLight * @param {Number[]|String|p5.Color} color * @param {p5.Vector} position * @chainable */ p5.prototype.pointLight = function(v1, v2, v3, x, y, z) { this._assert3d('pointLight'); p5._validateParameters('pointLight', arguments); //@TODO: check parameters number var color = this._renderer._pInst.color.apply(this, [v1, v2, v3]); var _x, _y, _z; var v = arguments[arguments.length - 1]; if (typeof v === 'number') { _x = arguments[arguments.length - 3]; _y = arguments[arguments.length - 2]; _z = arguments[arguments.length - 1]; } else { _x = v.x; _y = v.y; _z = v.z; } var shader = this._renderer._useLightShader(); shader.setUniform('uUseLighting', true); //in case there's no material color for the geometry shader.setUniform('uMaterialColor', this._renderer.curFillColor); this._renderer.pointLightPositions.push(_x, _y, _z); shader.setUniform('uPointLightLocation', this._renderer.pointLightPositions); this._renderer.pointLightColors.push( color._array[0], color._array[1], color._array[2] ); shader.setUniform('uPointLightColor', this._renderer.pointLightColors); shader.setUniform( 'uPointLightCount', this._renderer.pointLightColors.length / 3 ); return this; }; module.exports = p5; },{"../core/core":22}],66:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 3D Models * @for p5 * @requires core * @requires p5.Geometry */ 'use strict'; var p5 = _dereq_('../core/core'); _dereq_('./p5.Geometry'); /** * Load a 3d model from an OBJ file. *

* One of the limitations of the OBJ format is that it doesn't have a built-in * sense of scale. This means that models exported from different programs might * be very different sizes. If your model isn't displaying, try calling * loadModel() with the normalized parameter set to true. This will resize the * model to a scale appropriate for p5. You can also make additional changes to * the final size of your model with the scale() function. * * @method loadModel * @param {String} path Path of the model to be loaded * @param {Boolean} normalize If true, scale the model to a * standardized size when loading * @param {function(p5.Geometry)} [successCallback] Function to be called * once the model is loaded. Will be passed * the 3D model object. * @param {function(Event)} [failureCallback] called with event error if * the image fails to load. * @return {p5.Geometry} the p5.Geometry object * * @example *
* * //draw a spinning teapot * var teapot; * * function preload() { * teapot = loadModel('assets/teapot.obj'); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * model(teapot); * } * *
* * @alt * Vertically rotating 3-d teapot with red, green and blue gradient. */ /** * @method loadModel * @param {String} path * @param {function(p5.Geometry)} [successCallback] * @param {function(Event)} [failureCallback] * @return {p5.Geometry} the p5.Geometry object */ p5.prototype.loadModel = function(path) { p5._validateParameters('loadModel', arguments); var normalize; var successCallback; var failureCallback; if (typeof arguments[1] === 'boolean') { normalize = arguments[1]; successCallback = arguments[2]; failureCallback = arguments[3]; } else { normalize = false; successCallback = arguments[1]; failureCallback = arguments[2]; } var model = new p5.Geometry(); model.gid = path + '|' + normalize; var self = this; this.loadStrings( path, function(strings) { parseObj(model, strings); if (normalize) { model.normalize(); } self._decrementPreload(); if (typeof successCallback === 'function') { successCallback(model); } }.bind(this), failureCallback ); return model; }; /** * Parse OBJ lines into model. For reference, this is what a simple model of a * square might look like: * * v -0.5 -0.5 0.5 * v -0.5 -0.5 -0.5 * v -0.5 0.5 -0.5 * v -0.5 0.5 0.5 * * f 4 3 2 1 */ function parseObj(model, lines) { // OBJ allows a face to specify an index for a vertex (in the above example), // but it also allows you to specify a custom combination of vertex, UV // coordinate, and vertex normal. So, "3/4/3" would mean, "use vertex 3 with // UV coordinate 4 and vertex normal 3". In WebGL, every vertex with different // parameters must be a different vertex, so loadedVerts is used to // temporarily store the parsed vertices, normals, etc., and indexedVerts is // used to map a specific combination (keyed on, for example, the string // "3/4/3"), to the actual index of the newly created vertex in the final // object. var loadedVerts = { v: [], vt: [], vn: [] }; var indexedVerts = {}; for (var line = 0; line < lines.length; ++line) { // Each line is a separate object (vertex, face, vertex normal, etc) // For each line, split it into tokens on whitespace. The first token // describes the type. var tokens = lines[line].trim().split(/\b\s+/); if (tokens.length > 0) { if (tokens[0] === 'v' || tokens[0] === 'vn') { // Check if this line describes a vertex or vertex normal. // It will have three numeric parameters. var vertex = new p5.Vector( parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3]) ); loadedVerts[tokens[0]].push(vertex); } else if (tokens[0] === 'vt') { // Check if this line describes a texture coordinate. // It will have two numeric parameters. var texVertex = [parseFloat(tokens[1]), parseFloat(tokens[2])]; loadedVerts[tokens[0]].push(texVertex); } else if (tokens[0] === 'f') { // Check if this line describes a face. // OBJ faces can have more than three points. Triangulate points. for (var tri = 3; tri < tokens.length; ++tri) { var face = []; var vertexTokens = [1, tri - 1, tri]; for (var tokenInd = 0; tokenInd < vertexTokens.length; ++tokenInd) { // Now, convert the given token into an index var vertString = tokens[vertexTokens[tokenInd]]; var vertIndex = 0; // TODO: Faces can technically use negative numbers to refer to the // previous nth vertex. I haven't seen this used in practice, but // it might be good to implement this in the future. if (indexedVerts[vertString] !== undefined) { vertIndex = indexedVerts[vertString]; } else { var vertParts = vertString.split('/'); for (var i = 0; i < vertParts.length; i++) { vertParts[i] = parseInt(vertParts[i]) - 1; } vertIndex = indexedVerts[vertString] = model.vertices.length; model.vertices.push(loadedVerts.v[vertParts[0]].copy()); if (loadedVerts.vt[vertParts[1]]) { model.uvs.push(loadedVerts.vt[vertParts[1]].slice()); } else { model.uvs.push([0, 0]); } if (loadedVerts.vn[vertParts[2]]) { model.vertexNormals.push(loadedVerts.vn[vertParts[2]].copy()); } } face.push(vertIndex); } if ( face[0] !== face[1] && face[0] !== face[2] && face[1] !== face[2] ) { model.faces.push(face); } } } } } // If the model doesn't have normals, compute the normals if (model.vertexNormals.length === 0) { model.computeNormals(); } return model; } /** * Render a 3d model to the screen. * * @method model * @param {p5.Geometry} model Loaded 3d model to be rendered * @example *
* * //draw a spinning teapot * var teapot; * * function preload() { * teapot = loadModel('assets/teapot.obj'); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * model(teapot); * } * *
* * @alt * Vertically rotating 3-d teapot with red, green and blue gradient. * */ p5.prototype.model = function(model) { this._assert3d('model'); p5._validateParameters('model', arguments); if (model.vertices.length > 0) { if (!this._renderer.geometryInHash(model.gid)) { model._makeTriangleEdges()._edgesToVertices(); this._renderer.createBuffers(model.gid, model); } this._renderer.drawBuffers(model.gid); } }; module.exports = p5; },{"../core/core":22,"./p5.Geometry":68}],67:[function(_dereq_,module,exports){ /** * @module Lights, Camera * @submodule Material * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); _dereq_('./p5.Texture'); /** * Loads a custom shader from the provided vertex and fragment * shader paths. The shader files are loaded asynchronously in the * background, so this method should be used in preload(). * * For now, there are three main types of shaders. p5 will automatically * supply appropriate vertices, normals, colors, and lighting attributes * if the parameters defined in the shader match the names. * * @method loadShader * @param {String} [vertFilename] path to file containing vertex shader * source code * @param {String} [fragFilename] path to file containing fragment shader * source code * @return {p5.Shader} a shader object created from the provided * vertex and fragment shader files. */ p5.prototype.loadShader = function(vertFilename, fragFilename) { p5._validateParameters('loadShader', arguments); var loadedShader = new p5.Shader(); var self = this; var loadedFrag = false; var loadedVert = false; this.loadStrings(fragFilename, function(result) { loadedShader._fragSrc = result.join('\n'); loadedFrag = true; if (loadedVert) { self._decrementPreload(); } }); this.loadStrings(vertFilename, function(result) { loadedShader._vertSrc = result.join('\n'); loadedVert = true; if (loadedFrag) { self._decrementPreload(); } }); return loadedShader; }; /** * @method createShader * @param {String} vertSrc source code for the vertex shader * @param {String} fragSrc source code for the fragment shader * @returns {p5.Shader} a shader object created from the provided * vertex and fragment shaders. * * @example *
* * // the 'varying's are shared between both vertex & fragment shaders * var varying = 'precision highp float; varying vec2 vPos;'; * * // the vertex shader is called for each vertex * var vs = * varying + * 'attribute vec3 aPosition;' + * 'void main() { vPos = (gl_Position = vec4(aPosition,1.0)).xy; }'; * * // the fragment shader is called for each pixel * var fs = * varying + * 'uniform vec2 p;' + * 'uniform float r;' + * 'const int I = 500;' + * 'void main() {' + * ' vec2 c = p + vPos * r, z = c;' + * ' float n = 0.0;' + * ' for (int i = I; i > 0; i --) {' + * ' if(z.x*z.x+z.y*z.y > 4.0) {' + * ' n = float(i)/float(I);' + * ' break;' + * ' }' + * ' z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c;' + * ' }' + * ' gl_FragColor = vec4(0.5-cos(n*17.0)/2.0,0.5-cos(n*13.0)/2.0,0.5-cos(n*23.0)/2.0,1.0);' + * '}'; * * var mandel; * function setup() { * createCanvas(100, 100, WEBGL); * * // create and initialize the shader * mandel = createShader(vs, fs); * shader(mandel); * noStroke(); * * // 'p' is the center point of the Mandelbrot image * mandel.setUniform('p', [-0.74364388703, 0.13182590421]); * } * * function draw() { * // 'r' is the size of the image in Mandelbrot-space * mandel.setUniform('r', 1.5 * exp(-6.5 * (1 + sin(millis() / 2000)))); * quad(-1, -1, 1, -1, 1, 1, -1, 1); * } * *
* * @alt * zooming Mandelbrot set. a colorful, infinitely detailed fractal. */ p5.prototype.createShader = function(vertSrc, fragSrc) { this._assert3d('createShader'); p5._validateParameters('createShader', arguments); return new p5.Shader(this._renderer, vertSrc, fragSrc); }; /** * The shader() function lets the user provide a custom shader * to fill in shapes in WEBGL mode. Users can create their * own shaders by loading vertex and fragment shaders with * loadShader(). * * @method shader * @chainable * @param {p5.Shader} [s] the desired p5.Shader to use for rendering * shapes. */ p5.prototype.shader = function(s) { this._assert3d('shader'); p5._validateParameters('shader', arguments); if (s._renderer === undefined) { s._renderer = this._renderer; } if (s.isStrokeShader()) { this._renderer.setStrokeShader(s); } else { this._renderer.setFillShader(s); } return this; }; /** * Normal material for geometry. You can view all * possible materials in this * example. * @method normalMaterial * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * normalMaterial(); * sphere(50); * } * *
* * @alt * Red, green and blue gradient. * */ p5.prototype.normalMaterial = function() { this._assert3d('normalMaterial'); p5._validateParameters('normalMaterial', arguments); this._renderer.drawMode = constants.FILL; this._renderer.setFillShader(this._renderer._getNormalShader()); this._renderer.curFillColor = [1, 1, 1, 1]; this.noStroke(); return this; }; /** * Texture for geometry. You can view other possible materials in this * example. * @method texture * @param {p5.Image|p5.MediaElement|p5.Graphics} tex 2-dimensional graphics * to render as texture * @chainable * @example *
* * var img; * function preload() { * img = loadImage('assets/laDefense.jpg'); * } * * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * rotateZ(frameCount * 0.01); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * //pass image as texture * texture(img); * box(200, 200, 200); * } * *
* *
* * var pg; * function setup() { * createCanvas(100, 100, WEBGL); * pg = createGraphics(200, 200); * pg.textSize(100); * } * * function draw() { * background(0); * pg.background(255); * pg.text('hello!', 0, 100); * //pass image as texture * texture(pg); * plane(200); * } * *
* *
* * var vid; * function preload() { * vid = createVideo('assets/fingers.mov'); * vid.hide(); * vid.loop(); * } * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(0); * //pass video frame as texture * texture(vid); * plane(200); * } * *
* * @alt * Rotating view of many images umbrella and grid roof on a 3d plane * black canvas * black canvas * */ p5.prototype.texture = function(tex) { this._assert3d('texture'); p5._validateParameters('texture', arguments); this._renderer.drawMode = constants.TEXTURE; var shader = this._renderer._useLightShader(); shader.setUniform('uSpecular', false); shader.setUniform('isTexture', true); shader.setUniform('uSampler', tex); this.noStroke(); return this; }; /** * Ambient material for geometry with a given color. You can view all * possible materials in this * example. * @method ambientMaterial * @param {Number} v1 gray value, red or hue value * (depending on the current color mode), * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * ambientLight(100); * pointLight(250, 250, 250, 100, 100, 0); * ambientMaterial(250); * sphere(50); * } * *
* * @alt * radiating light source from top right of canvas * */ /** * @method ambientMaterial * @param {Number[]|String|p5.Color} color color, color Array, or CSS color string * @chainable */ p5.prototype.ambientMaterial = function(v1, v2, v3, a) { this._assert3d('ambientMaterial'); p5._validateParameters('ambientMaterial', arguments); var color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; var shader = this._renderer._useLightShader(); shader.setUniform('uMaterialColor', this._renderer.curFillColor); shader.setUniform('uSpecular', false); shader.setUniform('isTexture', false); return this; }; /** * Specular material for geometry with a given color. You can view all * possible materials in this * example. * @method specularMaterial * @param {Number} v1 gray value, red or hue value * (depending on the current color mode), * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @chainable * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * function draw() { * background(0); * ambientLight(100); * pointLight(250, 250, 250, 100, 100, 0); * specularMaterial(250); * sphere(50); * } * *
* * @alt * diffused radiating light source from top right of canvas * */ /** * @method specularMaterial * @param {Number[]|String|p5.Color} color color Array, or CSS color string * @chainable */ p5.prototype.specularMaterial = function(v1, v2, v3, a) { this._assert3d('specularMaterial'); p5._validateParameters('specularMaterial', arguments); var color = p5.prototype.color.apply(this, arguments); this._renderer.curFillColor = color._array; var shader = this._renderer._useLightShader(); shader.setUniform('uMaterialColor', this._renderer.curFillColor); shader.setUniform('uSpecular', true); shader.setUniform('isTexture', false); return this; }; /** * @private blends colors according to color components. * If alpha value is less than 1, we need to enable blending * on our gl context. Otherwise opaque objects need to a depthMask. * @param {Number[]} color [description] * @return {Number[]]} Normalized numbers array */ p5.RendererGL.prototype._applyColorBlend = function(colors) { var gl = this.GL; var isTexture = this.drawMode === constants.TEXTURE; if (isTexture || colors[colors.length - 1] < 1.0) { gl.depthMask(isTexture); gl.enable(gl.BLEND); gl.blendEquation(gl.FUNC_ADD); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); } else { gl.depthMask(true); gl.disable(gl.BLEND); } return colors; }; module.exports = p5; },{"../core/constants":21,"../core/core":22,"./p5.Texture":74}],68:[function(_dereq_,module,exports){ //some of the functions are adjusted from Three.js(http://threejs.org) 'use strict'; var p5 = _dereq_('../core/core'); /** * p5 Geometry class * @class p5.Geometry * @constructor * @param {function | Object} vertData callback function or Object * containing routine(s) for vertex data generation * @param {Integer} [detailX] number of vertices on horizontal surface * @param {Integer} [detailY] number of vertices on horizontal surface * @param {function} [callback] function to call upon object instantiation. * */ p5.Geometry = function(detailX, detailY, callback) { //an array containing every vertex //@type [p5.Vector] this.vertices = []; //an array containing every vertex for stroke drawing this.lineVertices = []; //an array 1 normal per lineVertex with //final position representing which direction to //displace for strokeWeight //[[0,0,-1,1], [0,1,0,-1] ...]; this.lineNormals = []; //an array containing 1 normal per vertex //@type [p5.Vector] //[p5.Vector, p5.Vector, p5.Vector,p5.Vector, p5.Vector, p5.Vector,...] this.vertexNormals = []; //an array containing each three vertex indices that form a face //[[0, 1, 2], [2, 1, 3], ...] this.faces = []; //a 2D array containing uvs for every vertex //[[0.0,0.0],[1.0,0.0], ...] this.uvs = []; // a 2D array containing edge connectivity pattern for create line vertices //based on faces for most objects; this.edges = []; this.detailX = detailX !== undefined ? detailX : 1; this.detailY = detailY !== undefined ? detailY : 1; if (callback instanceof Function) { callback.call(this); } return this; // TODO: is this a constructor? }; /** * @method computeFaces * @chainable */ p5.Geometry.prototype.computeFaces = function() { this.faces.length = 0; var sliceCount = this.detailX + 1; var a, b, c, d; for (var i = 0; i < this.detailY; i++) { for (var j = 0; j < this.detailX; j++) { a = i * sliceCount + j; // + offset; b = i * sliceCount + j + 1; // + offset; c = (i + 1) * sliceCount + j + 1; // + offset; d = (i + 1) * sliceCount + j; // + offset; this.faces.push([a, b, d]); this.faces.push([d, b, c]); } } return this; }; p5.Geometry.prototype._getFaceNormal = function(faceId) { //This assumes that vA->vB->vC is a counter-clockwise ordering var face = this.faces[faceId]; var vA = this.vertices[face[0]]; var vB = this.vertices[face[1]]; var vC = this.vertices[face[2]]; var ab = p5.Vector.sub(vB, vA); var ac = p5.Vector.sub(vC, vA); var n = p5.Vector.cross(ab, ac); var ln = p5.Vector.mag(n); var sinAlpha = ln / (p5.Vector.mag(ab) * p5.Vector.mag(ac)); if (sinAlpha === 0 || isNaN(sinAlpha)) { console.warn( 'p5.Geometry.prototype._getFaceNormal:', 'face has colinear sides or a repeated vertex' ); return n; } if (sinAlpha > 1) sinAlpha = 1; // handle float rounding error return n.mult(Math.asin(sinAlpha) / ln); }; /** * computes smooth normals per vertex as an average of each * face. * @method computeNormals * @chainable */ p5.Geometry.prototype.computeNormals = function() { var vertexNormals = this.vertexNormals; var vertices = this.vertices; var faces = this.faces; var iv; // initialize the vertexNormals array with empty vectors vertexNormals.length = 0; for (iv = 0; iv < vertices.length; ++iv) { vertexNormals.push(new p5.Vector()); } // loop through all the faces adding its normal to the normal // of each of its vertices for (var f = 0; f < faces.length; ++f) { var face = faces[f]; var faceNormal = this._getFaceNormal(f); // all three vertices get the normal added for (var fv = 0; fv < 3; ++fv) { var vertexIndex = face[fv]; vertexNormals[vertexIndex].add(faceNormal); } } // normalize the normals for (iv = 0; iv < vertices.length; ++iv) { vertexNormals[iv].normalize(); } return this; }; /** * Averages the vertex normals. Used in curved * surfaces * @method averageNormals * @chainable */ p5.Geometry.prototype.averageNormals = function() { for (var i = 0; i <= this.detailY; i++) { var offset = this.detailX + 1; var temp = p5.Vector.add( this.vertexNormals[i * offset], this.vertexNormals[i * offset + this.detailX] ); temp = p5.Vector.div(temp, 2); this.vertexNormals[i * offset] = temp; this.vertexNormals[i * offset + this.detailX] = temp; } return this; }; /** * Averages pole normals. Used in spherical primitives * @method averagePoleNormals * @chainable */ p5.Geometry.prototype.averagePoleNormals = function() { //average the north pole var sum = new p5.Vector(0, 0, 0); for (var i = 0; i < this.detailX; i++) { sum.add(this.vertexNormals[i]); } sum = p5.Vector.div(sum, this.detailX); for (i = 0; i < this.detailX; i++) { this.vertexNormals[i] = sum; } //average the south pole sum = new p5.Vector(0, 0, 0); for ( i = this.vertices.length - 1; i > this.vertices.length - 1 - this.detailX; i-- ) { sum.add(this.vertexNormals[i]); } sum = p5.Vector.div(sum, this.detailX); for ( i = this.vertices.length - 1; i > this.vertices.length - 1 - this.detailX; i-- ) { this.vertexNormals[i] = sum; } return this; }; /** * Create a 2D array for establishing stroke connections * @private * @chainable */ p5.Geometry.prototype._makeTriangleEdges = function() { this.edges.length = 0; if (Array.isArray(this.strokeIndices)) { for (var i = 0, max = this.strokeIndices.length; i < max; i++) { this.edges.push(this.strokeIndices[i]); } } else { for (var j = 0; j < this.faces.length; j++) { this.edges.push([this.faces[j][0], this.faces[j][1]]); this.edges.push([this.faces[j][1], this.faces[j][2]]); this.edges.push([this.faces[j][2], this.faces[j][0]]); } } return this; }; /** * Create 4 vertices for each stroke line, two at the beginning position * and two at the end position. These vertices are displaced relative to * that line's normal on the GPU * @private * @chainable */ p5.Geometry.prototype._edgesToVertices = function() { this.lineVertices.length = 0; this.lineNormals.length = 0; for (var i = 0; i < this.edges.length; i++) { var begin = this.vertices[this.edges[i][0]]; var end = this.vertices[this.edges[i][1]]; var dir = end .copy() .sub(begin) .normalize(); var a = begin.array(); var b = begin.array(); var c = end.array(); var d = end.array(); var dirAdd = dir.array(); var dirSub = dir.array(); // below is used to displace the pair of vertices at beginning and end // in opposite directions dirAdd.push(1); dirSub.push(-1); this.lineNormals.push(dirAdd, dirSub, dirAdd, dirAdd, dirSub, dirSub); this.lineVertices.push(a, b, c, c, b, d); } return this; }; /** * Modifies all vertices to be centered within the range -100 to 100. * @method normalize * @chainable */ p5.Geometry.prototype.normalize = function() { if (this.vertices.length > 0) { // Find the corners of our bounding box var maxPosition = this.vertices[0].copy(); var minPosition = this.vertices[0].copy(); for (var i = 0; i < this.vertices.length; i++) { maxPosition.x = Math.max(maxPosition.x, this.vertices[i].x); minPosition.x = Math.min(minPosition.x, this.vertices[i].x); maxPosition.y = Math.max(maxPosition.y, this.vertices[i].y); minPosition.y = Math.min(minPosition.y, this.vertices[i].y); maxPosition.z = Math.max(maxPosition.z, this.vertices[i].z); minPosition.z = Math.min(minPosition.z, this.vertices[i].z); } var center = p5.Vector.lerp(maxPosition, minPosition, 0.5); var dist = p5.Vector.sub(maxPosition, minPosition); var longestDist = Math.max(Math.max(dist.x, dist.y), dist.z); var scale = 200 / longestDist; for (i = 0; i < this.vertices.length; i++) { this.vertices[i].sub(center); this.vertices[i].mult(scale); } } return this; }; module.exports = p5.Geometry; },{"../core/core":22}],69:[function(_dereq_,module,exports){ /** * @requires constants * @todo see methods below needing further implementation. * future consideration: implement SIMD optimizations * when browser compatibility becomes available * https://developer.mozilla.org/en-US/docs/Web/JavaScript/ * Reference/Global_Objects/SIMD */ 'use strict'; var p5 = _dereq_('../core/core'); var GLMAT_ARRAY_TYPE = Array; var isMatrixArray = function(x) { return x instanceof Array; }; if (typeof Float32Array !== 'undefined') { GLMAT_ARRAY_TYPE = Float32Array; isMatrixArray = function(x) { return x instanceof Array || x instanceof Float32Array; }; } /** * A class to describe a 4x4 matrix * for model and view matrix manipulation in the p5js webgl renderer. * @class p5.Matrix * @private * @constructor * @param {Array} [mat4] array literal of our 4x4 matrix */ p5.Matrix = function() { var args = new Array(arguments.length); for (var i = 0; i < args.length; ++i) { args[i] = arguments[i]; } // This is default behavior when object // instantiated using createMatrix() // @todo implement createMatrix() in core/math.js if (args.length && args[args.length - 1] instanceof p5) { this.p5 = args[args.length - 1]; } if (args[0] === 'mat3') { this.mat3 = Array.isArray(args[1]) ? args[1] : new GLMAT_ARRAY_TYPE([1, 0, 0, 0, 1, 0, 0, 0, 1]); } else { this.mat4 = Array.isArray(args[0]) ? args[0] : new GLMAT_ARRAY_TYPE([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]); } return this; }; /** * Sets the x, y, and z component of the vector using two or three separate * variables, the data from a p5.Matrix, or the values from a float array. * * @method set * @param {p5.Matrix|Float32Array|Number[]} [inMatrix] the input p5.Matrix or * an Array of length 16 * @chainable */ /** * @method set * @param {Number[]} elements 16 numbers passed by value to avoid * array copying. * @chainable */ p5.Matrix.prototype.set = function(inMatrix) { if (inMatrix instanceof p5.Matrix) { this.mat4 = inMatrix.mat4; return this; } else if (isMatrixArray(inMatrix)) { this.mat4 = inMatrix; return this; } else if (arguments.length === 16) { this.mat4[0] = arguments[0]; this.mat4[1] = arguments[1]; this.mat4[2] = arguments[2]; this.mat4[3] = arguments[3]; this.mat4[4] = arguments[4]; this.mat4[5] = arguments[5]; this.mat4[6] = arguments[6]; this.mat4[7] = arguments[7]; this.mat4[8] = arguments[8]; this.mat4[9] = arguments[9]; this.mat4[10] = arguments[10]; this.mat4[11] = arguments[11]; this.mat4[12] = arguments[12]; this.mat4[13] = arguments[13]; this.mat4[14] = arguments[14]; this.mat4[15] = arguments[15]; } return this; }; /** * Gets a copy of the vector, returns a p5.Matrix object. * * @method get * @return {p5.Matrix} the copy of the p5.Matrix object */ p5.Matrix.prototype.get = function() { return new p5.Matrix(this.mat4, this.p5); }; /** * return a copy of a matrix * @method copy * @return {p5.Matrix} the result matrix */ p5.Matrix.prototype.copy = function() { var copied = new p5.Matrix(this.p5); copied.mat4[0] = this.mat4[0]; copied.mat4[1] = this.mat4[1]; copied.mat4[2] = this.mat4[2]; copied.mat4[3] = this.mat4[3]; copied.mat4[4] = this.mat4[4]; copied.mat4[5] = this.mat4[5]; copied.mat4[6] = this.mat4[6]; copied.mat4[7] = this.mat4[7]; copied.mat4[8] = this.mat4[8]; copied.mat4[9] = this.mat4[9]; copied.mat4[10] = this.mat4[10]; copied.mat4[11] = this.mat4[11]; copied.mat4[12] = this.mat4[12]; copied.mat4[13] = this.mat4[13]; copied.mat4[14] = this.mat4[14]; copied.mat4[15] = this.mat4[15]; return copied; }; /** * return an identity matrix * @method identity * @return {p5.Matrix} the result matrix */ p5.Matrix.identity = function(pInst) { return new p5.Matrix(pInst); }; /** * transpose according to a given matrix * @method transpose * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be * based on to transpose * @chainable */ p5.Matrix.prototype.transpose = function(a) { var a01, a02, a03, a12, a13, a23; if (a instanceof p5.Matrix) { a01 = a.mat4[1]; a02 = a.mat4[2]; a03 = a.mat4[3]; a12 = a.mat4[6]; a13 = a.mat4[7]; a23 = a.mat4[11]; this.mat4[0] = a.mat4[0]; this.mat4[1] = a.mat4[4]; this.mat4[2] = a.mat4[8]; this.mat4[3] = a.mat4[12]; this.mat4[4] = a01; this.mat4[5] = a.mat4[5]; this.mat4[6] = a.mat4[9]; this.mat4[7] = a.mat4[13]; this.mat4[8] = a02; this.mat4[9] = a12; this.mat4[10] = a.mat4[10]; this.mat4[11] = a.mat4[14]; this.mat4[12] = a03; this.mat4[13] = a13; this.mat4[14] = a23; this.mat4[15] = a.mat4[15]; } else if (isMatrixArray(a)) { a01 = a[1]; a02 = a[2]; a03 = a[3]; a12 = a[6]; a13 = a[7]; a23 = a[11]; this.mat4[0] = a[0]; this.mat4[1] = a[4]; this.mat4[2] = a[8]; this.mat4[3] = a[12]; this.mat4[4] = a01; this.mat4[5] = a[5]; this.mat4[6] = a[9]; this.mat4[7] = a[13]; this.mat4[8] = a02; this.mat4[9] = a12; this.mat4[10] = a[10]; this.mat4[11] = a[14]; this.mat4[12] = a03; this.mat4[13] = a13; this.mat4[14] = a23; this.mat4[15] = a[15]; } return this; }; /** * invert matrix according to a give matrix * @method invert * @param {p5.Matrix|Float32Array|Number[]} a the matrix to be * based on to invert * @chainable */ p5.Matrix.prototype.invert = function(a) { var a00, a01, a02, a03, a10, a11, a12, a13; var a20, a21, a22, a23, a30, a31, a32, a33; if (a instanceof p5.Matrix) { a00 = a.mat4[0]; a01 = a.mat4[1]; a02 = a.mat4[2]; a03 = a.mat4[3]; a10 = a.mat4[4]; a11 = a.mat4[5]; a12 = a.mat4[6]; a13 = a.mat4[7]; a20 = a.mat4[8]; a21 = a.mat4[9]; a22 = a.mat4[10]; a23 = a.mat4[11]; a30 = a.mat4[12]; a31 = a.mat4[13]; a32 = a.mat4[14]; a33 = a.mat4[15]; } else if (isMatrixArray(a)) { a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; a30 = a[12]; a31 = a[13]; a32 = a[14]; a33 = a[15]; } var b00 = a00 * a11 - a01 * a10; var b01 = a00 * a12 - a02 * a10; var b02 = a00 * a13 - a03 * a10; var b03 = a01 * a12 - a02 * a11; var b04 = a01 * a13 - a03 * a11; var b05 = a02 * a13 - a03 * a12; var b06 = a20 * a31 - a21 * a30; var b07 = a20 * a32 - a22 * a30; var b08 = a20 * a33 - a23 * a30; var b09 = a21 * a32 - a22 * a31; var b10 = a21 * a33 - a23 * a31; var b11 = a22 * a33 - a23 * a32; // Calculate the determinant var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; this.mat4[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; this.mat4[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; this.mat4[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; this.mat4[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; this.mat4[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; this.mat4[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; this.mat4[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; this.mat4[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; this.mat4[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; this.mat4[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; this.mat4[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; this.mat4[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; this.mat4[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; this.mat4[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; this.mat4[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; this.mat4[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; return this; }; /** * Inverts a 3x3 matrix * @method invert3x3 * @chainable */ p5.Matrix.prototype.invert3x3 = function() { var a00 = this.mat3[0]; var a01 = this.mat3[1]; var a02 = this.mat3[2]; var a10 = this.mat3[3]; var a11 = this.mat3[4]; var a12 = this.mat3[5]; var a20 = this.mat3[6]; var a21 = this.mat3[7]; var a22 = this.mat3[8]; var b01 = a22 * a11 - a12 * a21; var b11 = -a22 * a10 + a12 * a20; var b21 = a21 * a10 - a11 * a20; // Calculate the determinant var det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } det = 1.0 / det; this.mat3[0] = b01 * det; this.mat3[1] = (-a22 * a01 + a02 * a21) * det; this.mat3[2] = (a12 * a01 - a02 * a11) * det; this.mat3[3] = b11 * det; this.mat3[4] = (a22 * a00 - a02 * a20) * det; this.mat3[5] = (-a12 * a00 + a02 * a10) * det; this.mat3[6] = b21 * det; this.mat3[7] = (-a21 * a00 + a01 * a20) * det; this.mat3[8] = (a11 * a00 - a01 * a10) * det; return this; }; /** * transposes a 3x3 p5.Matrix by a mat3 * @method transpose3x3 * @param {Number[]} mat3 1-dimensional array * @chainable */ p5.Matrix.prototype.transpose3x3 = function(mat3) { var a01 = mat3[1], a02 = mat3[2], a12 = mat3[5]; this.mat3[1] = mat3[3]; this.mat3[2] = mat3[6]; this.mat3[3] = a01; this.mat3[5] = mat3[7]; this.mat3[6] = a02; this.mat3[7] = a12; return this; }; /** * converts a 4x4 matrix to its 3x3 inverse tranform * commonly used in MVMatrix to NMatrix conversions. * @method invertTranspose * @param {p5.Matrix} mat4 the matrix to be based on to invert * @chainable * @todo finish implementation */ p5.Matrix.prototype.inverseTranspose = function(matrix) { if (this.mat3 === undefined) { console.error('sorry, this function only works with mat3'); } else { //convert mat4 -> mat3 this.mat3[0] = matrix.mat4[0]; this.mat3[1] = matrix.mat4[1]; this.mat3[2] = matrix.mat4[2]; this.mat3[3] = matrix.mat4[4]; this.mat3[4] = matrix.mat4[5]; this.mat3[5] = matrix.mat4[6]; this.mat3[6] = matrix.mat4[8]; this.mat3[7] = matrix.mat4[9]; this.mat3[8] = matrix.mat4[10]; } var inverse = this.invert3x3(); // check inverse succeded if (inverse) { inverse.transpose3x3(this.mat3); } else { // in case of singularity, just zero the matrix for (var i = 0; i < 9; i++) { this.mat3[i] = 0; } } return this; }; /** * inspired by Toji's mat4 determinant * @method determinant * @return {Number} Determinant of our 4x4 matrix */ p5.Matrix.prototype.determinant = function() { var d00 = this.mat4[0] * this.mat4[5] - this.mat4[1] * this.mat4[4], d01 = this.mat4[0] * this.mat4[6] - this.mat4[2] * this.mat4[4], d02 = this.mat4[0] * this.mat4[7] - this.mat4[3] * this.mat4[4], d03 = this.mat4[1] * this.mat4[6] - this.mat4[2] * this.mat4[5], d04 = this.mat4[1] * this.mat4[7] - this.mat4[3] * this.mat4[5], d05 = this.mat4[2] * this.mat4[7] - this.mat4[3] * this.mat4[6], d06 = this.mat4[8] * this.mat4[13] - this.mat4[9] * this.mat4[12], d07 = this.mat4[8] * this.mat4[14] - this.mat4[10] * this.mat4[12], d08 = this.mat4[8] * this.mat4[15] - this.mat4[11] * this.mat4[12], d09 = this.mat4[9] * this.mat4[14] - this.mat4[10] * this.mat4[13], d10 = this.mat4[9] * this.mat4[15] - this.mat4[11] * this.mat4[13], d11 = this.mat4[10] * this.mat4[15] - this.mat4[11] * this.mat4[14]; // Calculate the determinant return d00 * d11 - d01 * d10 + d02 * d09 + d03 * d08 - d04 * d07 + d05 * d06; }; /** * multiply two mat4s * @method mult * @param {p5.Matrix|Float32Array|Number[]} multMatrix The matrix * we want to multiply by * @chainable */ p5.Matrix.prototype.mult = function(multMatrix) { var _src; if (multMatrix === this || multMatrix === this.mat4) { _src = this.copy().mat4; // only need to allocate in this rare case } else if (multMatrix instanceof p5.Matrix) { _src = multMatrix.mat4; } else if (isMatrixArray(multMatrix)) { _src = multMatrix; } else { return; // nothing to do. } // each row is used for the multiplier var b0 = this.mat4[0], b1 = this.mat4[1], b2 = this.mat4[2], b3 = this.mat4[3]; this.mat4[0] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; this.mat4[1] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; this.mat4[2] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; this.mat4[3] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; b0 = this.mat4[4]; b1 = this.mat4[5]; b2 = this.mat4[6]; b3 = this.mat4[7]; this.mat4[4] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; this.mat4[5] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; this.mat4[6] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; this.mat4[7] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; b0 = this.mat4[8]; b1 = this.mat4[9]; b2 = this.mat4[10]; b3 = this.mat4[11]; this.mat4[8] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; this.mat4[9] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; this.mat4[10] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; this.mat4[11] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; b0 = this.mat4[12]; b1 = this.mat4[13]; b2 = this.mat4[14]; b3 = this.mat4[15]; this.mat4[12] = b0 * _src[0] + b1 * _src[4] + b2 * _src[8] + b3 * _src[12]; this.mat4[13] = b0 * _src[1] + b1 * _src[5] + b2 * _src[9] + b3 * _src[13]; this.mat4[14] = b0 * _src[2] + b1 * _src[6] + b2 * _src[10] + b3 * _src[14]; this.mat4[15] = b0 * _src[3] + b1 * _src[7] + b2 * _src[11] + b3 * _src[15]; return this; }; /** * scales a p5.Matrix by scalars or a vector * @method scale * @param {p5.Vector|Float32Array|Number[]} s vector to scale by * @chainable */ p5.Matrix.prototype.scale = function(x, y, z) { if (x instanceof p5.Vector) { // x is a vector, extract the components from it. y = x.y; z = x.z; x = x.x; // must be last } else if (x instanceof Array) { // x is an array, extract the components from it. y = x[1]; z = x[2]; x = x[0]; // must be last } this.mat4[0] *= x; this.mat4[1] *= x; this.mat4[2] *= x; this.mat4[3] *= x; this.mat4[4] *= y; this.mat4[5] *= y; this.mat4[6] *= y; this.mat4[7] *= y; this.mat4[8] *= z; this.mat4[9] *= z; this.mat4[10] *= z; this.mat4[11] *= z; return this; }; /** * rotate our Matrix around an axis by the given angle. * @method rotate * @param {Number} a The angle of rotation in radians * @param {p5.Vector|Number[]} axis the axis(es) to rotate around * @chainable * inspired by Toji's gl-matrix lib, mat4 rotation */ p5.Matrix.prototype.rotate = function(a, x, y, z) { var _a = this.p5 ? this.p5._toRadians(a) : a; if (x instanceof p5.Vector) { // x is a vector, extract the components from it. y = x.y; z = x.z; x = x.x; //must be last } else if (x instanceof Array) { // x is an array, extract the components from it. y = x[1]; z = x[2]; x = x[0]; //must be last } var len = Math.sqrt(x * x + y * y + z * z); x *= 1 / len; y *= 1 / len; z *= 1 / len; var a00 = this.mat4[0]; var a01 = this.mat4[1]; var a02 = this.mat4[2]; var a03 = this.mat4[3]; var a10 = this.mat4[4]; var a11 = this.mat4[5]; var a12 = this.mat4[6]; var a13 = this.mat4[7]; var a20 = this.mat4[8]; var a21 = this.mat4[9]; var a22 = this.mat4[10]; var a23 = this.mat4[11]; //sin,cos, and tan of respective angle var sA = Math.sin(_a); var cA = Math.cos(_a); var tA = 1 - cA; // Construct the elements of the rotation matrix var b00 = x * x * tA + cA; var b01 = y * x * tA + z * sA; var b02 = z * x * tA - y * sA; var b10 = x * y * tA - z * sA; var b11 = y * y * tA + cA; var b12 = z * y * tA + x * sA; var b20 = x * z * tA + y * sA; var b21 = y * z * tA - x * sA; var b22 = z * z * tA + cA; // rotation-specific matrix multiplication this.mat4[0] = a00 * b00 + a10 * b01 + a20 * b02; this.mat4[1] = a01 * b00 + a11 * b01 + a21 * b02; this.mat4[2] = a02 * b00 + a12 * b01 + a22 * b02; this.mat4[3] = a03 * b00 + a13 * b01 + a23 * b02; this.mat4[4] = a00 * b10 + a10 * b11 + a20 * b12; this.mat4[5] = a01 * b10 + a11 * b11 + a21 * b12; this.mat4[6] = a02 * b10 + a12 * b11 + a22 * b12; this.mat4[7] = a03 * b10 + a13 * b11 + a23 * b12; this.mat4[8] = a00 * b20 + a10 * b21 + a20 * b22; this.mat4[9] = a01 * b20 + a11 * b21 + a21 * b22; this.mat4[10] = a02 * b20 + a12 * b21 + a22 * b22; this.mat4[11] = a03 * b20 + a13 * b21 + a23 * b22; return this; }; /** * @todo finish implementing this method! * translates * @method translate * @param {Number[]} v vector to translate by * @chainable */ p5.Matrix.prototype.translate = function(v) { var x = v[0], y = v[1], z = v[2] || 0; this.mat4[12] += this.mat4[0] * x + this.mat4[4] * y + this.mat4[8] * z; this.mat4[13] += this.mat4[1] * x + this.mat4[5] * y + this.mat4[9] * z; this.mat4[14] += this.mat4[2] * x + this.mat4[6] * y + this.mat4[10] * z; this.mat4[15] += this.mat4[3] * x + this.mat4[7] * y + this.mat4[11] * z; }; p5.Matrix.prototype.rotateX = function(a) { this.rotate(a, 1, 0, 0); }; p5.Matrix.prototype.rotateY = function(a) { this.rotate(a, 0, 1, 0); }; p5.Matrix.prototype.rotateZ = function(a) { this.rotate(a, 0, 0, 1); }; /** * sets the perspective matrix * @method perspective * @param {Number} fovy [description] * @param {Number} aspect [description] * @param {Number} near near clipping plane * @param {Number} far far clipping plane * @chainable */ p5.Matrix.prototype.perspective = function(fovy, aspect, near, far) { var f = 1.0 / Math.tan(fovy / 2), nf = 1 / (near - far); this.mat4[0] = f / aspect; this.mat4[1] = 0; this.mat4[2] = 0; this.mat4[3] = 0; this.mat4[4] = 0; this.mat4[5] = f; this.mat4[6] = 0; this.mat4[7] = 0; this.mat4[8] = 0; this.mat4[9] = 0; this.mat4[10] = (far + near) * nf; this.mat4[11] = -1; this.mat4[12] = 0; this.mat4[13] = 0; this.mat4[14] = 2 * far * near * nf; this.mat4[15] = 0; return this; }; /** * sets the ortho matrix * @method ortho * @param {Number} left [description] * @param {Number} right [description] * @param {Number} bottom [description] * @param {Number} top [description] * @param {Number} near near clipping plane * @param {Number} far far clipping plane * @chainable */ p5.Matrix.prototype.ortho = function(left, right, bottom, top, near, far) { var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far); this.mat4[0] = -2 * lr; this.mat4[1] = 0; this.mat4[2] = 0; this.mat4[3] = 0; this.mat4[4] = 0; this.mat4[5] = -2 * bt; this.mat4[6] = 0; this.mat4[7] = 0; this.mat4[8] = 0; this.mat4[9] = 0; this.mat4[10] = 2 * nf; this.mat4[11] = 0; this.mat4[12] = (left + right) * lr; this.mat4[13] = (top + bottom) * bt; this.mat4[14] = (far + near) * nf; this.mat4[15] = 1; return this; }; /** * PRIVATE */ // matrix methods adapted from: // https://developer.mozilla.org/en-US/docs/Web/WebGL/ // gluPerspective // // function _makePerspective(fovy, aspect, znear, zfar){ // var ymax = znear * Math.tan(fovy * Math.PI / 360.0); // var ymin = -ymax; // var xmin = ymin * aspect; // var xmax = ymax * aspect; // return _makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); // } //// //// glFrustum //// //function _makeFrustum(left, right, bottom, top, znear, zfar){ // var X = 2*znear/(right-left); // var Y = 2*znear/(top-bottom); // var A = (right+left)/(right-left); // var B = (top+bottom)/(top-bottom); // var C = -(zfar+znear)/(zfar-znear); // var D = -2*zfar*znear/(zfar-znear); // var frustrumMatrix =[ // X, 0, A, 0, // 0, Y, B, 0, // 0, 0, C, D, // 0, 0, -1, 0 //]; //return frustrumMatrix; // } // function _setMVPMatrices(){ ////an identity matrix ////@TODO use the p5.Matrix class to abstract away our MV matrices and ///other math //var _mvMatrix = //[ // 1.0,0.0,0.0,0.0, // 0.0,1.0,0.0,0.0, // 0.0,0.0,1.0,0.0, // 0.0,0.0,0.0,1.0 //]; module.exports = p5.Matrix; },{"../core/core":22}],70:[function(_dereq_,module,exports){ /** * Welcome to RendererGL Immediate Mode. * Immediate mode is used for drawing custom shapes * from a set of vertices. Immediate Mode is activated * when you call beginShape() & de-activated when you call endShape(). * Immediate mode is a style of programming borrowed * from OpenGL's (now-deprecated) immediate mode. * It differs from p5.js' default, Retained Mode, which caches * geometries and buffers on the CPU to reduce the number of webgl * draw calls. Retained mode is more efficient & performative, * however, Immediate Mode is useful for sketching quick * geometric ideas. */ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); /** * Begin shape drawing. This is a helpful way of generating * custom shapes quickly. However in WEBGL mode, application * performance will likely drop as a result of too many calls to * beginShape() / endShape(). As a high performance alternative, * please use p5.js geometry primitives. * @private * @method beginShape * @param {Number} mode webgl primitives mode. beginShape supports the * following modes: * POINTS,LINES,LINE_STRIP,LINE_LOOP,TRIANGLES, * TRIANGLE_STRIP,and TRIANGLE_FAN. * @chainable */ p5.RendererGL.prototype.beginShape = function(mode) { //default shape mode is line_strip this.immediateMode.shapeMode = mode !== undefined ? mode : constants.LINE_STRIP; //if we haven't yet initialized our //immediateMode vertices & buffers, create them now! if (this.immediateMode.vertices === undefined) { this.immediateMode.vertices = []; this.immediateMode.edges = []; this.immediateMode.lineVertices = []; this.immediateMode.vertexColors = []; this.immediateMode.lineNormals = []; this.immediateMode.uvCoords = []; this.immediateMode.vertexBuffer = this.GL.createBuffer(); this.immediateMode.colorBuffer = this.GL.createBuffer(); this.immediateMode.uvBuffer = this.GL.createBuffer(); this.immediateMode.lineVertexBuffer = this.GL.createBuffer(); this.immediateMode.lineNormalBuffer = this.GL.createBuffer(); } else { this.immediateMode.vertices.length = 0; this.immediateMode.edges.length = 0; this.immediateMode.lineVertices.length = 0; this.immediateMode.lineNormals.length = 0; this.immediateMode.vertexColors.length = 0; this.immediateMode.uvCoords.length = 0; } this.isImmediateDrawing = true; return this; }; /** * adds a vertex to be drawn in a custom Shape. * @private * @method vertex * @param {Number} x x-coordinate of vertex * @param {Number} y y-coordinate of vertex * @param {Number} z z-coordinate of vertex * @chainable * @TODO implement handling of p5.Vector args */ p5.RendererGL.prototype.vertex = function(x, y) { var z, u, v; // default to (x, y) mode: all other arugments assumed to be 0. z = u = v = 0; if (arguments.length === 3) { // (x, y, z) mode: (u, v) assumed to be 0. z = arguments[2]; } else if (arguments.length === 4) { // (x, y, u, v) mode: z assumed to be 0. u = arguments[2]; v = arguments[3]; } else if (arguments.length === 5) { // (x, y, z, u, v) mode z = arguments[2]; u = arguments[3]; v = arguments[4]; } var vert = new p5.Vector(x, y, z); this.immediateMode.vertices.push(vert); var vertexColor = this.curFillColor || [0.5, 0.5, 0.5, 1.0]; this.immediateMode.vertexColors.push( vertexColor[0], vertexColor[1], vertexColor[2], vertexColor[3] ); this.immediateMode.uvCoords.push(u, v); return this; }; /** * End shape drawing and render vertices to screen. * @chainable */ p5.RendererGL.prototype.endShape = function( mode, isCurve, isBezier, isQuadratic, isContour, shapeKind ) { this._useImmediateModeShader(); if (this._doStroke && this.drawMode !== constants.TEXTURE) { for (var i = 0; i < this.immediateMode.vertices.length - 1; i++) { this.immediateMode.edges.push([i, i + 1]); } if (mode === constants.CLOSE) { this.immediateMode.edges.push([ this.immediateMode.vertices.length - 1, 0 ]); } p5.Geometry.prototype._edgesToVertices.call(this.immediateMode); this._drawStrokeImmediateMode(); } if (this._doFill) { this._drawFillImmediateMode( mode, isCurve, isBezier, isQuadratic, isContour, shapeKind ); } //clear out our vertexPositions & colors arrays //after rendering this.immediateMode.vertices.length = 0; this.immediateMode.vertexColors.length = 0; this.immediateMode.uvCoords.length = 0; this.isImmediateDrawing = false; return this; }; p5.RendererGL.prototype._drawFillImmediateMode = function( mode, isCurve, isBezier, isQuadratic, isContour, shapeKind ) { var gl = this.GL; this.curFillShader.bindShader(); // initialize the fill shader's 'aPosition' buffer if (this.curFillShader.attributes.aPosition) { //vertex position Attribute this._bindBuffer( this.immediateMode.vertexBuffer, gl.ARRAY_BUFFER, this._vToNArray(this.immediateMode.vertices), Float32Array, gl.DYNAMIC_DRAW ); this.curFillShader.enableAttrib( this.curFillShader.attributes.aPosition.location, 3, gl.FLOAT, false, 0, 0 ); } // initialize the fill shader's 'aVertexColor' buffer if ( this.drawMode === constants.FILL && this.curFillShader.attributes.aVertexColor ) { this._bindBuffer( this.immediateMode.colorBuffer, gl.ARRAY_BUFFER, this.immediateMode.vertexColors, Float32Array, gl.DYNAMIC_DRAW ); this.curFillShader.enableAttrib( this.curFillShader.attributes.aVertexColor.location, 4, gl.FLOAT, false, 0, 0 ); } // initialize the fill shader's 'aTexCoord' buffer if ( this.drawMode === constants.TEXTURE && this.curFillShader.attributes.aTexCoord ) { //texture coordinate Attribute this._bindBuffer( this.immediateMode.uvBuffer, gl.ARRAY_BUFFER, this.immediateMode.uvCoords, Float32Array, gl.DYNAMIC_DRAW ); this.curFillShader.enableAttrib( this.curFillShader.attributes.aTexCoord.location, 2, gl.FLOAT, false, 0, 0 ); } //if (true || mode) { if (this.drawMode === constants.FILL || this.drawMode === constants.TEXTURE) { switch (this.immediateMode.shapeMode) { case constants.LINE_STRIP: case constants.LINES: case constants.TRIANGLES: this.immediateMode.shapeMode = constants.TRIANGLE_FAN; break; } } else { switch (this.immediateMode.shapeMode) { case constants.LINE_STRIP: case constants.LINES: this.immediateMode.shapeMode = constants.LINE_LOOP; break; } } //} //QUADS & QUAD_STRIP are not supported primitives modes //in webgl. if ( this.immediateMode.shapeMode === constants.QUADS || this.immediateMode.shapeMode === constants.QUAD_STRIP ) { throw new Error( 'sorry, ' + this.immediateMode.shapeMode + ' not yet implemented in webgl mode.' ); } else { this._applyColorBlend(this.curFillColor); gl.enable(gl.BLEND); gl.drawArrays( this.immediateMode.shapeMode, 0, this.immediateMode.vertices.length ); } // todo / optimizations? leave bound until another shader is set? this.curFillShader.unbindShader(); }; p5.RendererGL.prototype._drawStrokeImmediateMode = function() { var gl = this.GL; this.curStrokeShader.bindShader(); // initialize the stroke shader's 'aPosition' buffer if (this.curStrokeShader.attributes.aPosition) { this._bindBuffer( this.immediateMode.lineVertexBuffer, gl.ARRAY_BUFFER, this._flatten(this.immediateMode.lineVertices), Float32Array, gl.STATIC_DRAW ); this.curStrokeShader.enableAttrib( this.curStrokeShader.attributes.aPosition.location, 3, gl.FLOAT, false, 0, 0 ); } // initialize the stroke shader's 'aDirection' buffer if (this.curStrokeShader.attributes.aDirection) { this._bindBuffer( this.immediateMode.lineNormalBuffer, gl.ARRAY_BUFFER, this._flatten(this.immediateMode.lineNormals), Float32Array, gl.STATIC_DRAW ); this.curStrokeShader.enableAttrib( this.curStrokeShader.attributes.aDirection.location, 4, gl.FLOAT, false, 0, 0 ); } this._applyColorBlend(this.curStrokeColor); gl.drawArrays(gl.TRIANGLES, 0, this.immediateMode.lineVertices.length); // todo / optimizations? leave bound until another shader is set? this.curStrokeShader.unbindShader(); }; module.exports = p5.RendererGL; },{"../core/constants":21,"../core/core":22}],71:[function(_dereq_,module,exports){ //Retained Mode. The default mode for rendering 3D primitives //in WEBGL. 'use strict'; var p5 = _dereq_('../core/core'); var hashCount = 0; /** * _initBufferDefaults * @private * @description initializes buffer defaults. runs each time a new geometry is * registered * @param {String} gId key of the geometry object */ p5.RendererGL.prototype._initBufferDefaults = function(gId) { this._freeBuffers(gId); //@TODO remove this limit on hashes in gHash hashCount++; if (hashCount > 1000) { var key = Object.keys(this.gHash)[0]; delete this.gHash[key]; hashCount--; } //create a new entry in our gHash this.gHash[gId] = {}; }; p5.RendererGL.prototype._freeBuffers = function(gId) { var geometry = this.gHash[gId]; if (!geometry) { return; } delete this.gHash[gId]; hashCount--; var gl = this.GL; geometry.vertexBuffer && gl.deleteBuffer(geometry.vertexBuffer); geometry.normalBuffer && gl.deleteBuffer(geometry.normalBuffer); geometry.lineNormalBuffer && gl.deleteBuffer(geometry.lineNormalBuffer); geometry.uvBuffer && gl.deleteBuffer(geometry.uvBuffer); geometry.indexBuffer && gl.deleteBuffer(geometry.indexBuffer); geometry.lineVertexBuffer && gl.deleteBuffer(geometry.lineVertexBuffer); }; /** * createBuffers description * @private * @param {String} gId key of the geometry object * @param {p5.Geometry} obj contains geometry data */ p5.RendererGL.prototype.createBuffers = function(gId, obj) { var gl = this.GL; this._setDefaultCamera(); //initialize the gl buffers for our geom groups this._initBufferDefaults(gId); var geometry = this.gHash[gId]; geometry.numberOfItems = obj.faces.length * 3; geometry.lineVertexCount = obj.lineVertices.length; this._useColorShader(); // initialize the stroke shader's 'aPosition' buffer, if used if (this.curStrokeShader.attributes.aPosition) { geometry.lineVertexBuffer = gl.createBuffer(); this._bindBuffer( geometry.lineVertexBuffer, gl.ARRAY_BUFFER, this._flatten(obj.lineVertices), Float32Array, gl.STATIC_DRAW ); this.curStrokeShader.enableAttrib( this.curStrokeShader.attributes.aPosition.location, 3, gl.FLOAT, false, 0, 0 ); } // initialize the stroke shader's 'aDirection' buffer, if used if (this.curStrokeShader.attributes.aDirection) { geometry.lineNormalBuffer = gl.createBuffer(); this._bindBuffer( geometry.lineNormalBuffer, gl.ARRAY_BUFFER, this._flatten(obj.lineNormals), Float32Array, gl.STATIC_DRAW ); this.curStrokeShader.enableAttrib( this.curStrokeShader.attributes.aDirection.location, 4, gl.FLOAT, false, 0, 0 ); } // initialize the fill shader's 'aPosition' buffer, if used if (this.curFillShader.attributes.aPosition) { geometry.vertexBuffer = gl.createBuffer(); // allocate space for vertex positions this._bindBuffer( geometry.vertexBuffer, gl.ARRAY_BUFFER, this._vToNArray(obj.vertices), Float32Array, gl.STATIC_DRAW ); this.curFillShader.enableAttrib( this.curFillShader.attributes.aPosition.location, 3, gl.FLOAT, false, 0, 0 ); } // allocate space for faces geometry.indexBuffer = gl.createBuffer(); this._bindBuffer( geometry.indexBuffer, gl.ELEMENT_ARRAY_BUFFER, this._flatten(obj.faces), Uint16Array, gl.STATIC_DRAW ); // initialize the fill shader's 'aNormal' buffer, if used if (this.curFillShader.attributes.aNormal) { geometry.normalBuffer = gl.createBuffer(); // allocate space for normals this._bindBuffer( geometry.normalBuffer, gl.ARRAY_BUFFER, this._vToNArray(obj.vertexNormals), Float32Array, gl.STATIC_DRAW ); this.curFillShader.enableAttrib( this.curFillShader.attributes.aNormal.location, 3, gl.FLOAT, false, 0, 0 ); } // initialize the fill shader's 'aTexCoord' buffer, if used if (this.curFillShader.attributes.aTexCoord) { geometry.uvBuffer = gl.createBuffer(); // tex coords this._bindBuffer( geometry.uvBuffer, gl.ARRAY_BUFFER, this._flatten(obj.uvs), Float32Array, gl.STATIC_DRAW ); this.curFillShader.enableAttrib( this.curFillShader.attributes.aTexCoord.location, 2, gl.FLOAT, false, 0, 0 ); } //} }; /** * Draws buffers given a geometry key ID * @private * @param {String} gId ID in our geom hash * @chainable */ p5.RendererGL.prototype.drawBuffers = function(gId) { this._setDefaultCamera(); var gl = this.GL; this._useColorShader(); var geometry = this.gHash[gId]; if (this._doStroke && geometry.lineVertexCount > 0) { this.curStrokeShader.bindShader(); // bind the stroke shader's 'aPosition' buffer if (geometry.lineVertexBuffer) { this._bindBuffer(geometry.lineVertexBuffer, gl.ARRAY_BUFFER); this.curStrokeShader.enableAttrib( this.curStrokeShader.attributes.aPosition.location, 3, gl.FLOAT, false, 0, 0 ); } // bind the stroke shader's 'aDirection' buffer if (geometry.lineNormalBuffer) { this._bindBuffer(geometry.lineNormalBuffer, gl.ARRAY_BUFFER); this.curStrokeShader.enableAttrib( this.curStrokeShader.attributes.aDirection.location, 4, gl.FLOAT, false, 0, 0 ); } this._applyColorBlend(this.curStrokeColor); this._drawArrays(gl.TRIANGLES, gId); this.curStrokeShader.unbindShader(); } if (this._doFill !== false) { this.curFillShader.bindShader(); // bind the fill shader's 'aPosition' buffer if (geometry.vertexBuffer) { //vertex position buffer this._bindBuffer(geometry.vertexBuffer, gl.ARRAY_BUFFER); this.curFillShader.enableAttrib( this.curFillShader.attributes.aPosition.location, 3, gl.FLOAT, false, 0, 0 ); } if (geometry.indexBuffer) { //vertex index buffer this._bindBuffer(geometry.indexBuffer, gl.ELEMENT_ARRAY_BUFFER); } // bind the fill shader's 'aNormal' buffer if (geometry.normalBuffer) { this._bindBuffer(geometry.normalBuffer, gl.ARRAY_BUFFER); this.curFillShader.enableAttrib( this.curFillShader.attributes.aNormal.location, 3, gl.FLOAT, false, 0, 0 ); } // bind the fill shader's 'aTexCoord' buffer if (geometry.uvBuffer) { // uv buffer this._bindBuffer(geometry.uvBuffer, gl.ARRAY_BUFFER); this.curFillShader.enableAttrib( this.curFillShader.attributes.aTexCoord.location, 2, gl.FLOAT, false, 0, 0 ); } this._applyColorBlend(this.curFillColor); this._drawElements(gl.TRIANGLES, gId); this.curFillShader.unbindShader(); } return this; }; /** * Calls drawBuffers() with a scaled model/view matrix. * * This is used by various 3d primitive methods (in primitives.js, eg. plane, * box, torus, etc...) to allow caching of un-scaled geometries. Those * geometries are generally created with unit-length dimensions, cached as * such, and then scaled appropriately in this method prior to rendering. * * @private * @method drawBuffersScaled * @param {String} gId ID in our geom hash * @param {Number} scaleX the amount to scale in the X direction * @param {Number} scaleY the amount to scale in the Y direction * @param {Number} scaleZ the amount to scale in the Z direction */ p5.RendererGL.prototype.drawBuffersScaled = function( gId, scaleX, scaleY, scaleZ ) { var uMVMatrix = this.uMVMatrix.copy(); try { this.uMVMatrix.scale(scaleX, scaleY, scaleZ); this.drawBuffers(gId); } finally { this.uMVMatrix = uMVMatrix; } }; p5.RendererGL.prototype._drawArrays = function(drawMode, gId) { this.GL.drawArrays(drawMode, 0, this.gHash[gId].lineVertexCount); return this; }; p5.RendererGL.prototype._drawElements = function(drawMode, gId) { this.GL.drawElements( drawMode, this.gHash[gId].numberOfItems, this.GL.UNSIGNED_SHORT, 0 ); }; module.exports = p5.RendererGL; },{"../core/core":22}],72:[function(_dereq_,module,exports){ 'use strict'; var p5 = _dereq_('../core/core'); var constants = _dereq_('../core/constants'); _dereq_('./p5.Shader'); _dereq_('../core/p5.Renderer'); _dereq_('./p5.Matrix'); var defaultShaders = { immediateVert: "attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uResolution;\nuniform float uPointSize;\n\nvarying vec4 vColor;\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n gl_PointSize = uPointSize;\n}\n", vertexColorVert: "attribute vec3 aPosition;\nattribute vec4 aVertexColor;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\n\nvarying vec4 vColor;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vColor = aVertexColor;\n}\n", vertexColorFrag: "precision mediump float;\nvarying vec4 vColor;\nvoid main(void) {\n gl_FragColor = vColor;\n}", normalVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\n\nvarying vec3 vVertexNormal;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n vVertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertTexCoord = aTexCoord;\n}\n", normalFrag: "precision mediump float;\nvarying vec3 vVertexNormal;\nvoid main(void) {\n gl_FragColor = vec4(vVertexNormal, 1.0);\n}", basicFrag: "precision mediump float;\nvarying vec3 vVertexNormal;\nuniform vec4 uMaterialColor;\nvoid main(void) {\n gl_FragColor = uMaterialColor;\n}", lightVert: "attribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform mat4 uViewMatrix;\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nuniform vec3 uAmbientColor[8];\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nvarying vec3 vVertexNormal;\nvarying vec2 vVertTexCoord;\nvarying vec3 vLightWeighting;\n\nvoid main(void){\n\n vec4 positionVec4 = vec4(aPosition, 1.0);\n gl_Position = uProjectionMatrix * uModelViewMatrix * positionVec4;\n\n vec3 vertexNormal = normalize(vec3( uNormalMatrix * aNormal ));\n vVertexNormal = vertexNormal;\n vVertTexCoord = aTexCoord;\n\n vec4 mvPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n vec3 eyeDirection = normalize(-mvPosition.xyz);\n\n float shininess = 32.0;\n float specularFactor = 2.0;\n float diffuseFactor = 0.3;\n\n vec3 ambientLightFactor = vec3(0.0);\n\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n ambientLightFactor += uAmbientColor[i];\n }\n\n\n vec3 directionalLightFactor = vec3(0.0);\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n vec3 dir = uLightingDirection[j];\n float directionalLightWeighting = max(dot(vertexNormal, -dir), 0.0);\n directionalLightFactor += uDirectionalColor[j] * directionalLightWeighting;\n }\n\n\n vec3 pointLightFactor = vec3(0.0);\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n vec3 loc = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightDirection = normalize(loc - mvPosition.xyz);\n\n float directionalLightWeighting = max(dot(vertexNormal, lightDirection), 0.0);\n\n float specularLightWeighting = 0.0;\n if (uSpecular ){\n vec3 reflectionDirection = reflect(-lightDirection, vertexNormal);\n specularLightWeighting = pow(max(dot(reflectionDirection, eyeDirection), 0.0), shininess);\n }\n\n pointLightFactor += uPointLightColor[k] * (specularFactor * specularLightWeighting\n + directionalLightWeighting * diffuseFactor);\n }\n\n vLightWeighting = ambientLightFactor + directionalLightFactor + pointLightFactor;\n}\n", lightTextureFrag: "precision mediump float;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nvarying vec3 vLightWeighting;\nvarying highp vec2 vVertTexCoord;\n\nvoid main(void) {\n gl_FragColor = isTexture ? texture2D(uSampler, vVertTexCoord) : uMaterialColor;\n if (uUseLighting)\n gl_FragColor.rgb *= vLightWeighting;\n}", phongVert: "precision mediump float;\n\nattribute vec3 aPosition;\nattribute vec3 aNormal;\nattribute vec2 aTexCoord;\n\nuniform vec3 uAmbientColor[8];\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform mat3 uNormalMatrix;\nuniform int uAmbientLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvoid main(void){\n\n vec4 viewModelPosition = uModelViewMatrix * vec4(aPosition, 1.0);\n\n // Pass varyings to fragment shader\n vViewPosition = viewModelPosition.xyz;\n gl_Position = uProjectionMatrix * viewModelPosition; \n\n vNormal = normalize(uNormalMatrix * normalize(aNormal));\n vTexCoord = aTexCoord;\n\n vAmbientColor = vec3(0.0);\n for (int i = 0; i < 8; i++) {\n if (uAmbientLightCount == i) break;\n vAmbientColor += uAmbientColor[i];\n }\n}\n", phongFrag: "precision mediump float;\n\n//uniform mat4 uModelViewMatrix;\nuniform mat4 uViewMatrix;\n\nuniform vec4 uMaterialColor;\nuniform sampler2D uSampler;\nuniform bool isTexture;\nuniform bool uUseLighting;\n\nuniform vec3 uLightingDirection[8];\nuniform vec3 uDirectionalColor[8];\nuniform vec3 uPointLightLocation[8];\nuniform vec3 uPointLightColor[8];\nuniform bool uSpecular;\n\nuniform int uDirectionalLightCount;\nuniform int uPointLightCount;\n\nvarying vec3 vNormal;\nvarying vec2 vTexCoord;\nvarying vec3 vViewPosition;\nvarying vec3 vAmbientColor;\n\nvec3 V;\nvec3 N;\n\nconst float shininess = 32.0;\nconst float specularFactor = 2.0;\nconst float diffuseFactor = 0.73;\n\nstruct LightResult {\n\tfloat specular;\n\tfloat diffuse;\n};\n\nfloat phongSpecular(\n vec3 lightDirection,\n vec3 viewDirection,\n vec3 surfaceNormal,\n float shininess) {\n\n vec3 R = normalize(reflect(-lightDirection, surfaceNormal)); \n return pow(max(0.0, dot(R, viewDirection)), shininess);\n}\n\nfloat lambertDiffuse(\n vec3 lightDirection,\n vec3 surfaceNormal) {\n return max(0.0, dot(-lightDirection, surfaceNormal));\n}\n\nLightResult light(vec3 lightVector) {\n\n vec3 L = normalize(lightVector);\n\n //compute our diffuse & specular terms\n LightResult lr;\n if (uSpecular)\n lr.specular = phongSpecular(L, V, N, shininess);\n lr.diffuse = lambertDiffuse(L, N);\n return lr;\n}\n\nvoid main(void) {\n\n V = normalize(vViewPosition);\n N = vNormal;\n\n vec3 diffuse = vec3(0.0);\n float specular = 0.0;\n\n for (int j = 0; j < 8; j++) {\n if (uDirectionalLightCount == j) break;\n\n LightResult result = light(uLightingDirection[j]);\n diffuse += result.diffuse * uDirectionalColor[j];\n specular += result.specular;\n }\n\n for (int k = 0; k < 8; k++) {\n if (uPointLightCount == k) break;\n\n vec3 lightPosition = (uViewMatrix * vec4(uPointLightLocation[k], 1.0)).xyz;\n vec3 lightVector = vViewPosition - lightPosition;\n\t\n //calculate attenuation\n float lightDistance = length(lightVector);\n float falloff = 500.0 / (lightDistance + 500.0);\n\n LightResult result = light(lightVector);\n diffuse += result.diffuse * falloff * uPointLightColor[k];\n specular += result.specular * falloff;\n }\n\n gl_FragColor = isTexture ? texture2D(uSampler, vTexCoord) : uMaterialColor;\n gl_FragColor.rgb = gl_FragColor.rgb * (diffuse * diffuseFactor + vAmbientColor) + specular * specularFactor;\n}", lineVert: "/*\n Part of the Processing project - http://processing.org\n Copyright (c) 2012-15 The Processing Foundation\n Copyright (c) 2004-12 Ben Fry and Casey Reas\n Copyright (c) 2001-04 Massachusetts Institute of Technology\n This library is free software; you can redistribute it and/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation, version 2.1.\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n You should have received a copy of the GNU Lesser General\n Public License along with this library; if not, write to the\n Free Software Foundation, Inc., 59 Temple Place, Suite 330,\n Boston, MA 02111-1307 USA\n*/\n\n#define PROCESSING_LINE_SHADER\n\nuniform mat4 uModelViewMatrix;\nuniform mat4 uProjectionMatrix;\nuniform float uStrokeWeight;\n\nuniform vec4 uViewport;\nvec3 scale = vec3(1.0);\n\nattribute vec4 aPosition;\nattribute vec4 aDirection;\n \nvoid main() {\n vec4 posp = uModelViewMatrix * aPosition;\n vec4 posq = uModelViewMatrix * (aPosition + vec4(aDirection.xyz, 0));\n\n // Moving vertices slightly toward the camera\n // to avoid depth-fighting with the fill triangles.\n // Discussed here:\n // http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=252848 \n posp.xyz = posp.xyz * scale;\n posq.xyz = posq.xyz * scale;\n\n vec4 p = uProjectionMatrix * posp;\n vec4 q = uProjectionMatrix * posq;\n\n // formula to convert from clip space (range -1..1) to screen space (range 0..[width or height])\n // screen_p = (p.xy/p.w + <1,1>) * 0.5 * uViewport.zw\n\n // prevent division by W by transforming the tangent formula (div by 0 causes\n // the line to disappear, see https://github.com/processing/processing/issues/5183)\n // t = screen_q - screen_p\n //\n // tangent is normalized and we don't care which aDirection it points to (+-)\n // t = +- normalize( screen_q - screen_p )\n // t = +- normalize( (q.xy/q.w+<1,1>)*0.5*uViewport.zw - (p.xy/p.w+<1,1>)*0.5*uViewport.zw )\n //\n // extract common factor, <1,1> - <1,1> cancels out\n // t = +- normalize( (q.xy/q.w - p.xy/p.w) * 0.5 * uViewport.zw )\n //\n // convert to common divisor\n // t = +- normalize( ((q.xy*p.w - p.xy*q.w) / (p.w*q.w)) * 0.5 * uViewport.zw )\n //\n // remove the common scalar divisor/factor, not needed due to normalize and +-\n // (keep uViewport - can't remove because it has different components for x and y\n // and corrects for aspect ratio, see https://github.com/processing/processing/issues/5181)\n // t = +- normalize( (q.xy*p.w - p.xy*q.w) * uViewport.zw )\n\n vec2 tangent = normalize((q.xy*p.w - p.xy*q.w) * uViewport.zw);\n\n // flip tangent to normal (it's already normalized)\n vec2 normal = vec2(-tangent.y, tangent.x);\n\n float thickness = aDirection.w * uStrokeWeight;\n vec2 offset = normal * thickness / 2.0;\n\n // Perspective ---\n // convert from world to clip by multiplying with projection scaling factor\n // to get the right thickness (see https://github.com/processing/processing/issues/5182)\n // invert Y, projections in Processing invert Y\n vec2 perspScale = (uProjectionMatrix * vec4(1, -1, 0, 0)).xy;\n\n // No Perspective ---\n // multiply by W (to cancel out division by W later in the pipeline) and\n // convert from screen to clip (derived from clip to screen above)\n vec2 noPerspScale = p.w / (0.5 * uViewport.zw);\n\n //gl_Position.xy = p.xy + offset.xy * mix(noPerspScale, perspScale, float(perspective > 0));\n gl_Position.xy = p.xy + offset.xy * perspScale;\n gl_Position.zw = p.zw;\n}\n", lineFrag: "precision mediump float;\nprecision mediump int;\n\nuniform vec4 uMaterialColor;\n\nvoid main() {\n gl_FragColor = uMaterialColor;\n}" }; /** * 3D graphics class * @private * @class p5.RendererGL * @constructor * @extends p5.Renderer * @todo extend class to include public method for offscreen * rendering (FBO). * */ p5.RendererGL = function(elt, pInst, isMainCanvas, attr) { p5.Renderer.call(this, elt, pInst, isMainCanvas); this.attributes = {}; attr = attr || {}; this.attributes.alpha = attr.alpha === undefined ? true : attr.alpha; this.attributes.depth = attr.depth === undefined ? true : attr.depth; this.attributes.stencil = attr.stencil === undefined ? true : attr.stencil; this.attributes.antialias = attr.antialias === undefined ? false : attr.antialias; this.attributes.premultipliedAlpha = attr.premultipliedAlpha === undefined ? false : attr.premultipliedAlpha; this.attributes.preserveDrawingBuffer = attr.preserveDrawingBuffer === undefined ? true : attr.preserveDrawingBuffer; this.attributes.perPixelLighting = attr.perPixelLighting === undefined ? false : attr.perPixelLighting; this._initContext(); this.isP3D = true; //lets us know we're in 3d mode this.GL = this.drawingContext; // lights this.ambientLightColors = []; this.directionalLightDirections = []; this.directionalLightColors = []; this.pointLightPositions = []; this.pointLightColors = []; /** * model view, projection, & normal * matrices */ this.uMVMatrix = new p5.Matrix(); this.uPMatrix = new p5.Matrix(); this.uNMatrix = new p5.Matrix('mat3'); // Camera this._curCamera = null; // default camera settings, then use those to populate camera fields. this._computeCameraDefaultSettings(); this.cameraFOV = this.defaultCameraFOV; this.cameraAspect = this.defaultAspect; this.cameraX = this.defaultCameraX; this.cameraY = this.defaultCameraY; this.cameraZ = this.defaultCameraZ; this.cameraNear = this.defaultCameraNear; this.cameraFar = this.defaultCameraFar; this.cameraMatrix = new p5.Matrix(); this.camera(); // set default camera matrices //Geometry & Material hashes this.gHash = {}; this._defaultLightShader = undefined; this._defaultImmediateModeShader = undefined; this._defaultNormalShader = undefined; this._defaultColorShader = undefined; this.curFillShader = undefined; this.curStrokeShader = undefined; this._useColorShader(); this.setStrokeShader(this._getLineShader()); //Imediate Mode //default drawing is done in Retained Mode this.isImmediateDrawing = false; this.immediateMode = {}; // note: must call fill() and stroke () AFTER // default shader has been set. this.fill(255, 255, 255, 255); //this.stroke(0, 0, 0, 255); this.pointSize = 5.0; //default point size this.strokeWeight(2); this.stroke(0, 0, 0); // array of textures created in this gl context via this.getTexture(src) this.textures = []; return this; }; p5.RendererGL.prototype = Object.create(p5.Renderer.prototype); ////////////////////////////////////////////// // Setting ////////////////////////////////////////////// p5.RendererGL.prototype._initContext = function() { try { this.drawingContext = this.canvas.getContext('webgl', this.attributes) || this.canvas.getContext('experimental-webgl', this.attributes); if (this.drawingContext === null) { throw new Error('Error creating webgl context'); } else { console.log('p5.RendererGL: enabled webgl context'); var gl = this.drawingContext; gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); this._viewport = this.drawingContext.getParameter( this.drawingContext.VIEWPORT ); } } catch (er) { throw new Error(er); } }; //This is helper function to reset the context anytime the attributes //are changed with setAttributes() p5.RendererGL.prototype._resetContext = function(attr, options, callback) { var w = this.width; var h = this.height; var defaultId = this.canvas.id; var c = this.canvas; if (c) { c.parentNode.removeChild(c); } c = document.createElement('canvas'); c.id = defaultId; if (this._pInst._userNode) { this._pInst._userNode.appendChild(c); } else { document.body.appendChild(c); } this._pInst.canvas = c; var renderer = new p5.RendererGL(this._pInst.canvas, this._pInst, true, attr); this._pInst._setProperty('_renderer', renderer); renderer.resize(w, h); renderer._applyDefaults(); this._pInst._elements.push(renderer); if (typeof callback === 'function') { //setTimeout with 0 forces the task to the back of the queue, this ensures that //we finish switching out the renderer setTimeout(function() { callback.apply(window._renderer, options); }, 0); } }; /** * @module Rendering * @submodule Rendering * @for p5 */ /** * Set attributes for the WebGL Drawing context. * This is a way of adjusting ways that the WebGL * renderer works to fine-tune the display and performance. * This should be put in setup(). * The available attributes are: *
* alpha - indicates if the canvas contains an alpha buffer * default is true *

* depth - indicates whether the drawing buffer has a depth buffer * of at least 16 bits - default is true *

* stencil - indicates whether the drawing buffer has a stencil buffer * of at least 8 bits *

* antialias - indicates whether or not to perform anti-aliasing * default is false *

* premultipliedAlpha - indicates that the page compositor will assume * the drawing buffer contains colors with pre-multiplied alpha * default is false *

* preserveDrawingBuffer - if true the buffers will not be cleared and * and will preserve their values until cleared or overwritten by author * (note that p5 clears automatically on draw loop) * default is true *

* perPixelLighting - if true, per-pixel lighting will be used in the * lighting shader. * default is false *

* @method setAttributes * @for p5 * @param {String} key Name of attribute * @param {Boolean} value New value of named attribute * @example *
* * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(255); * push(); * rotateZ(frameCount * 0.02); * rotateX(frameCount * 0.02); * rotateY(frameCount * 0.02); * fill(0, 0, 0); * box(50); * pop(); * } * *
*
* Now with the antialias attribute set to true. *
*
* * function setup() { * createCanvas(100, 100, WEBGL); * setAttributes('antialias', true); * } * * function draw() { * background(255); * push(); * rotateZ(frameCount * 0.02); * rotateX(frameCount * 0.02); * rotateY(frameCount * 0.02); * fill(0, 0, 0); * box(50); * pop(); * } * *
* *
* * // press the mouse button to enable perPixelLighting * function setup() { * createCanvas(100, 100, WEBGL); * noStroke(); * fill(255); * } * * var lights = [ * { c: '#f00', t: 1.12, p: 1.91, r: 0.2 }, * { c: '#0f0', t: 1.21, p: 1.31, r: 0.2 }, * { c: '#00f', t: 1.37, p: 1.57, r: 0.2 }, * { c: '#ff0', t: 1.12, p: 1.91, r: 0.7 }, * { c: '#0ff', t: 1.21, p: 1.31, r: 0.7 }, * { c: '#f0f', t: 1.37, p: 1.57, r: 0.7 } * ]; * * function draw() { * var t = millis() / 1000 + 1000; * background(0); * directionalLight(color('#222'), 1, 1, 1); * * for (var i = 0; i < lights.length; i++) { * var light = lights[i]; * pointLight( * color(light.c), * p5.Vector.fromAngles(t * light.t, t * light.p, width * light.r) * ); * } * * specularMaterial(255); * sphere(width * 0.1); * * rotateX(t * 0.77); * rotateY(t * 0.83); * rotateZ(t * 0.91); * torus(width * 0.3, width * 0.07, 30, 10); * } * * function mousePressed() { * setAttributes('perPixelLighting', true); * noStroke(); * fill(255); * } * function mouseReleased() { * setAttributes('perPixelLighting', false); * noStroke(); * fill(255); * } * *
* * @alt a rotating cube with smoother edges */ /** * @method setAttributes * @for p5 * @param {Object} obj object with key-value pairs */ p5.prototype.setAttributes = function(key, value) { this._assert3d('setAttributes'); //@todo_FES var attr; if (typeof value !== 'undefined') { attr = {}; attr[key] = value; } else if (key instanceof Object) { attr = key; } this.push(); this._renderer._resetContext(attr); this.pop(); }; /** * @class p5.RendererGL */ p5.RendererGL.prototype._computeCameraDefaultSettings = function() { this.defaultCameraFOV = 60 / 180 * Math.PI; this.defaultCameraAspect = this.width / this.height; this.defaultCameraX = 0; this.defaultCameraY = 0; this.defaultCameraZ = this.height / 2.0 / Math.tan(this.defaultCameraFOV / 2.0); this.defaultCameraNear = this.defaultCameraZ * 0.1; this.defaultCameraFar = this.defaultCameraZ * 10; }; //detect if user didn't set the camera //then call this function below p5.RendererGL.prototype._setDefaultCamera = function() { if (this._curCamera === null) { this._computeCameraDefaultSettings(); this.cameraFOV = this.defaultCameraFOV; this.cameraAspect = this.defaultAspect; this.cameraX = this.defaultCameraX; this.cameraY = this.defaultCameraY; this.cameraZ = this.defaultCameraZ; this.cameraNear = this.defaultCameraNear; this.cameraFar = this.defaultCameraFar; this.perspective(); this.camera(); this._curCamera = 'default'; } }; p5.RendererGL.prototype._update = function() { // reset model view and apply initial camera transform // (containing only look at info; no projection). this.uMVMatrix.set( this.cameraMatrix.mat4[0], this.cameraMatrix.mat4[1], this.cameraMatrix.mat4[2], this.cameraMatrix.mat4[3], this.cameraMatrix.mat4[4], this.cameraMatrix.mat4[5], this.cameraMatrix.mat4[6], this.cameraMatrix.mat4[7], this.cameraMatrix.mat4[8], this.cameraMatrix.mat4[9], this.cameraMatrix.mat4[10], this.cameraMatrix.mat4[11], this.cameraMatrix.mat4[12], this.cameraMatrix.mat4[13], this.cameraMatrix.mat4[14], this.cameraMatrix.mat4[15] ); // reset light data for new frame. this.ambientLightColors.length = 0; this.directionalLightDirections.length = 0; this.directionalLightColors.length = 0; this.pointLightPositions.length = 0; this.pointLightColors.length = 0; }; /** * [background description] */ p5.RendererGL.prototype.background = function() { var _col = this._pInst.color.apply(this._pInst, arguments); var _r = _col.levels[0] / 255; var _g = _col.levels[1] / 255; var _b = _col.levels[2] / 255; var _a = _col.levels[3] / 255; this.GL.clearColor(_r, _g, _b, _a); this.GL.depthMask(true); this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); }; //@TODO implement this // p5.RendererGL.prototype.clear = function() { //@TODO // }; ////////////////////////////////////////////// // COLOR ////////////////////////////////////////////// /** * Basic fill material for geometry with a given color * @method fill * @class p5.RendererGL * @param {Number|Number[]|String|p5.Color} v1 gray value, * red or hue value (depending on the current color mode), * or color Array, or CSS color string * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @chainable * @example *
* * function setup() { * createCanvas(200, 200, WEBGL); * } * * function draw() { * background(0); * noStroke(); * fill(100, 100, 240); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(75, 75, 75); * } * *
* * @alt * black canvas with purple cube spinning * */ p5.RendererGL.prototype.fill = function(v1, v2, v3, a) { //see material.js for more info on color blending in webgl var color = p5.prototype.color.apply(this._pInst, arguments); this.curFillColor = color._array; if (this.isImmediateDrawing) { this.setFillShader(this._getImmediateModeShader()); } else { this.setFillShader(this._getColorShader()); } this.drawMode = constants.FILL; this.curFillShader.setUniform('uMaterialColor', this.curFillColor); }; /** * Basic stroke material for geometry with a given color * @method stroke * @param {Number|Number[]|String|p5.Color} v1 gray value, * red or hue value (depending on the current color mode), * or color Array, or CSS color string * @param {Number} [v2] green or saturation value * @param {Number} [v3] blue or brightness value * @param {Number} [a] opacity * @example *
* * function setup() { * createCanvas(200, 200, WEBGL); * } * * function draw() { * background(0); * stroke(240, 150, 150); * fill(100, 100, 240); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(75, 75, 75); * } * *
* * @alt * black canvas with purple cube with pink outline spinning * */ p5.RendererGL.prototype.stroke = function(r, g, b, a) { //@todo allow transparency in stroking currently doesn't have //any impact and causes problems with specularMaterial arguments[3] = 255; var color = p5.prototype.color.apply(this._pInst, arguments); this.curStrokeColor = color._array; this.curStrokeShader.setUniform('uMaterialColor', this.curStrokeColor); }; /** * Change weight of stroke * @method strokeWeight * @param {Number} stroke weight to be used for drawing * @example *
* * function setup() { * createCanvas(200, 400, WEBGL); * setAttributes('antialias', true); * } * * function draw() { * background(0); * noStroke(); * translate(0, -100, 0); * stroke(240, 150, 150); * fill(100, 100, 240); * push(); * strokeWeight(8); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * sphere(75); * pop(); * push(); * translate(0, 200, 0); * strokeWeight(1); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * sphere(75); * pop(); * } * *
* * @alt * black canvas with two purple rotating spheres with pink * outlines the sphere on top has much heavier outlines, * */ p5.RendererGL.prototype.strokeWeight = function(w) { if (this.curStrokeWeight !== w) { this.pointSize = w; this.curStrokeWeight = w; this.curStrokeShader.setUniform('uStrokeWeight', w); } }; /** * Returns an array of [R,G,B,A] values for any pixel or grabs a section of * an image. If no parameters are specified, the entire image is returned. * Use the x and y parameters to get the value of one pixel. Get a section of * the display window by specifying additional w and h parameters. When * getting an image, the x and y parameters define the coordinates for the * upper-left corner of the image, regardless of the current imageMode(). *

* If the pixel requested is outside of the image window, [0,0,0,255] is * returned. *

* Getting the color of a single pixel with get(x, y) is easy, but not as fast * as grabbing the data directly from pixels[]. The equivalent statement to * get(x, y) is using pixels[] with pixel density d * * @private * @method get * @param {Number} [x] x-coordinate of the pixel * @param {Number} [y] y-coordinate of the pixel * @param {Number} [w] width * @param {Number} [h] height * @return {Number[]|Color|p5.Image} color of pixel at x,y in array format * [R, G, B, A] or p5.Image */ p5.RendererGL.prototype.get = function(x, y, w, h) { return p5.Renderer2D.prototype.get.apply(this, [x, y, w, h]); }; /** * Loads the pixels data for this canvas into the pixels[] attribute. * Note that updatePixels() and set() do not work. * Any pixel manipulation must be done directly to the pixels[] array. * * @private * @method loadPixels * */ p5.RendererGL.prototype.loadPixels = function() { //@todo_FES if (this.attributes.preserveDrawingBuffer !== true) { console.log( 'loadPixels only works in WebGL when preserveDrawingBuffer ' + 'is true.' ); return; } var pd = this._pInst._pixelDensity; var x = 0; var y = 0; var w = this.width; var h = this.height; w *= pd; h *= pd; //if there isn't a renderer-level temporary pixels buffer //make a new one if (typeof this.pixels === 'undefined') { this.pixels = new Uint8Array( this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4 ); } this.GL.readPixels( x, y, w, h, this.GL.RGBA, this.GL.UNSIGNED_BYTE, this.pixels ); this._pInst._setProperty('pixels', this.pixels); }; ////////////////////////////////////////////// // HASH | for geometry ////////////////////////////////////////////// p5.RendererGL.prototype.geometryInHash = function(gId) { return this.gHash[gId] !== undefined; }; /** * [resize description] * @private * @param {Number} w [description] * @param {Number} h [description] */ p5.RendererGL.prototype.resize = function(w, h) { p5.Renderer.prototype.resize.call(this, w, h); this.GL.viewport( 0, 0, this.GL.drawingBufferWidth, this.GL.drawingBufferHeight ); this._viewport = this.GL.getParameter(this.GL.VIEWPORT); // If we're using the default camera, update the aspect ratio if (this._curCamera === null || this._curCamera === 'default') { this._curCamera = null; // camera defaults are dependent on the width & height of the screen, // so we'll want to update them if the size of the screen changes. this._setDefaultCamera(); } //resize pixels buffer if (typeof this.pixels !== 'undefined') { this.pixels = new Uint8Array( this.GL.drawingBufferWidth * this.GL.drawingBufferHeight * 4 ); } }; /** * clears color and depth buffers * with r,g,b,a * @private * @param {Number} r normalized red val. * @param {Number} g normalized green val. * @param {Number} b normalized blue val. * @param {Number} a normalized alpha val. */ p5.RendererGL.prototype.clear = function() { var _r = arguments[0] || 0; var _g = arguments[1] || 0; var _b = arguments[2] || 0; var _a = arguments[3] || 0; this.GL.clearColor(_r, _g, _b, _a); this.GL.clear(this.GL.COLOR_BUFFER_BIT | this.GL.DEPTH_BUFFER_BIT); }; /** * [translate description] * @private * @param {Number} x [description] * @param {Number} y [description] * @param {Number} z [description] * @chainable * @todo implement handle for components or vector as args */ p5.RendererGL.prototype.translate = function(x, y, z) { if (x instanceof p5.Vector) { z = x.z; y = x.y; x = x.x; } this.uMVMatrix.translate([x, y, z]); return this; }; /** * Scales the Model View Matrix by a vector * @private * @param {Number | p5.Vector | Array} x [description] * @param {Number} [y] y-axis scalar * @param {Number} [z] z-axis scalar * @chainable */ p5.RendererGL.prototype.scale = function(x, y, z) { this.uMVMatrix.scale(x, y, z); return this; }; p5.RendererGL.prototype.rotate = function(rad, axis) { if (typeof axis === 'undefined') { return this.rotateZ(rad); } p5.Matrix.prototype.rotate.apply(this.uMVMatrix, arguments); return this; }; p5.RendererGL.prototype.rotateX = function(rad) { this.rotate(rad, 1, 0, 0); return this; }; p5.RendererGL.prototype.rotateY = function(rad) { this.rotate(rad, 0, 1, 0); return this; }; p5.RendererGL.prototype.rotateZ = function(rad) { this.rotate(rad, 0, 0, 1); return this; }; p5.RendererGL.prototype.push = function() { // get the base renderer style var style = p5.Renderer.prototype.push.apply(this); // add webgl-specific style properties var properties = style.properties; properties.uMVMatrix = this.uMVMatrix.copy(); properties.cameraMatrix = this.cameraMatrix.copy(); return style; }; p5.RendererGL.prototype.resetMatrix = function() { this.uMVMatrix = p5.Matrix.identity(this._pInst); return this; }; // Text/Typography // @TODO: p5.RendererGL.prototype._applyTextProperties = function() { //@TODO finish implementation console.error('text commands not yet implemented in webgl'); }; ////////////////////////////////////////////// // SHADER ////////////////////////////////////////////// /* * Initializes and uses the specified shader, then returns * that shader. Note: initialization and resetting the program * is only used if needed (say, if a new value is provided) * so it is safe to call this method with the same shader multiple * times without a signficant performance hit). * * @method setFillShader * @param {p5.Shader} [s] a p5.Shader object * @return {p5.Shader} the current, updated fill shader */ p5.RendererGL.prototype.setFillShader = function(s) { if (this.curFillShader !== s) { // only do setup etc. if shader is actually new. this.curFillShader = s; // safe to do this multiple times; // init() will bail early if has already been run. this.curFillShader.init(); //this.curFillShader.useProgram(); } // always return this.curFillShader, even if no change was made. return this.curFillShader; }; /* * @method setStrokeShader * @param {p5.Shader} [s] a p5.Shader object * @return {p5.Shader} the current, updated stroke shader */ p5.RendererGL.prototype.setStrokeShader = function(s) { if (this.curStrokeShader !== s) { // only do setup etc. if shader is actually new. this.curStrokeShader = s; // safe to do this multiple times; // init() will bail early if has already been run. this.curStrokeShader.init(); //this.curStrokeShader.useProgram(); } // always return this.curLineShader, even if no change was made. return this.curStrokeShader; }; /* * shaders are created and cached on a per-renderer basis, * on the grounds that each renderer will have its own gl context * and the shader must be valid in that context. * * */ p5.RendererGL.prototype._useLightShader = function() { if (!this.curFillShader || !this.curFillShader.isLightShader()) { this.setFillShader(this._getLightShader()); } return this.curFillShader; }; p5.RendererGL.prototype._useColorShader = function() { // looking at the code within the glsl files, I'm not really // sure why these are two different shaders. but, they are, // and if we're drawing in retain mode but the shader is the // immediate mode one, we need to switch. // TODO: what if curFillShader is _any_ other shader? if ( !this.curFillShader || this.curFillShader === this._defaultImmediateModeShader ) { // there are different immediate mode and retain mode color shaders. // if we're using the immediate mode one, we need to switch to // one that works for retain mode. this.setFillShader(this._getColorShader()); } return this.curFillShader; }; p5.RendererGL.prototype._useImmediateModeShader = function() { // TODO: what if curFillShader is _any_ other shader? if (!this.curFillShader || this.curFillShader === this._defaultColorShader) { // this is the fill/stroke shader for retain mode. // must switch to immediate mode shader before drawing! this.setFillShader(this._getImmediateModeShader()); // note that if we're using the texture shader... // this shouldn't change. :) } return this.curFillShader; }; p5.RendererGL.prototype._getLightShader = function() { if (!this._defaultLightShader) { if (this.attributes.perPixelLighting) { this._defaultLightShader = new p5.Shader( this, defaultShaders.phongVert, defaultShaders.phongFrag ); } else { this._defaultLightShader = new p5.Shader( this, defaultShaders.lightVert, defaultShaders.lightTextureFrag ); } } //this.drawMode = constants.FILL; return this._defaultLightShader; }; p5.RendererGL.prototype._getImmediateModeShader = function() { if (!this._defaultImmediateModeShader) { this._defaultImmediateModeShader = new p5.Shader( this, defaultShaders.immediateVert, defaultShaders.vertexColorFrag ); } //this.drawMode = constants.FILL; return this._defaultImmediateModeShader; }; p5.RendererGL.prototype._getNormalShader = function() { if (!this._defaultNormalShader) { this._defaultNormalShader = new p5.Shader( this, defaultShaders.normalVert, defaultShaders.normalFrag ); } //this.drawMode = constants.FILL; return this._defaultNormalShader; }; p5.RendererGL.prototype._getColorShader = function() { if (!this._defaultColorShader) { this._defaultColorShader = new p5.Shader( this, defaultShaders.normalVert, defaultShaders.basicFrag ); } //this.drawMode = constants.FILL; return this._defaultColorShader; }; p5.RendererGL.prototype._getLineShader = function() { if (!this._defaultLineShader) { this._defaultLineShader = new p5.Shader( this, defaultShaders.lineVert, defaultShaders.lineFrag ); } //this.drawMode = constants.STROKE; return this._defaultLineShader; }; p5.RendererGL.prototype._getEmptyTexture = function() { if (!this._emptyTexture) { // a plain white texture RGBA, full alpha, single pixel. var im = new p5.Image(1, 1); im.set(0, 0, 255); this._emptyTexture = new p5.Texture(this, im); } return this._emptyTexture; }; p5.RendererGL.prototype.getTexture = function(img) { var checkSource = function(element) { return element.src === img; }; //this.drawMode = constants.TEXTURE; var tex = this.textures.find(checkSource); if (!tex) { tex = new p5.Texture(this, img); this.textures.push(tex); } return tex; }; //Binds a buffer to the drawing context //when passed more than two arguments it also updates or initializes //the data associated with the buffer p5.RendererGL.prototype._bindBuffer = function( buffer, target, values, type, usage ) { this.GL.bindBuffer(target, buffer); if (values !== undefined) { var data = new type(values); this.GL.bufferData(target, data, usage); } }; ////////////////////////// //// SMOOTHING ///////////////////////// // @TODO: p5.RendererGL.prototype.smooth = function() { //@TODO finish implementation console.log('smoothing not yet implemented in webgl'); }; p5.RendererGL.prototype.noSmooth = function() { //@TODO finish implementation console.log('smoothing not yet implemented in webgl'); }; /////////////////////////////// //// UTILITY FUNCTIONS ////////////////////////////// /** * turn a two dimensional array into one dimensional array * @private * @param {Array} arr 2-dimensional array * @return {Array} 1-dimensional array * [[1, 2, 3],[4, 5, 6]] -> [1, 2, 3, 4, 5, 6] */ p5.RendererGL.prototype._flatten = function(arr) { //when empty, return empty if (arr.length === 0) { return []; } else if (arr.length > 20000) { //big models , load slower to avoid stack overflow //faster non-recursive flatten via axelduch //stackoverflow.com/questions/27266550/how-to-flatten-nested-array-in-javascript var toString = Object.prototype.toString; var arrayTypeStr = '[object Array]'; var result = []; var nodes = arr.slice(); var node; node = nodes.pop(); do { if (toString.call(node) === arrayTypeStr) { nodes.push.apply(nodes, node); } else { result.push(node); } } while (nodes.length && (node = nodes.pop()) !== undefined); result.reverse(); // we reverse result to restore the original order return result; } else { //otherwise if model within limits for browser //use faster recursive loading return [].concat.apply([], arr); } }; /** * turn a p5.Vector Array into a one dimensional number array * @private * @param {p5.Vector[]} arr an array of p5.Vector * @return {Number[]} a one dimensional array of numbers * [p5.Vector(1, 2, 3), p5.Vector(4, 5, 6)] -> * [1, 2, 3, 4, 5, 6] */ p5.RendererGL.prototype._vToNArray = function(arr) { return this._flatten( arr.map(function(item) { return [item.x, item.y, item.z]; }) ); }; /** * ensures that p5 is using a 3d renderer. throws an error if not. */ p5.prototype._assert3d = function(name) { if (!this._renderer.isP3D) throw new Error( name + "() is only supported in WEBGL mode. If you'd like to use 3D graphics" + ' and WebGL, see https://p5js.org/examples/form-3d-primitives.html' + ' for more information.' ); }; module.exports = p5.RendererGL; },{"../core/constants":21,"../core/core":22,"../core/p5.Renderer":29,"./p5.Matrix":69,"./p5.Shader":73}],73:[function(_dereq_,module,exports){ /** * This module defines the p5.Shader class * @module Lights, Camera * @submodule Shaders * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Shader class for WEBGL Mode * @class p5.Shader * @param {p5.RendererGL} renderer an instance of p5.RendererGL that * will provide the GL context for this new p5.Shader * @param {String} vertSrc source code for the vertex shader (as a string) * @param {String} fragSrc source code for the fragment shader (as a string) */ p5.Shader = function(renderer, vertSrc, fragSrc) { // TODO: adapt this to not take ids, but rather, // to take the source for a vertex and fragment shader // to enable custom shaders at some later date this._renderer = renderer; this._vertSrc = vertSrc; this._fragSrc = fragSrc; this._vertShader = -1; this._fragShader = -1; this._glProgram = 0; this._loadedAttributes = false; this.attributes = {}; this._loadedUniforms = false; this.uniforms = {}; this._bound = false; this.samplers = []; return this; }; /** * Creates, compiles, and links the shader based on its * sources for the vertex and fragment shaders (provided * to the constructor). Populates known attributes and * uniforms from the shader. * @method init * @chainable * @private */ p5.Shader.prototype.init = function() { if (this._glProgram === 0 /* or context is stale? */) { var gl = this._renderer.GL; // @todo: once custom shading is allowed, // friendly error messages should be used here to share // compiler and linker errors. //set up the shader by // 1. creating and getting a gl id for the shader program, // 2. compliling its vertex & fragment sources, // 3. linking the vertex and fragment shaders this._vertShader = gl.createShader(gl.VERTEX_SHADER); //load in our default vertex shader gl.shaderSource(this._vertShader, this._vertSrc); gl.compileShader(this._vertShader); // if our vertex shader failed compilation? if (!gl.getShaderParameter(this._vertShader, gl.COMPILE_STATUS)) { console.error( 'Yikes! An error occurred compiling the vertex shader:' + gl.getShaderInfoLog(this._vertShader) ); return null; } this._fragShader = gl.createShader(gl.FRAGMENT_SHADER); //load in our material frag shader gl.shaderSource(this._fragShader, this._fragSrc); gl.compileShader(this._fragShader); // if our frag shader failed compilation? if (!gl.getShaderParameter(this._fragShader, gl.COMPILE_STATUS)) { console.error( 'Darn! An error occurred compiling the fragment shader:' + gl.getShaderInfoLog(this._fragShader) ); return null; } this._glProgram = gl.createProgram(); gl.attachShader(this._glProgram, this._vertShader); gl.attachShader(this._glProgram, this._fragShader); gl.linkProgram(this._glProgram); if (!gl.getProgramParameter(this._glProgram, gl.LINK_STATUS)) { console.error( 'Snap! Error linking shader program: ' + gl.getProgramInfoLog(this._glProgram) ); } this._loadAttributes(); this._loadUniforms(); } return this; }; /** * Queries the active attributes for this shader and loads * their names and locations into the attributes array. * @method _loadAttributes * @private */ p5.Shader.prototype._loadAttributes = function() { if (this._loadedAttributes) { return; } this.attributes = {}; var gl = this._renderer.GL; var numAttributes = gl.getProgramParameter( this._glProgram, gl.ACTIVE_ATTRIBUTES ); for (var i = 0; i < numAttributes; ++i) { var attributeInfo = gl.getActiveAttrib(this._glProgram, i); var name = attributeInfo.name; var location = gl.getAttribLocation(this._glProgram, name); var attribute = {}; attribute.name = name; attribute.location = location; attribute.type = attributeInfo.type; attribute.size = attributeInfo.size; this.attributes[name] = attribute; } this._loadedAttributes = true; }; /** * Queries the active uniforms for this shader and loads * their names and locations into the uniforms array. * @method _loadUniforms * @private */ p5.Shader.prototype._loadUniforms = function() { if (this._loadedUniforms) { return; } var gl = this._renderer.GL; // Inspect shader and cache uniform info var numUniforms = gl.getProgramParameter(this._glProgram, gl.ACTIVE_UNIFORMS); var samplerIndex = 0; for (var i = 0; i < numUniforms; ++i) { var uniformInfo = gl.getActiveUniform(this._glProgram, i); var uniform = {}; uniform.location = gl.getUniformLocation(this._glProgram, uniformInfo.name); uniform.size = uniformInfo.size; var uniformName = uniformInfo.name; //uniforms thats are arrays have their name returned as //someUniform[0] which is a bit silly so we trim it //off here. The size property tells us that its an array //so we dont lose any information by doing this if (uniformInfo.size > 1) { uniformName = uniformName.substring(0, uniformName.indexOf('[0]')); } uniform.name = uniformName; uniform.type = uniformInfo.type; if (uniform.type === gl.SAMPLER_2D) { uniform.samplerIndex = samplerIndex; samplerIndex++; this.samplers.push(uniform); } this.uniforms[uniformName] = uniform; } this._loadedUniforms = true; }; p5.Shader.prototype.compile = function() { // TODO }; /** * initializes (if needed) and binds the shader program. * @method bindShader * @private */ p5.Shader.prototype.bindShader = function() { this.init(); if (!this._bound) { this.useProgram(); this._bound = true; this.bindTextures(); this._loadAttributes(); this._loadUniforms(); this._renderer._setDefaultCamera(); this._setMatrixUniforms(); if (this === this._renderer.curStrokeShader) { this._setViewportUniform(); } } }; /** * @method unbindShader * @chainable * @private */ p5.Shader.prototype.unbindShader = function() { if (this._bound) { this.unbindTextures(); //this._renderer.GL.useProgram(0); ?? this._bound = false; } return this; }; p5.Shader.prototype.bindTextures = function() { var gl = this._renderer.GL; for (var i = 0; i < this.samplers.length; i++) { var uniform = this.samplers[i]; var tex = uniform.texture; if (tex === undefined) { // user hasn't yet supplied a texture for this slot. // (or there may not be one--maybe just lighting), // so we supply a default texture instead. tex = this._renderer._getEmptyTexture(); } gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); tex.bindTexture(); tex.update(); gl.uniform1i(uniform.location, uniform.samplerIndex); } }; p5.Shader.prototype.unbindTextures = function() { // TODO: migrate stuff from material.js here // - OR - have material.js define this function }; p5.Shader.prototype._setMatrixUniforms = function() { this.setUniform('uProjectionMatrix', this._renderer.uPMatrix.mat4); this.setUniform('uModelViewMatrix', this._renderer.uMVMatrix.mat4); this.setUniform('uViewMatrix', this._renderer.cameraMatrix.mat4); if (this === this._renderer.curFillShader) { this._renderer.uNMatrix.inverseTranspose(this._renderer.uMVMatrix); this.setUniform('uNormalMatrix', this._renderer.uNMatrix.mat3); } }; p5.Shader.prototype._setViewportUniform = function() { this.setUniform('uViewport', this._renderer._viewport); }; /** * @method useProgram * @chainable * @private */ p5.Shader.prototype.useProgram = function() { var gl = this._renderer.GL; gl.useProgram(this._glProgram); return this; }; /** * Wrapper around gl.uniform functions. * As we store uniform info in the shader we can use that * to do type checking on the supplied data and call * the appropriate function. * @method setUniform * @chainable * @param {String} uniformName the name of the uniform in the * shader program * @param {Object|Number|Boolean|Number[]} data the data to be associated * with that uniform; type varies (could be a single numerical value, array, * matrix, or texture / sampler reference) */ p5.Shader.prototype.setUniform = function(uniformName, data) { //@todo update all current gl.uniformXX calls var uniform = this.uniforms[uniformName]; if (!uniform) { //@todo warning? return; } var location = uniform.location; var gl = this._renderer.GL; // todo: is this safe to do here? // todo: store the values another way? this.useProgram(); // TODO BIND? switch (uniform.type) { case gl.BOOL: if (data === true) { gl.uniform1i(location, 1); } else { gl.uniform1i(location, 0); } break; case gl.INT: if (uniform.size > 1) { data.length && gl.uniform1iv(location, data); } else { gl.uniform1i(location, data); } break; case gl.FLOAT: if (uniform.size > 1) { data.length && gl.uniform1fv(location, data); } else { gl.uniform1f(location, data); } break; case gl.FLOAT_MAT3: gl.uniformMatrix3fv(location, false, data); break; case gl.FLOAT_MAT4: gl.uniformMatrix4fv(location, false, data); break; case gl.FLOAT_VEC2: if (uniform.size > 1) { data.length && gl.uniform2fv(location, data); } else { gl.uniform2f(location, data[0], data[1]); } break; case gl.FLOAT_VEC3: if (uniform.size > 1) { data.length && gl.uniform3fv(location, data); } else { gl.uniform3f(location, data[0], data[1], data[2]); } break; case gl.FLOAT_VEC4: if (uniform.size > 1) { data.length && gl.uniform4fv(location, data); } else { gl.uniform4f(location, data[0], data[1], data[2], data[3]); } break; case gl.SAMPLER_2D: gl.activeTexture(gl.TEXTURE0 + uniform.samplerIndex); uniform.texture = this._renderer.getTexture(data); gl.uniform1i(uniform.location, uniform.samplerIndex); break; //@todo complete all types } return this; }; /* NONE OF THIS IS FAST OR EFFICIENT BUT BEAR WITH ME * * these shader "type" query methods are used by various * facilities of the renderer to determine if changing * the shader type for the required action (for example, * do we need to load the default lighting shader if the * current shader cannot handle lighting?) * **/ p5.Shader.prototype.isLightShader = function() { return ( this.uniforms.uUseLighting !== undefined || this.uniforms.uAmbientLightCount !== undefined || this.uniforms.uDirectionalLightCount !== undefined || this.uniforms.uPointLightCount !== undefined || this.uniforms.uAmbientColor !== undefined || this.uniforms.uDirectionalColor !== undefined || this.uniforms.uPointLightLocation !== undefined || this.uniforms.uPointLightColor !== undefined || this.uniforms.uLightingDirection !== undefined || this.uniforms.uSpecular !== undefined ); }; p5.Shader.prototype.isTextureShader = function() { return this.samplerIndex > 0; }; p5.Shader.prototype.isColorShader = function() { return ( this.attributes.aVertexColor !== undefined || this.uniforms.uMaterialColor !== undefined ); }; p5.Shader.prototype.isTexLightShader = function() { return this.isLightShader() && this.isTextureShader(); }; p5.Shader.prototype.isStrokeShader = function() { return this.uniforms.uStrokeWeight !== undefined; }; /** * @method enableAttrib * @chainable * @private */ p5.Shader.prototype.enableAttrib = function( loc, size, type, normalized, stride, offset ) { var gl = this._renderer.GL; if (loc !== -1) { gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, type, normalized, stride, offset); } return this; }; module.exports = p5.Shader; },{"../core/core":22}],74:[function(_dereq_,module,exports){ /** * This module defines the p5.Texture class * @module Lights, Camera * @submodule Material * @for p5 * @requires core */ 'use strict'; var p5 = _dereq_('../core/core'); /** * Texture class for WEBGL Mode * @private * @class p5.Texture * @param {p5.RendererGL} renderer an instance of p5.RendererGL that * will provide the GL context for this new p5.Texture * @param {p5.Image|p5.Graphics|p5.Element|p5.MediaElement} [obj] the * object containing the image data to store in the texture. */ p5.Texture = function(renderer, obj) { this._renderer = renderer; var gl = this._renderer.GL; this.src = obj; this.glTex = undefined; this.glTarget = gl.TEXTURE_2D; this.glFormat = gl.RGBA; this.mipmaps = false; this.glMinFilter = gl.LINEAR; this.glMagFilter = gl.LINEAR; this.glWrapS = gl.CLAMP_TO_EDGE; this.glWrapT = gl.CLAMP_TO_EDGE; // used to determine if this texture might need constant updating // because it is a video or gif. this.isSrcMediaElement = typeof p5.MediaElement !== 'undefined' && obj instanceof p5.MediaElement; this._videoPrevUpdateTime = 0; this.isSrcHTMLElement = typeof p5.Element !== 'undefined' && obj instanceof p5.Element && !(obj instanceof p5.Graphics); this.isSrcP5Image = obj instanceof p5.Image; this.isSrcP5Graphics = obj instanceof p5.Graphics; var textureData = this._getTextureDataFromSource(); this.width = textureData.width; this.height = textureData.height; this.init(textureData); return this; }; p5.Texture.prototype._getTextureDataFromSource = function() { var textureData; if (this.isSrcP5Image) { // param is a p5.Image textureData = this.src.canvas; } else if ( this.isSrcMediaElement || this.isSrcP5Graphics || this.isSrcHTMLElement ) { // if param is a video HTML element textureData = this.src.elt; } return textureData; }; /** * Initializes common texture parameters, creates a gl texture, * tries to upload the texture for the first time if data is * already available. * @private * @method init */ p5.Texture.prototype.init = function(data) { var gl = this._renderer.GL; this.glTex = gl.createTexture(); this.bindTexture(); //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this.glMagFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this.glMinFilter); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this.glWrapS); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this.glWrapT); if ( this.width === 0 || this.height === 0 || (this.isSrcMediaElement && !this.src.loadedmetadata) ) { // assign a 1x1 empty texture initially, because data is not yet ready, // so that no errors occur in gl console! var tmpdata = new Uint8Array([1, 1, 1, 1]); gl.texImage2D( this.glTarget, 0, gl.RGBA, 1, 1, 0, this.glFormat, gl.UNSIGNED_BYTE, tmpdata ); } else { // data is ready: just push the texture! gl.texImage2D( this.glTarget, 0, this.glFormat, this.glFormat, gl.UNSIGNED_BYTE, data ); } }; /** * Checks if the source data for this texture has changed (if it's * easy to do so) and reuploads the texture if necessary. If it's not * possible or to expensive to do a calculation to determine wheter or * not the data has occurred, this method simply re-uploads the texture. * @method update */ p5.Texture.prototype.update = function() { var data = this.src; if (data.width === 0 || data.height === 0) { return; // nothing to do! } var textureData = this._getTextureDataFromSource(); var gl = this._renderer.GL; // pull texture from data, make sure width & height are appropriate if (textureData.width !== this.width || textureData.height !== this.height) { // make sure that if the width and height of this.src have changed // for some reason, we update our metadata and upload the texture again this.width = textureData.width; this.height = textureData.height; this.bindTexture(); gl.texImage2D( this.glTarget, 0, this.glFormat, this.glFormat, gl.UNSIGNED_BYTE, textureData ); if (this.isSrcP5Image) { data.setModified(false); } else if (this.isSrcMediaElement || this.isSrcHTMLElement) { // on the first frame the metadata comes in, the size will be changed // from 0 to actual size, but pixels may not be available. // flag for update in a future frame. // if we don't do this, a paused video, for example, may not // send the first frame to texture memory. data.setModified(true); } } else if (this.isSrcP5Image) { // for an image, we only update if the modified field has been set, // for example, by a call to p5.Image.set if (data.isModified()) { this.bindTexture(); gl.texImage2D( this.glTarget, 0, this.glFormat, this.glFormat, gl.UNSIGNED_BYTE, textureData ); data.setModified(false); } } else if (this.isSrcMediaElement) { var shouldUpdate = false; // for a media element (video), we'll check if the current time in // the video frame matches the last time. if it doesn't match, the // video has advanced or otherwise been taken to a new frame, // and we need to upload it. if (data.isModified()) { // p5.MediaElement may have also had set/updatePixels, etc. called // on it and should be updated, or may have been set for the first // time! shouldUpdate = true; data.setModified(false); } else if (data.loadedmetadata) { // if the meta data has been loaded, we can ask the video // what it's current position (in time) is. if (this._videoPrevUpdateTime !== data.time()) { // update the texture in gpu mem only if the current // video timestamp does not match the timestamp of the last // time we uploaded this texture (and update the time we // last uploaded, too) this._videoPrevUpdateTime = data.time(); shouldUpdate = true; } } if (shouldUpdate) { this.bindTexture(); gl.texImage2D( this.glTarget, 0, this.glFormat, this.glFormat, gl.UNSIGNED_BYTE, textureData ); } } else { /* data instanceof p5.Graphics, probably */ // there is not enough information to tell if the texture can be // conditionally updated; so to be safe, we just go ahead and upload it. gl.texImage2D( this.glTarget, 0, this.glFormat, this.glFormat, gl.UNSIGNED_BYTE, textureData ); } }; /** * Binds the texture to the appropriate GL target. * @method bindTexture */ p5.Texture.prototype.bindTexture = function() { // bind texture using gl context + glTarget and // generated gl texture object var gl = this._renderer.GL; gl.bindTexture(this.glTarget, this.glTex); return this; }; /** * Unbinds the texture from the appropriate GL target. * @method unbindTexture */ p5.Texture.prototype.unbindTexture = function() { // unbind per above, disable texturing on glTarget var gl = this._renderer.GL; gl.bindTexture(this.glTarget, null); }; module.exports = p5.Texture; },{"../core/core":22}],75:[function(_dereq_,module,exports){ /** * @module Shape * @submodule 3D Primitives * @for p5 * @requires core * @requires p5.Geometry */ 'use strict'; var p5 = _dereq_('../core/core'); _dereq_('./p5.Geometry'); /** * Draw a plane with given a width and height * @method plane * @param {Number} [width] width of the plane * @param {Number} [height] height of the plane * @param {Integer} [detailX] Optional number of triangle * subdivisions in x-dimension * @param {Integer} [detailY] Optional number of triangle * subdivisions in y-dimension * @chainable * @example *
* * //draw a plane with width 50 and height 50 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * plane(50, 50); * } * *
* * @alt * Nothing displayed on canvas * Rotating interior view of a box with sides that change color. * 3d red and green gradient. * Rotating interior view of a cylinder with sides that change color. * Rotating view of a cylinder with sides that change color. * 3d red and green gradient. * rotating view of a multi-colored cylinder with concave sides. */ p5.prototype.plane = function(width, height, detailX, detailY) { this._assert3d('plane'); p5._validateParameters('plane', arguments); if (typeof width === 'undefined') { width = 50; } if (typeof height === 'undefined') { height = width; } if (typeof detailX === 'undefined') { detailX = 1; } if (typeof detailY === 'undefined') { detailY = 1; } var gId = 'plane|' + detailX + '|' + detailY; if (!this._renderer.geometryInHash(gId)) { var _plane = function() { var u, v, p; for (var i = 0; i <= this.detailY; i++) { v = i / this.detailY; for (var j = 0; j <= this.detailX; j++) { u = j / this.detailX; p = new p5.Vector(u - 0.5, v - 0.5, 0); this.vertices.push(p); this.uvs.push(u, v); } } }; var planeGeom = new p5.Geometry(detailX, detailY, _plane); planeGeom.computeFaces().computeNormals(); if (detailX <= 1 && detailY <= 1) { planeGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log( 'Cannot draw stroke on plane objects with more' + ' than 1 detailX or 1 detailY' ); } this._renderer.createBuffers(gId, planeGeom); } this._renderer.drawBuffersScaled(gId, width, height, 0); }; /** * Draw a box with given width, height and depth * @method box * @param {Number} [width] width of the box * @param {Number} [Height] height of the box * @param {Number} [depth] depth of the box * @param {Integer} [detailX] Optional number of triangle * subdivisions in x-dimension * @param {Integer} [detailY] Optional number of triangle * subdivisions in y-dimension * @chainable * @example *
* * //draw a spinning box with width, height and depth 200 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * box(50); * } * *
*/ p5.prototype.box = function(width, height, depth, detailX, detailY) { this._assert3d('box'); p5._validateParameters('box', arguments); if (typeof width === 'undefined') { width = 50; } if (typeof height === 'undefined') { height = width; } if (typeof depth === 'undefined') { depth = height; } var perPixelLighting = this._renderer.attributes && this._renderer.attributes.perPixelLighting; if (typeof detailX === 'undefined') { detailX = perPixelLighting ? 1 : 4; } if (typeof detailY === 'undefined') { detailY = perPixelLighting ? 1 : 4; } var gId = 'box|' + detailX + '|' + detailY; if (!this._renderer.geometryInHash(gId)) { var _box = function() { var cubeIndices = [ [0, 4, 2, 6], // -1, 0, 0],// -x [1, 3, 5, 7], // +1, 0, 0],// +x [0, 1, 4, 5], // 0, -1, 0],// -y [2, 6, 3, 7], // 0, +1, 0],// +y [0, 2, 1, 3], // 0, 0, -1],// -z [4, 5, 6, 7] // 0, 0, +1] // +z ]; //using strokeIndices instead of faces for strokes //to avoid diagonal stroke lines across face of box this.strokeIndices = [ [0, 1], [1, 3], [3, 2], [6, 7], [8, 9], [9, 11], [14, 15], [16, 17], [17, 19], [18, 19], [20, 21], [22, 23] ]; for (var i = 0; i < cubeIndices.length; i++) { var cubeIndex = cubeIndices[i]; var v = i * 4; for (var j = 0; j < 4; j++) { var d = cubeIndex[j]; //inspired by lightgl: //https://github.com/evanw/lightgl.js //octants:https://en.wikipedia.org/wiki/Octant_(solid_geometry) var octant = new p5.Vector( ((d & 1) * 2 - 1) / 2, ((d & 2) - 1) / 2, ((d & 4) / 2 - 1) / 2 ); this.vertices.push(octant); this.uvs.push(j & 1, (j & 2) / 2); } this.faces.push([v, v + 1, v + 2]); this.faces.push([v + 2, v + 1, v + 3]); } }; var boxGeom = new p5.Geometry(detailX, detailY, _box); boxGeom.computeNormals(); if (detailX <= 4 && detailY <= 4) { boxGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log( 'Cannot draw stroke on box objects with more' + ' than 4 detailX or 4 detailY' ); } //initialize our geometry buffer with //the key val pair: //geometry Id, Geom object this._renderer.createBuffers(gId, boxGeom); } this._renderer.drawBuffersScaled(gId, width, height, depth); return this; }; /** * Draw a sphere with given radius * @method sphere * @param {Number} [radius] radius of circle * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments, * the more segments the smoother geometry * default is 16 * @chainable * @example *
* * // draw a sphere with radius 200 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * sphere(40); * } * *
*/ p5.prototype.sphere = function(radius, detailX, detailY) { this._assert3d('sphere'); p5._validateParameters('sphere', arguments); if (typeof radius === 'undefined') { radius = 50; } if (typeof detailX === 'undefined') { detailX = 24; } if (typeof detailY === 'undefined') { detailY = 16; } this.ellipsoid(radius, radius, radius, detailX, detailY); return this; }; /** * @private * Helper function for creating both cones and cyllinders * Will only generate well-defined geometry when bottomRadius, height > 0 * and topRadius >= 0 * If topRadius == 0, topCap should be false */ var _truncatedCone = function( bottomRadius, topRadius, height, detailX, detailY, bottomCap, topCap ) { bottomRadius = bottomRadius <= 0 ? 1 : bottomRadius; topRadius = topRadius < 0 ? 0 : topRadius; height = height <= 0 ? bottomRadius : height; detailX = detailX < 3 ? 3 : detailX; detailY = detailY < 1 ? 1 : detailY; bottomCap = bottomCap === undefined ? true : bottomCap; topCap = topCap === undefined ? topRadius !== 0 : topCap; var start = bottomCap ? -2 : 0; var end = detailY + (topCap ? 2 : 0); var vertsOnLayer = {}; //ensure constant slant for interior vertex normals var slant = Math.atan2(bottomRadius - topRadius, height); var yy, ii, jj, nextii, nextjj; for (yy = start; yy <= end; ++yy) { var v = yy / detailY; var y = height * v; var ringRadius; if (yy < 0) { //for the bottomCap edge y = 0; v = 0; ringRadius = bottomRadius; } else if (yy > detailY) { //for the topCap edge y = height; v = 1; ringRadius = topRadius; } else { //for the middle ringRadius = bottomRadius + (topRadius - bottomRadius) * v; } if (yy === -2 || yy === detailY + 2) { //center of bottom or top caps ringRadius = 0; } y -= height / 2; //shift coordiate origin to the center of object vertsOnLayer[yy] = ringRadius === 0 ? 1 : detailX; for (ii = 0; ii < vertsOnLayer[yy]; ++ii) { var u = ii / detailX; //VERTICES this.vertices.push( new p5.Vector( Math.sin(u * 2 * Math.PI) * ringRadius, y, Math.cos(u * 2 * Math.PI) * ringRadius ) ); //VERTEX NORMALS this.vertexNormals.push( new p5.Vector( yy < 0 || yy > detailY ? 0 : Math.sin(u * 2 * Math.PI) * Math.cos(slant), yy < 0 ? -1 : yy > detailY ? 1 : Math.sin(slant), yy < 0 || yy > detailY ? 0 : Math.cos(u * 2 * Math.PI) * Math.cos(slant) ) ); //UVs this.uvs.push(u, v); } } var startIndex = 0; if (bottomCap) { for (jj = 0; jj < vertsOnLayer[-1]; ++jj) { nextjj = (jj + 1) % vertsOnLayer[-1]; this.faces.push([ startIndex, startIndex + 1 + nextjj, startIndex + 1 + jj ]); } startIndex += vertsOnLayer[-2] + vertsOnLayer[-1]; } for (yy = 0; yy < detailY; ++yy) { for (ii = 0; ii < vertsOnLayer[yy]; ++ii) { if (vertsOnLayer[yy + 1] === 1) { //top layer nextii = (ii + 1) % vertsOnLayer[yy]; this.faces.push([ startIndex + ii, startIndex + nextii, startIndex + vertsOnLayer[yy] ]); } else { //other side faces //should have vertsOnLayer[yy] === vertsOnLayer[yy + 1] nextii = (ii + 1) % vertsOnLayer[yy]; this.faces.push([ startIndex + ii, startIndex + nextii, startIndex + vertsOnLayer[yy] + nextii ]); this.faces.push([ startIndex + ii, startIndex + vertsOnLayer[yy] + nextii, startIndex + vertsOnLayer[yy] + ii ]); } } startIndex += vertsOnLayer[yy]; } if (topCap) { startIndex += vertsOnLayer[detailY]; for (ii = 0; ii < vertsOnLayer[detailY + 1]; ++ii) { nextii = (ii + 1) % vertsOnLayer[detailY + 1]; this.faces.push([ startIndex + ii, startIndex + nextii, startIndex + vertsOnLayer[detailY + 1] ]); } } }; /** * Draw a cylinder with given radius and height * @method cylinder * @param {Number} [radius] radius of the surface * @param {Number} [height] height of the cylinder * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments in y-dimension, * the more segments the smoother geometry * default is 1 * @param {Boolean} [bottomCap] whether to draw the bottom of the cylinder * @param {Boolean} [topCap] whether to draw the top of the cylinder * @chainable * @example *
* * //draw a spinning cylinder with radius 20 and height 50 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateZ(frameCount * 0.01); * cylinder(20, 50); * } * *
*/ p5.prototype.cylinder = function( radius, height, detailX, detailY, bottomCap, topCap ) { this._assert3d('cylinder'); p5._validateParameters('cylinder', arguments); if (typeof radius === 'undefined') { radius = 50; } if (typeof height === 'undefined') { height = radius; } if (typeof detailX === 'undefined') { detailX = 24; } if (typeof detailY === 'undefined') { detailY = 1; } if (typeof topCap === 'undefined') { topCap = true; } if (typeof bottomCap === 'undefined') { bottomCap = true; } var gId = 'cylinder|' + detailX + '|' + detailY + '|' + bottomCap + '|' + topCap; if (!this._renderer.geometryInHash(gId)) { var cylinderGeom = new p5.Geometry(detailX, detailY); _truncatedCone.call( cylinderGeom, 1, 1, 1, detailX, detailY, bottomCap, topCap ); cylinderGeom.computeNormals(); if (detailX <= 24 && detailY <= 16) { cylinderGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log( 'Cannot draw stroke on cylinder objects with more' + ' than 24 detailX or 16 detailY' ); } this._renderer.createBuffers(gId, cylinderGeom); } this._renderer.drawBuffersScaled(gId, radius, height, radius); return this; }; /** * Draw a cone with given radius and height * @method cone * @param {Number} [radius] radius of the bottom surface * @param {Number} [height] height of the cone * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments, * the more segments the smoother geometry * default is 1 * @param {Boolean} [cap] whether to draw the base of the cone * @chainable * @example *
* * //draw a spinning cone with radius 40 and height 70 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateZ(frameCount * 0.01); * cone(40, 70); * } * *
*/ p5.prototype.cone = function(radius, height, detailX, detailY, cap) { this._assert3d('cone'); p5._validateParameters('cone', arguments); if (typeof radius === 'undefined') { radius = 50; } if (typeof height === 'undefined') { height = radius; } if (typeof detailX === 'undefined') { detailX = 24; } if (typeof detailY === 'undefined') { detailY = 1; } if (typeof cap === 'undefined') { cap = true; } var gId = 'cone|' + detailX + '|' + detailY + '|' + cap; if (!this._renderer.geometryInHash(gId)) { var coneGeom = new p5.Geometry(detailX, detailY); _truncatedCone.call(coneGeom, 1, 0, 1, detailX, detailY, cap, false); //for cones we need to average Normals coneGeom.computeNormals(); if (detailX <= 24 && detailY <= 16) { coneGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log( 'Cannot draw stroke on cone objects with more' + ' than 24 detailX or 16 detailY' ); } this._renderer.createBuffers(gId, coneGeom); } this._renderer.drawBuffersScaled(gId, radius, height, radius); return this; }; /** * Draw an ellipsoid with given radius * @method ellipsoid * @param {Number} [radiusx] xradius of circle * @param {Number} [radiusy] yradius of circle * @param {Number} [radiusz] zradius of circle * @param {Integer} [detailX] number of segments, * the more segments the smoother geometry * default is 24. Avoid detail number above * 150, it may crash the browser. * @param {Integer} [detailY] number of segments, * the more segments the smoother geometry * default is 16. Avoid detail number above * 150, it may crash the browser. * @chainable * @example *
* * // draw an ellipsoid with radius 20, 30 and 40. * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * ellipsoid(20, 30, 40); * } * *
*/ p5.prototype.ellipsoid = function(radiusX, radiusY, radiusZ, detailX, detailY) { this._assert3d('ellipsoid'); p5._validateParameters('ellipsoid', arguments); if (typeof radiusX === 'undefined') { radiusX = 50; } if (typeof radiusY === 'undefined') { radiusY = radiusX; } if (typeof radiusZ === 'undefined') { radiusZ = radiusX; } if (typeof detailX === 'undefined') { detailX = 24; } if (typeof detailY === 'undefined') { detailY = 16; } var gId = 'ellipsoid|' + detailX + '|' + detailY; if (!this._renderer.geometryInHash(gId)) { var _ellipsoid = function() { for (var i = 0; i <= this.detailY; i++) { var v = i / this.detailY; var phi = Math.PI * v - Math.PI / 2; var cosPhi = Math.cos(phi); var sinPhi = Math.sin(phi); for (var j = 0; j <= this.detailX; j++) { var u = j / this.detailX; var theta = 2 * Math.PI * u; var cosTheta = Math.cos(theta); var sinTheta = Math.sin(theta); var p = new p5.Vector(cosPhi * sinTheta, sinPhi, cosPhi * cosTheta); this.vertices.push(p); this.vertexNormals.push(p); this.uvs.push(u, v); } } }; var ellipsoidGeom = new p5.Geometry(detailX, detailY, _ellipsoid); ellipsoidGeom.computeFaces(); if (detailX <= 24 && detailY <= 24) { ellipsoidGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log( 'Cannot draw stroke on ellipsoids with more' + ' than 24 detailX or 24 detailY' ); } this._renderer.createBuffers(gId, ellipsoidGeom); } this._renderer.drawBuffersScaled(gId, radiusX, radiusY, radiusZ); return this; }; /** * Draw a torus with given radius and tube radius * @method torus * @param {Number} [radius] radius of the whole ring * @param {Number} [tubeRadius] radius of the tube * @param {Integer} [detailX] number of segments in x-dimension, * the more segments the smoother geometry * default is 24 * @param {Integer} [detailY] number of segments in y-dimension, * the more segments the smoother geometry * default is 16 * @chainable * @example *
* * //draw a spinning torus with radius 200 and tube radius 60 * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * torus(50, 15); * } * *
*/ p5.prototype.torus = function(radius, tubeRadius, detailX, detailY) { this._assert3d('torus'); p5._validateParameters('torus', arguments); if (typeof radius === 'undefined') { radius = 50; } else if (!radius) { return; // nothing to draw } if (typeof tubeRadius === 'undefined') { tubeRadius = 10; } else if (!tubeRadius) { return; // nothing to draw } if (typeof detailX === 'undefined') { detailX = 24; } if (typeof detailY === 'undefined') { detailY = 16; } var tubeRatio = (tubeRadius / radius).toPrecision(4); var gId = 'torus|' + tubeRatio + '|' + detailX + '|' + detailY; if (!this._renderer.geometryInHash(gId)) { var _torus = function() { for (var i = 0; i <= this.detailY; i++) { var v = i / this.detailY; var phi = 2 * Math.PI * v; var cosPhi = Math.cos(phi); var sinPhi = Math.sin(phi); var r = 1 + tubeRatio * cosPhi; for (var j = 0; j <= this.detailX; j++) { var u = j / this.detailX; var theta = 2 * Math.PI * u; var cosTheta = Math.cos(theta); var sinTheta = Math.sin(theta); var p = new p5.Vector(r * cosTheta, r * sinTheta, tubeRatio * sinPhi); var n = new p5.Vector(cosPhi * cosTheta, cosPhi * sinTheta, sinPhi); this.vertices.push(p); this.vertexNormals.push(n); this.uvs.push(u, v); } } }; var torusGeom = new p5.Geometry(detailX, detailY, _torus); torusGeom.computeFaces(); if (detailX <= 24 && detailY <= 16) { torusGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log( 'Cannot draw strokes on torus object with more' + ' than 24 detailX or 16 detailY' ); } this._renderer.createBuffers(gId, torusGeom); } this._renderer.drawBuffersScaled(gId, radius, radius, radius); return this; }; /////////////////////// /// 2D primitives ///////////////////////// //@TODO p5.RendererGL.prototype.point = function(x, y, z) { console.log('point not yet implemented in webgl'); return this; }; p5.RendererGL.prototype.triangle = function(args) { var x1 = args[0], y1 = args[1]; var x2 = args[2], y2 = args[3]; var x3 = args[4], y3 = args[5]; var gId = 'tri'; if (!this.geometryInHash(gId)) { var _triangle = function() { var vertices = []; vertices.push(new p5.Vector(0, 0, 0)); vertices.push(new p5.Vector(0, 1, 0)); vertices.push(new p5.Vector(1, 0, 0)); this.strokeIndices = [[0, 1], [1, 2], [2, 0]]; this.vertices = vertices; this.faces = [[0, 1, 2]]; this.uvs = [0, 0, 0, 1, 1, 1]; }; var triGeom = new p5.Geometry(1, 1, _triangle); triGeom._makeTriangleEdges()._edgesToVertices(); triGeom.computeNormals(); this.createBuffers(gId, triGeom); } // only one triangle is cached, one point is at the origin, and the // two adjacent sides are tne unit vectors along the X & Y axes. // // this matrix multiplication transforms those two unit vectors // onto the required vector prior to rendering, and moves the // origin appropriately. var uMVMatrix = this.uMVMatrix.copy(); try { // prettier-ignore var mult = new p5.Matrix([ x2 - x1, y2 - y1, 0, 0, // the resulting unit X-axis x3 - x1, y3 - y1, 0, 0, // the resulting unit Y-axis 0, 0, 1, 0, // the resulting unit Z-axis (unchanged) x1, y1, 0, 1 // the resulting origin ]).mult(this.uMVMatrix); this.uMVMatrix = mult; this.drawBuffers(gId); } finally { this.uMVMatrix = uMVMatrix; } return this; }; p5.RendererGL.prototype.ellipse = function(args) { var x = args[0]; var y = args[1]; var width = args[2]; var height = args[3]; //detailX and Y are optional 6th & 7th //arguments var detailX = args[4] || 24; var gId = 'ellipse|' + detailX; if (!this.geometryInHash(gId)) { var _ellipse = function() { this.vertices.push(new p5.Vector(0.5, 0.5, 0)); this.uvs.push([0.5, 0.5]); for (var i = 0; i < this.detailX; i++) { var u = i / this.detailX; var theta = 2 * Math.PI * u; var _x = 0.5 + Math.cos(theta) / 2; var _y = 0.5 + Math.sin(theta) / 2; this.vertices.push(new p5.Vector(_x, _y, 0)); this.uvs.push(_x, _y); this.faces.push([0, (i + 1) % this.detailX + 1, i + 1]); } }; var ellipseGeom = new p5.Geometry(detailX, 1, _ellipse); ellipseGeom.computeNormals(); if (detailX <= 50) { ellipseGeom._makeTriangleEdges()._edgesToVertices(); } else { console.log('Cannot stroke ellipse with more than 50 detailX'); } this.createBuffers(gId, ellipseGeom); } // only a single ellipse (of a given detail) is cached: a circle of // _diameter_ 1 (radius 0.5). // // before rendering, this circle is squished (technical term ;) // appropriately and moved to the required location. var uMVMatrix = this.uMVMatrix.copy(); try { this.uMVMatrix.translate([x, y, 0]); this.uMVMatrix.scale(width, height, 1); this.drawBuffers(gId); } finally { this.uMVMatrix = uMVMatrix; } return this; }; p5.RendererGL.prototype.rect = function(args) { var perPixelLighting = this.attributes.perPixelLighting; var x = args[0]; var y = args[1]; var width = args[2]; var height = args[3]; var detailX = args[4] || (perPixelLighting ? 1 : 24); var detailY = args[5] || (perPixelLighting ? 1 : 16); var gId = 'rect|' + detailX + '|' + detailY; if (!this.geometryInHash(gId)) { var _rect = function() { for (var i = 0; i <= this.detailY; i++) { var v = i / this.detailY; for (var j = 0; j <= this.detailX; j++) { var u = j / this.detailX; var p = new p5.Vector(u, v, 0); this.vertices.push(p); this.uvs.push(u, v); } } }; var rectGeom = new p5.Geometry(detailX, detailY, _rect); rectGeom .computeFaces() .computeNormals() ._makeTriangleEdges() ._edgesToVertices(); this.createBuffers(gId, rectGeom); } // only a single rectangle (of a given detail) is cached: a square with // opposite corners at (0,0) & (1,1). // // before rendering, this square is scaled & moved to the required location. var uMVMatrix = this.uMVMatrix.copy(); try { this.uMVMatrix.translate([x, y, 0]); this.uMVMatrix.scale(width, height, 1); this.drawBuffers(gId); } finally { this.uMVMatrix = uMVMatrix; } return this; }; p5.RendererGL.prototype.quad = function(x1, y1, x2, y2, x3, y3, x4, y4) { var gId = 'quad|' + x1 + '|' + y1 + '|' + x2 + '|' + y2 + '|' + x3 + '|' + y3 + '|' + x4 + '|' + y4; if (!this.geometryInHash(gId)) { var _quad = function() { this.vertices.push(new p5.Vector(x1, y1, 0)); this.vertices.push(new p5.Vector(x2, y2, 0)); this.vertices.push(new p5.Vector(x3, y3, 0)); this.vertices.push(new p5.Vector(x4, y4, 0)); this.uvs.push(0, 0, 1, 0, 1, 1, 0, 1); this.strokeIndices = [[0, 1], [1, 2], [2, 3], [3, 0]]; }; var quadGeom = new p5.Geometry(2, 2, _quad); quadGeom .computeNormals() ._makeTriangleEdges() ._edgesToVertices(); quadGeom.faces = [[0, 1, 2], [2, 3, 0]]; this.createBuffers(gId, quadGeom); } this.drawBuffers(gId); return this; }; //this implementation of bezier curve //is based on Bernstein polynomial // pretier-ignore p5.RendererGL.prototype.bezier = function( x1, y1, z1, // x2 x2, // y2 y2, // x3 z2, // y3 x3, // x4 y3, // y4 z3, x4, y4, z4 ) { if (arguments.length === 8) { x4 = x3; y4 = y3; x3 = y2; y3 = x2; x2 = z1; y2 = x2; z1 = z2 = z3 = z4 = 0; } var bezierDetail = this._pInst._bezierDetail || 20; //value of Bezier detail this.beginShape(); for (var i = 0; i <= bezierDetail; i++) { var c1 = Math.pow(1 - i / bezierDetail, 3); var c2 = 3 * (i / bezierDetail) * Math.pow(1 - i / bezierDetail, 2); var c3 = 3 * Math.pow(i / bezierDetail, 2) * (1 - i / bezierDetail); var c4 = Math.pow(i / bezierDetail, 3); this.vertex( x1 * c1 + x2 * c2 + x3 * c3 + x4 * c4, y1 * c1 + y2 * c2 + y3 * c3 + y4 * c4, z1 * c1 + z2 * c2 + z3 * c3 + z4 * c4 ); } this.endShape(); return this; }; // pretier-ignore p5.RendererGL.prototype.curve = function( x1, y1, z1, // x2 x2, // y2 y2, // x3 z2, // y3 x3, // x4 y3, // y4 z3, x4, y4, z4 ) { if (arguments.length === 8) { x4 = x3; y4 = y3; x3 = y2; y3 = x2; x2 = z1; y2 = x2; z1 = z2 = z3 = z4 = 0; } var curveDetail = this._pInst._curveDetail; this.beginShape(); for (var i = 0; i <= curveDetail; i++) { var c1 = Math.pow(i / curveDetail, 3) * 0.5; var c2 = Math.pow(i / curveDetail, 2) * 0.5; var c3 = i / curveDetail * 0.5; var c4 = 0.5; var vx = c1 * (-x1 + 3 * x2 - 3 * x3 + x4) + c2 * (2 * x1 - 5 * x2 + 4 * x3 - x4) + c3 * (-x1 + x3) + c4 * (2 * x2); var vy = c1 * (-y1 + 3 * y2 - 3 * y3 + y4) + c2 * (2 * y1 - 5 * y2 + 4 * y3 - y4) + c3 * (-y1 + y3) + c4 * (2 * y2); var vz = c1 * (-z1 + 3 * z2 - 3 * z3 + z4) + c2 * (2 * z1 - 5 * z2 + 4 * z3 - z4) + c3 * (-z1 + z3) + c4 * (2 * z2); this.vertex(vx, vy, vz); } this.endShape(); return this; }; /** * Draw a line given two points * @private * @param {Number} x0 x-coordinate of first vertex * @param {Number} y0 y-coordinate of first vertex * @param {Number} z0 z-coordinate of first vertex * @param {Number} x1 x-coordinate of second vertex * @param {Number} y1 y-coordinate of second vertex * @param {Number} z1 z-coordinate of second vertex * @chainable * @example *
* * //draw a line * function setup() { * createCanvas(100, 100, WEBGL); * } * * function draw() { * background(200); * rotateX(frameCount * 0.01); * rotateY(frameCount * 0.01); * // Use fill instead of stroke to change the color of shape. * fill(255, 0, 0); * line(10, 10, 0, 60, 60, 20); * } * *
*/ p5.RendererGL.prototype.line = function() { if (arguments.length === 6) { this.beginShape(); this.vertex(arguments[0], arguments[1], arguments[2]); this.vertex(arguments[3], arguments[4], arguments[5]); this.endShape(); } else if (arguments.length === 4) { this.beginShape(); this.vertex(arguments[0], arguments[1], 0); this.vertex(arguments[2], arguments[3], 0); this.endShape(); } return this; }; module.exports = p5; },{"../core/core":22,"./p5.Geometry":68}]},{},[13])(13) }); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],87:[function(require,module,exports){ /** * Compiles a querystring * Returns string representation of the object * * @param {Object} * @api private */ exports.encode = function (obj) { var str = ''; for (var i in obj) { if (obj.hasOwnProperty(i)) { if (str.length) str += '&'; str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]); } } return str; }; /** * Parses a simple querystring into an object * * @param {String} qs * @api private */ exports.decode = function(qs){ var qry = {}; var pairs = qs.split('&'); for (var i = 0, l = pairs.length; i < l; i++) { var pair = pairs[i].split('='); qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } return qry; }; },{}],88:[function(require,module,exports){ /** * Parses an URI * * @author Steven Levithan (MIT license) * @api private */ var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/; var parts = [ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor' ]; module.exports = function parseuri(str) { var src = str, b = str.indexOf('['), e = str.indexOf(']'); if (b != -1 && e != -1) { str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length); } var m = re.exec(str || ''), uri = {}, i = 14; while (i--) { uri[parts[i]] = m[i] || ''; } if (b != -1 && e != -1) { uri.source = src; uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':'); uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':'); uri.ipv6uri = true; } return uri; }; },{}],89:[function(require,module,exports){ (function (process){ // Generated by CoffeeScript 1.12.2 (function() { var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime; if ((typeof performance !== "undefined" && performance !== null) && performance.now) { module.exports = function() { return performance.now(); }; } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { module.exports = function() { return (getNanoSeconds() - nodeLoadTime) / 1e6; }; hrtime = process.hrtime; getNanoSeconds = function() { var hr; hr = hrtime(); return hr[0] * 1e9 + hr[1]; }; moduleLoadTime = getNanoSeconds(); upTime = process.uptime() * 1e9; nodeLoadTime = moduleLoadTime - upTime; } else if (Date.now) { module.exports = function() { return Date.now() - loadTime; }; loadTime = Date.now(); } else { module.exports = function() { return new Date().getTime() - loadTime; }; loadTime = new Date().getTime(); } }).call(this); }).call(this,require('_process')) },{"_process":93}],90:[function(require,module,exports){ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(((t=t||self).prettierPlugins=t.prettierPlugins||{},t.prettierPlugins.babel={}))}(this,(function(t){"use strict";var e=function(t,e){const s=new SyntaxError(t+" ("+e.start.line+":"+e.start.column+")");return s.loc=e,s};function s(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function i(t,e){return t(e={exports:{}},e.exports),e.exports}var r=Object.freeze({__proto__:null,default:{EOL:"\n"}});const a=t=>{if("string"!=typeof t)throw new TypeError("Expected a string");const e=t.match(/(?:\r?\n)/g)||[];if(0===e.length)return;const s=e.filter(t=>"\r\n"===t).length;return s>e.length-s?"\r\n":"\n"};var n=a;n.graceful=t=>"string"==typeof t&&a(t)||"\n";var o,h=(o=r)&&o.default||o,p=i((function(t,e){function s(){const t=h;return s=function(){return t},t}function i(){const t=(e=n)&&e.__esModule?e:{default:e};var e;return i=function(){return t},t}Object.defineProperty(e,"__esModule",{value:!0}),e.extract=function(t){const e=t.match(o);return e?e[0].trimLeft():""},e.strip=function(t){const e=t.match(o);return e&&e[0]?t.substring(e[0].length):t},e.parse=function(t){return m(t).pragmas},e.parseWithComments=m,e.print=function({comments:t="",pragmas:e={}}){const r=(0,i().default)(t)||s().EOL,a=Object.keys(e),n=a.map(t=>f(t,e[t])).reduce((t,e)=>t.concat(e),[]).map(t=>" * "+t+r).join("");if(!t){if(0===a.length)return"";if(1===a.length&&!Array.isArray(e[a[0]])){const t=e[a[0]];return"".concat("/**"," ").concat(f(a[0],t)[0]).concat(" */")}}const o=t.split(r).map(t=>"".concat(" *"," ").concat(t)).join(r)+r;return"/**"+r+(t?o:"")+(t&&a.length?" *"+r:"")+n+" */"};const r=/\*\/$/,a=/^\/\*\*/,o=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/,p=/(^|\s+)\/\/([^\r\n]*)/g,c=/^(\r?\n)+/,u=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g,l=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g,d=/(\r?\n|^) *\* ?/g;function m(t){const e=(0,i().default)(t)||s().EOL;t=t.replace(a,"").replace(r,"").replace(d,"$1");let n="";for(;n!==t;)n=t,t=t.replace(u,"".concat(e,"$1 $2").concat(e));t=t.replace(c,"").trimRight();const o=Object.create(null),h=t.replace(l,"").replace(c,"").trimRight();let m;for(;m=l.exec(t);){const t=m[2].replace(p,"");"string"==typeof o[m[1]]||Array.isArray(o[m[1]])?o[m[1]]=[].concat(o[m[1]],t):o[m[1]]=t}return{comments:h,pragmas:o}}function f(t,e){return[].concat(e).map(e=>"@".concat(t," ").concat(e).trim())}}));s(p);p.extract,p.strip,p.parse,p.parseWithComments,p.print;var c={hasPragma:function(t){const e=Object.keys(p.parse(p.extract(t)));return e.includes("prettier")||e.includes("format")},insertPragma:function(t){const e=p.parseWithComments(p.extract(t)),s=Object.assign({format:""},e.pragmas),i=p.print({pragmas:s,comments:e.comments.replace(/^(\s+?\r?\n)+/,"")}).replace(/(\r\n|\r)/g,"\n"),r=p.strip(t);return i+(r.startsWith("\n")?"\n":"\n\n")+r}},u=t=>t[t.length-1];function l(t,e){return!(e=e||{}).ignoreDecorators&&t.declaration&&t.declaration.decorators&&t.declaration.decorators.length>0?l(t.declaration.decorators[0]):!e.ignoreDecorators&&t.decorators&&t.decorators.length>0?l(t.decorators[0]):t.__location?t.__location.startOffset:t.range?t.range[0]:"number"==typeof t.start?t.start:t.loc?t.loc.start:null}function d(t){const e=t.nodes&&u(t.nodes);if(e&&t.source&&!t.source.end&&(t=e),t.__location)return t.__location.endOffset;const s=t.range?t.range[1]:"number"==typeof t.end?t.end:null;return t.typeAnnotation?Math.max(s,d(t.typeAnnotation)):t.loc&&!s?t.loc.end:s}var m={locStart:l,locEnd:d,composeLoc:function(t,e=t){const s="number"==typeof e?e:-1,i=l(t),r=-1!==s?i+s:d(e),a=t.loc.start;return{start:i,end:r,range:[i,r],loc:{start:a,end:-1!==s?{line:a.line,column:a.column+s}:e.loc.end}}}},f=t=>"string"==typeof t?t.replace((({onlyFirst:t=!1}={})=>{const e=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(e,t?void 0:"g")})(),""):t;const D=t=>!Number.isNaN(t)&&(t>=4352&&(t<=4447||9001===t||9002===t||11904<=t&&t<=12871&&12351!==t||12880<=t&&t<=19903||19968<=t&&t<=42182||43360<=t&&t<=43388||44032<=t&&t<=55203||63744<=t&&t<=64255||65040<=t&&t<=65049||65072<=t&&t<=65131||65281<=t&&t<=65376||65504<=t&&t<=65510||110592<=t&&t<=110593||127488<=t&&t<=127569||131072<=t&&t<=262141));var y=D,x=D;y.default=x;const g=t=>{if("string"!=typeof(t=t.replace(/\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g," "))||0===t.length)return 0;t=f(t);let e=0;for(let s=0;s=127&&i<=159||(i>=768&&i<=879||(i>65535&&s++,e+=y(i)?2:1))}return e};var P=g,E=g;P.default=E;const C=/[|\\{}()[\]^$+*?.-]/g;var b=t=>{if("string"!=typeof t)throw new TypeError("Expected a string");return t.replace(C,"\\$&")};const T=/[^\x20-\x7F]/;function A(t){return(e,s,i)=>{const r=i&&i.backwards;if(!1===s)return!1;const{length:a}=e;let n=s;for(;n>=0&&n"],["??"],["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]].forEach((t,e)=>{t.forEach(t=>{R[t]=e})});const j={"==":!0,"!=":!0,"===":!0,"!==":!0},U={"*":!0,"/":!0,"%":!0},q={">>":!0,">>>":!0,"<<":!0};function V(t,e,s){let i=0;for(let r=s=s||0;r(s.match(n.regex)||[]).length?n.quote:a.quote}return o}function H(t,e,s){const i='"'===e?"'":'"',r=t.replace(/\\([\s\S])|(['"])/g,(t,r,a)=>r===i?r:a===e?"\\"+a:a||(s&&/^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(r)?r:"\\"+r));return e+r+e}function W(t){return t&&(t.comments&&t.comments.length>0&&t.comments.some(t=>K(t)&&!t.unignore)||t.prettierIgnore)}function K(t){return"prettier-ignore"===t.value.trim()}function J(t,e){(t.comments||(t.comments=[])).push(e),e.printed=!1,"JSXText"===t.type&&(e.printed=!0)}var X={replaceEndOfLineWith:function(t,e){const s=[];for(const i of t.split("\n"))0!==s.length&&s.push(e),s.push(i);return s},getStringWidth:function(t){return t?T.test(t)?P(t):t.length:0},getMaxContinuousCount:function(t,e){const s=t.match(new RegExp("(".concat(b(e),")+"),"g"));return null===s?0:s.reduce((t,s)=>Math.max(t,s.length/e.length),0)},getMinNotPresentContinuousCount:function(t,e){const s=t.match(new RegExp("(".concat(b(e),")+"),"g"));if(null===s)return 0;const i=new Map;let r=0;for(const t of s){const s=t.length/e.length;i.set(s,!0),s>r&&(r=s)}for(let t=1;t1?t[t.length-2]:null},getLast:u,getNextNonSpaceNonCommentCharacterIndexWithStartIndex:M,getNextNonSpaceNonCommentCharacterIndex:O,getNextNonSpaceNonCommentCharacter:function(t,e,s){return t.charAt(O(t,e,s))},skip:A,skipWhitespace:w,skipSpaces:S,skipToLineEnd:N,skipEverythingButNewLine:F,skipInlineComment:k,skipTrailingComment:I,skipNewline:v,isNextLineEmptyAfterIndex:B,isNextLineEmpty:function(t,e,s){return B(t,s(e))},isPreviousLineEmpty:function(t,e,s){let i=s(e)-1;return i=S(t,i,{backwards:!0}),i=v(t,i,{backwards:!0}),i=S(t,i,{backwards:!0}),i!==v(t,i,{backwards:!0})},hasNewline:L,hasNewlineInRange:function(t,e,s){for(let i=e;i"EmptyStatement"!==t.type);0===s.length?Et(t,e):gt(s[0],e)}function Tt(t,e){"BlockStatement"===t.type?bt(t,e):gt(t,e)}function At(t,e,s,i,r,a){if(!s||"IfStatement"!==s.type||!i)return!1;return")"===X.getNextNonSpaceNonCommentCharacter(t,r,a.locEnd)?(Pt(e,r),!0):e===s.consequent&&i===s.alternate?("BlockStatement"===e.type?Pt(e,r):Et(s,r),!0):"BlockStatement"===i.type?(bt(i,r),!0):"IfStatement"===i.type?(Tt(i.consequent,r),!0):s.consequent===i&&(gt(i,r),!0)}function wt(t,e,s,i,r,a){if(!s||"WhileStatement"!==s.type||!i)return!1;return")"===X.getNextNonSpaceNonCommentCharacter(t,r,a.locEnd)?(Pt(e,r),!0):"BlockStatement"===i.type&&(bt(i,r),!0)}function St(t,e,s,i){return!(!t||"TryStatement"!==t.type&&"CatchClause"!==t.type||!s)&&("CatchClause"===t.type&&e?(Pt(e,i),!0):"BlockStatement"===s.type?(bt(s,i),!0):"TryStatement"===s.type?(Tt(s.finalizer,i),!0):"CatchClause"===s.type&&(Tt(s.body,i),!0))}function Nt(t,e,s,i){return!(!(t&&("ClassDeclaration"===t.type||"ClassExpression"===t.type)&&t.decorators&&t.decorators.length>0)||s&&"Decorator"===s.type)&&(t.decorators&&0!==t.decorators.length?Pt(t.decorators[t.decorators.length-1],i):gt(t,i),!0)}function Ft(t,e,s,i,r){return e&&s&&("Property"===e.type||"TSDeclareMethod"===e.type||"TSAbstractMethodDefinition"===e.type)&&"Identifier"===s.type&&e.key===s&&":"!==X.getNextNonSpaceNonCommentCharacter(t,s,r.locEnd)?(Pt(s,i),!0):!(!s||!e||"Decorator"!==s.type||"ClassMethod"!==e.type&&"ClassProperty"!==e.type&&"TSAbstractClassProperty"!==e.type&&"TSAbstractMethodDefinition"!==e.type&&"TSDeclareMethod"!==e.type&&"MethodDefinition"!==e.type)&&(Pt(s,i),!0)}function kt(t,e,s,i,r,a){if(e&&"FunctionTypeParam"===e.type&&s&&"FunctionTypeAnnotation"===s.type&&i&&"FunctionTypeParam"!==i.type)return Pt(e,r),!0;if(e&&("Identifier"===e.type||"AssignmentPattern"===e.type)&&s&&Mt(s)&&")"===X.getNextNonSpaceNonCommentCharacter(t,r,a.locEnd))return Pt(e,r),!0;if(s&&"FunctionDeclaration"===s.type&&i&&"BlockStatement"===i.type){const e=(()=>{if(0!==(s.params||s.parameters).length)return X.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(t,a.locEnd(X.getLast(s.params||s.parameters)));const e=X.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(t,a.locEnd(s.id));return X.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(t,e+1)})();if(a.locStart(r)>e)return bt(i,r),!0}return!1}function It(t,e){return!(!t||"ImportSpecifier"!==t.type)&&(gt(t,e),!0)}function vt(t,e){return!(!t||"LabeledStatement"!==t.type)&&(gt(t,e),!0)}function Lt(t,e,s,i){return e&&e.body&&0===e.body.length?(i?Et(e,s):gt(e,s),!0):!(!t||"Program"!==t.type||0!==t.body.length||!t.directives||0!==t.directives.length)&&(i?Et(t,s):gt(t,s),!0)}function Bt(t){return"Block"===t.type||"CommentBlock"===t.type}function Mt(t){return"ArrowFunctionExpression"===t.type||"FunctionExpression"===t.type||"FunctionDeclaration"===t.type||"ObjectMethod"===t.type||"ClassMethod"===t.type||"TSDeclareFunction"===t.type||"TSCallSignatureDeclaration"===t.type||"TSConstructSignatureDeclaration"===t.type||"TSConstructSignatureDeclaration"===t.type||"TSMethodSignature"===t.type||"TSConstructorType"===t.type||"TSFunctionType"===t.type||"TSDeclareMethod"===t.type}function Ot(t){return Bt(t)&&"*"===t.value[0]&&/@type\b/.test(t.value)}var Rt={handleOwnLineComment:function(t,e,s,i,r){const{precedingNode:a,enclosingNode:n,followingNode:o}=t;return kt(e,a,n,o,t,s)||function(t,e,s){if(t&&("MemberExpression"===t.type||"OptionalMemberExpression"===t.type)&&e&&"Identifier"===e.type)return gt(t,s),!0;return!1}(n,o,t)||At(e,a,n,o,t,s)||wt(e,a,n,o,t,s)||St(n,a,o,t)||Nt(n,a,o,t)||It(n,t)||function(t,e,s){if(t&&("ForInStatement"===t.type||"ForOfStatement"===t.type))return gt(t,s),!0;return!1}(n,0,t)||function(t,e,s,i){if(e&&("UnionTypeAnnotation"===e.type||"TSUnionType"===e.type))return X.isNodeIgnoreComment(i)&&(s.prettierIgnore=!0,i.unignore=!0),!!t&&(Pt(t,i),!0);s&&("UnionTypeAnnotation"===s.type||"TSUnionType"===s.type)&&X.isNodeIgnoreComment(i)&&(s.types[0].prettierIgnore=!0,i.unignore=!0);return!1}(a,n,o,t)||Lt(n,i,t,r)||function(t,e,s,i,r){if(s&&"ImportSpecifier"===s.type&&e&&"ImportDeclaration"===e.type&&X.hasNewline(t,r.locEnd(i)))return Pt(s,i),!0;return!1}(e,n,a,t,s)||function(t,e){if(t&&"AssignmentPattern"===t.type)return gt(t,e),!0;return!1}(n,t)||Ft(e,n,a,t,s)||vt(n,t)},handleEndOfLineComment:function(t,e,s,i,r){const{precedingNode:a,enclosingNode:n,followingNode:o}=t;return function(t,e){if(t&&Ot(e))return gt(t,e),!0;return!1}(o,t)||kt(e,a,n,o,t,s)||function(t,e,s,i,r,a){const n=e&&!X.hasNewlineInRange(r,a.locEnd(e),a.locStart(i));if((!e||!n)&&t&&"ConditionalExpression"===t.type&&s)return gt(s,i),!0;return!1}(n,a,o,t,e,s)||It(n,t)||At(e,a,n,o,t,s)||wt(e,a,n,o,t,s)||St(n,a,o,t)||Nt(n,a,o,t)||vt(n,t)||function(t,e,s){if(e&&("CallExpression"===e.type||"OptionalCallExpression"===e.type)&&t&&e.callee===t&&e.arguments.length>0)return gt(e.arguments[0],s),!0;return!1}(a,n,t)||function(t,e){if(t&&("Property"===t.type||"ObjectProperty"===t.type))return gt(t,e),!0;return!1}(n,t)||Lt(n,i,t,r)||function(t,e,s){if(t&&"TypeAlias"===t.type)return gt(t,s),!0;return!1}(n,0,t)||function(t,e,s){if(t&&("VariableDeclarator"===t.type||"AssignmentExpression"===t.type)&&e&&("ObjectExpression"===e.type||"ArrayExpression"===e.type||"TemplateLiteral"===e.type||"TaggedTemplateExpression"===e.type||Bt(s)))return gt(e,s),!0;return!1}(n,o,t)},handleRemainingComment:function(t,e,s,i,r){const{precedingNode:a,enclosingNode:n,followingNode:o}=t;return!!(At(e,a,n,o,t,s)||wt(e,a,n,o,t,s)||function(t,e,s){if(t&&("ObjectProperty"===t.type||"Property"===t.type)&&t.shorthand&&t.key===e&&"AssignmentPattern"===t.value.type)return Pt(t.value.left,s),!0;return!1}(n,a,t)||function(t,e,s,i){if(")"!==X.getNextNonSpaceNonCommentCharacter(t,s,i.locEnd))return!1;if(e&&(Mt(e)&&0===(e.params||e.parameters).length||("CallExpression"===e.type||"OptionalCallExpression"===e.type||"NewExpression"===e.type)&&0===e.arguments.length))return Et(e,s),!0;if(e&&"MethodDefinition"===e.type&&0===e.value.params.length)return Et(e.value,s),!0;return!1}(e,n,t,s)||Ft(e,n,a,t,s)||Lt(n,i,t,r)||function(t,e,s,i){if(!e||"ArrowFunctionExpression"!==e.type)return!1;const r=Ct(t,s,i.locEnd);if("=>"===t.slice(r,r+2))return Et(e,s),!0;return!1}(e,n,t,s)||function(t,e,s,i,r){if("("!==X.getNextNonSpaceNonCommentCharacter(t,i,r.locEnd))return!1;if(s&&e&&("FunctionDeclaration"===e.type||"FunctionExpression"===e.type||"ClassMethod"===e.type||"MethodDefinition"===e.type||"ObjectMethod"===e.type))return Pt(s,i),!0;return!1}(e,n,a,t,s)||function(t,e,s,i,r){if(!e||"TSMappedType"!==e.type)return!1;if(i&&"TSTypeParameter"===i.type&&i.name)return gt(i.name,r),!0;if(s&&"TSTypeParameter"===s.type&&s.constraint)return Pt(s.constraint,r),!0;return!1}(0,n,a,o,t)||function(t,e){if(t&&("ContinueStatement"===t.type||"BreakStatement"===t.type)&&!t.label)return Pt(t,e),!0;return!1}(n,t)||function(t,e,s,i,r){if(!s&&e&&("TSMethodSignature"===e.type||"TSDeclareFunction"===e.type||"TSAbstractMethodDefinition"===e.type)&&";"===X.getNextNonSpaceNonCommentCharacter(t,i,r.locEnd))return Pt(e,i),!0;return!1}(e,n,o,t,s))},hasLeadingComment:function(t,e=(()=>!0)){return t.leadingComments?t.leadingComments.some(e):!!t.comments&&t.comments.some(t=>t.leading&&e(t))},isBlockComment:Bt,isTypeCastComment:Ot,getGapRegex:function(t){if(t&&"BinaryExpression"!==t.type&&"LogicalExpression"!==t.type)return/^[\s(&|]*$/},getCommentChildNodes:function(t,e){if(("typescript"===e.parser||"flow"===e.parser)&&"MethodDefinition"===t.type&&t.value&&"FunctionExpression"===t.value.type&&0===t.value.params.length&&!t.value.returnType&&(!t.value.typeParameters||0===t.value.typeParameters.length)&&t.value.body)return[...t.decorators||[],t.key,t.value.body]}};const{getLast:_t,getNextNonSpaceNonCommentCharacter:jt}=X,{composeLoc:Ut,locEnd:qt}=m,{isTypeCastComment:Vt}=Rt;function zt(t,e,s,i){if(!t||"object"!=typeof t)return;if(Array.isArray(t)){for(let s=0;s{t.leadingComments&&t.leadingComments.some(Vt)&&e.add(t.start)}),zt(t,t=>{if("ParenthesizedExpression"===t.type&&!e.has(t.start)){const{expression:e}=t;return e.extra||(e.extra={}),e.extra.parenthesized=!0,e.extra.parenStart=t.start,e}})}return zt(t,t=>{switch(t.type){case"LogicalExpression":if(Ht(t))return function t(e){if(!Ht(e))return e;return t(Object.assign({type:"LogicalExpression",operator:e.operator,left:t(Object.assign({type:"LogicalExpression",operator:e.operator,left:e.left,right:e.right.left},Ut(e.left,e.right.left))),right:e.right.right},Ut(e)))}(t);break;case"VariableDeclaration":{const s=_t(t.declarations);s&&s.init&&function(t,s){if(";"===e.originalText[qt(s)])return;Array.isArray(t.range)?t.range=[t.range[0],s.range[1]]:t.end=s.end;t.loc=Object.assign({},t.loc,{end:t.loc.end})}(t,s);break}case"TSParenthesizedType":return Object.assign({},t.typeAnnotation,{},Ut(t));case"TSUnionType":case"TSIntersectionType":if(1===t.types.length)return Object.assign({},t.types[0],{},Ut(t));break;case"TSTypeParameter":"string"==typeof t.name&&(t.name=Object.assign({type:"Identifier",name:t.name},Ut(t,t.name.length)));break;case"SequenceExpression":t.end&&t.end>_t(t.expressions).end&&(t.end=_t(t.expressions).end);break;case"ClassProperty":t.key&&"TSPrivateIdentifier"===t.key.type&&"?"===jt(e.originalText,t.key,qt)&&(t.optional=!0)}}),t},Kt=i((function(t,e){Object.defineProperty(e,"__esModule",{value:!0});class s{constructor(t,e={}){this.label=t,this.keyword=e.keyword,this.beforeExpr=!!e.beforeExpr,this.startsExpr=!!e.startsExpr,this.rightAssociative=!!e.rightAssociative,this.isLoop=!!e.isLoop,this.isAssign=!!e.isAssign,this.prefix=!!e.prefix,this.postfix=!!e.postfix,this.binop=null!=e.binop?e.binop:null,this.updateContext=null}}const i=new Map;function r(t,e={}){e.keyword=t;const r=new s(t,e);return i.set(t,r),r}function a(t,e){return new s(t,{beforeExpr:!0,binop:e})}const n={num:new s("num",{startsExpr:!0}),bigint:new s("bigint",{startsExpr:!0}),regexp:new s("regexp",{startsExpr:!0}),string:new s("string",{startsExpr:!0}),name:new s("name",{startsExpr:!0}),eof:new s("eof"),bracketL:new s("[",{beforeExpr:!0,startsExpr:!0}),bracketHashL:new s("#[",{beforeExpr:!0,startsExpr:!0}),bracketBarL:new s("[|",{beforeExpr:!0,startsExpr:!0}),bracketR:new s("]"),bracketBarR:new s("|]"),braceL:new s("{",{beforeExpr:!0,startsExpr:!0}),braceBarL:new s("{|",{beforeExpr:!0,startsExpr:!0}),braceHashL:new s("#{",{beforeExpr:!0,startsExpr:!0}),braceR:new s("}"),braceBarR:new s("|}"),parenL:new s("(",{beforeExpr:!0,startsExpr:!0}),parenR:new s(")"),comma:new s(",",{beforeExpr:!0}),semi:new s(";",{beforeExpr:!0}),colon:new s(":",{beforeExpr:!0}),doubleColon:new s("::",{beforeExpr:!0}),dot:new s("."),question:new s("?",{beforeExpr:!0}),questionDot:new s("?."),arrow:new s("=>",{beforeExpr:!0}),template:new s("template"),ellipsis:new s("...",{beforeExpr:!0}),backQuote:new s("`",{startsExpr:!0}),dollarBraceL:new s("${",{beforeExpr:!0,startsExpr:!0}),at:new s("@"),hash:new s("#",{startsExpr:!0}),interpreterDirective:new s("#!..."),eq:new s("=",{beforeExpr:!0,isAssign:!0}),assign:new s("_=",{beforeExpr:!0,isAssign:!0}),incDec:new s("++/--",{prefix:!0,postfix:!0,startsExpr:!0}),bang:new s("!",{beforeExpr:!0,prefix:!0,startsExpr:!0}),tilde:new s("~",{beforeExpr:!0,prefix:!0,startsExpr:!0}),pipeline:a("|>",0),nullishCoalescing:a("??",1),logicalOR:a("||",1),logicalAND:a("&&",2),bitwiseOR:a("|",3),bitwiseXOR:a("^",4),bitwiseAND:a("&",5),equality:a("==/!=/===/!==",6),relational:a("/<=/>=",7),bitShift:a("<>/>>>",8),plusMin:new s("+/-",{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:new s("%",{beforeExpr:!0,binop:10,startsExpr:!0}),star:a("*",10),slash:a("/",10),exponent:new s("**",{beforeExpr:!0,binop:11,rightAssociative:!0}),_break:r("break"),_case:r("case",{beforeExpr:!0}),_catch:r("catch"),_continue:r("continue"),_debugger:r("debugger"),_default:r("default",{beforeExpr:!0}),_do:r("do",{isLoop:!0,beforeExpr:!0}),_else:r("else",{beforeExpr:!0}),_finally:r("finally"),_for:r("for",{isLoop:!0}),_function:r("function",{startsExpr:!0}),_if:r("if"),_return:r("return",{beforeExpr:!0}),_switch:r("switch"),_throw:r("throw",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_try:r("try"),_var:r("var"),_const:r("const"),_while:r("while",{isLoop:!0}),_with:r("with"),_new:r("new",{beforeExpr:!0,startsExpr:!0}),_this:r("this",{startsExpr:!0}),_super:r("super",{startsExpr:!0}),_class:r("class",{startsExpr:!0}),_extends:r("extends",{beforeExpr:!0}),_export:r("export"),_import:r("import",{startsExpr:!0}),_null:r("null",{startsExpr:!0}),_true:r("true",{startsExpr:!0}),_false:r("false",{startsExpr:!0}),_in:r("in",{beforeExpr:!0,binop:7}),_instanceof:r("instanceof",{beforeExpr:!0,binop:7}),_typeof:r("typeof",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:r("void",{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:r("delete",{beforeExpr:!0,prefix:!0,startsExpr:!0})},o=/\r\n?|[\n\u2028\u2029]/,h=new RegExp(o.source,"g");function p(t){switch(t){case 10:case 13:case 8232:case 8233:return!0;default:return!1}}const c=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;function u(t){switch(t){case 9:case 11:case 12:case 32:case 160:case 5760:case 8192:case 8193:case 8194:case 8195:case 8196:case 8197:case 8198:case 8199:case 8200:case 8201:case 8202:case 8239:case 8287:case 12288:case 65279:return!0;default:return!1}}class l{constructor(t,e){this.line=t,this.column=e}}class d{constructor(t,e){this.start=t,this.end=e}}function m(t){return t[t.length-1]}const f=Object.freeze({ArgumentsDisallowedInInitializer:"'arguments' is not allowed in class field initializer",AsyncFunctionInSingleStatementContext:"Async functions can only be declared at the top level or inside a block",AwaitBindingIdentifier:"Can not use 'await' as identifier inside an async function",AwaitExpressionFormalParameter:"await is not allowed in async function parameters",AwaitNotInAsyncFunction:"Can not use keyword 'await' outside an async function",BadGetterArity:"getter must not have any formal parameters",BadSetterArity:"setter must have exactly one formal parameter",BadSetterRestParameter:"setter function argument must not be a rest parameter",ConstructorClassField:"Classes may not have a field named 'constructor'",ConstructorClassPrivateField:"Classes may not have a private field named '#constructor'",ConstructorIsAccessor:"Class constructor may not be an accessor",ConstructorIsAsync:"Constructor can't be an async function",ConstructorIsGenerator:"Constructor can't be a generator",DeclarationMissingInitializer:"%0 require an initialization value",DecoratorBeforeExport:"Decorators must be placed *before* the 'export' keyword. You can set the 'decoratorsBeforeExport' option to false to use the 'export @decorator class {}' syntax",DecoratorConstructor:"Decorators can't be used with a constructor. Did you mean '@dec class { ... }'?",DecoratorExportClass:"Using the export keyword between a decorator and a class is not allowed. Please use `export @dec class` instead.",DecoratorSemicolon:"Decorators must not be followed by a semicolon",DeletePrivateField:"Deleting a private field is not allowed",DestructureNamedImport:"ES2015 named imports do not destructure. Use another statement for destructuring after the import.",DuplicateConstructor:"Duplicate constructor in the same class",DuplicateDefaultExport:"Only one default export allowed per module.",DuplicateExport:"`%0` has already been exported. Exported identifiers must be unique.",DuplicateProto:"Redefinition of __proto__ property",DuplicateRegExpFlags:"Duplicate regular expression flag",ElementAfterRest:"Rest element must be last element",EscapedCharNotAnIdentifier:"Invalid Unicode escape",ForInOfLoopInitializer:"%0 loop variable declaration may not have an initializer",GeneratorInSingleStatementContext:"Generators can only be declared at the top level or inside a block",IllegalBreakContinue:"Unsyntactic %0",IllegalLanguageModeDirective:"Illegal 'use strict' directive in function with non-simple parameter list",IllegalReturn:"'return' outside of function",ImportCallArgumentTrailingComma:"Trailing comma is disallowed inside import(...) arguments",ImportCallArity:"import() requires exactly one argument",ImportCallArityLtOne:"Dynamic imports require a parameter: import('a.js')",ImportCallNotNewExpression:"Cannot use new with import(...)",ImportCallSpreadArgument:"... is not allowed in import()",ImportMetaOutsideModule:"import.meta may appear only with 'sourceType: \"module\"'",ImportOutsideModule:"'import' and 'export' may appear only with 'sourceType: \"module\"'",InvalidCodePoint:"Code point out of bounds",InvalidDigit:"Expected number in radix %0",InvalidEscapeSequence:"Bad character escape sequence",InvalidEscapeSequenceTemplate:"Invalid escape sequence in template",InvalidEscapedReservedWord:"Escape sequence in keyword %0",InvalidIdentifier:"Invalid identifier %0",InvalidLhs:"Invalid left-hand side in %0",InvalidLhsBinding:"Binding invalid left-hand side in %0",InvalidNumber:"Invalid number",InvalidOrUnexpectedToken:"Unexpected character '%0'",InvalidParenthesizedAssignment:"Invalid parenthesized assignment pattern",InvalidPrivateFieldResolution:"Private name #%0 is not defined",InvalidPropertyBindingPattern:"Binding member expression",InvalidRestAssignmentPattern:"Invalid rest operator's argument",LabelRedeclaration:"Label '%0' is already declared",LetInLexicalBinding:"'let' is not allowed to be used as a name in 'let' or 'const' declarations.",MalformedRegExpFlags:"Invalid regular expression flag",MissingClassName:"A class name is required",MissingEqInAssignment:"Only '=' operator can be used for specifying default value.",MissingUnicodeEscape:"Expecting Unicode escape sequence \\uXXXX",MixingCoalesceWithLogical:"Nullish coalescing operator(??) requires parens when mixing with logical operators",ModuleExportUndefined:"Export '%0' is not defined",MultipleDefaultsInSwitch:"Multiple default clauses",NewlineAfterThrow:"Illegal newline after throw",NoCatchOrFinally:"Missing catch or finally clause",NumberIdentifier:"Identifier directly after number",NumericSeparatorInEscapeSequence:"Numeric separators are not allowed inside unicode escape sequences or hex escape sequences",ObsoleteAwaitStar:"await* has been removed from the async functions proposal. Use Promise.all() instead.",OptionalChainingNoNew:"constructors in/after an Optional Chain are not allowed",OptionalChainingNoTemplate:"Tagged Template Literals are not allowed in optionalChain",ParamDupe:"Argument name clash",PatternHasAccessor:"Object pattern can't contain getter or setter",PatternHasMethod:"Object pattern can't contain methods",PipelineBodyNoArrow:'Unexpected arrow "=>" after pipeline body; arrow function in pipeline body must be parenthesized',PipelineBodySequenceExpression:"Pipeline body may not be a comma-separated sequence expression",PipelineHeadSequenceExpression:"Pipeline head should not be a comma-separated sequence expression",PipelineTopicUnused:"Pipeline is in topic style but does not use topic reference",PrimaryTopicNotAllowed:"Topic reference was used in a lexical context without topic binding",PrimaryTopicRequiresSmartPipeline:"Primary Topic Reference found but pipelineOperator not passed 'smart' for 'proposal' option.",PrivateNameRedeclaration:"Duplicate private name #%0",RecordExpressionBarIncorrectEndSyntaxType:"Record expressions ending with '|}' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",RecordExpressionBarIncorrectStartSyntaxType:"Record expressions starting with '{|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",RecordExpressionHashIncorrectStartSyntaxType:"Record expressions starting with '#{' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",RestTrailingComma:"Unexpected trailing comma after rest element",SloppyFunction:"In non-strict mode code, functions can only be declared at top level, inside a block, or as the body of an if statement",StaticPrototype:"Classes may not have static property named prototype",StrictDelete:"Deleting local variable in strict mode",StrictEvalArguments:"Assigning to '%0' in strict mode",StrictEvalArgumentsBinding:"Binding '%0' in strict mode",StrictFunction:"In strict mode code, functions can only be declared at top level or inside a block",StrictOctalLiteral:"Legacy octal literals are not allowed in strict mode",StrictWith:"'with' in strict mode",SuperNotAllowed:"super() is only valid inside a class constructor of a subclass. Maybe a typo in the method name ('constructor') or not extending another class?",SuperPrivateField:"Private fields can't be accessed on super",TrailingDecorator:"Decorators must be attached to a class element",TupleExpressionBarIncorrectEndSyntaxType:"Tuple expressions ending with '|]' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",TupleExpressionBarIncorrectStartSyntaxType:"Tuple expressions starting with '[|' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'bar'",TupleExpressionHashIncorrectStartSyntaxType:"Tuple expressions starting with '#[' are only allowed when the 'syntaxType' option of the 'recordAndTuple' plugin is set to 'hash'",UnexpectedArgumentPlaceholder:"Unexpected argument placeholder",UnexpectedAwaitAfterPipelineBody:'Unexpected "await" after pipeline body; await must have parentheses in minimal proposal',UnexpectedDigitAfterHash:"Unexpected digit after hash token",UnexpectedImportExport:"'import' and 'export' may only appear at the top level",UnexpectedKeyword:"Unexpected keyword '%0'",UnexpectedLeadingDecorator:"Leading decorators must be attached to a class declaration",UnexpectedLexicalDeclaration:"Lexical declaration cannot appear in a single-statement context",UnexpectedNewTarget:"new.target can only be used in functions",UnexpectedNumericSeparator:"A numeric separator is only allowed between two digits",UnexpectedPrivateField:"Private names can only be used as the name of a class element (i.e. class C { #p = 42; #m() {} } )\n or a property of member expression (i.e. this.#p).",UnexpectedReservedWord:"Unexpected reserved word '%0'",UnexpectedSuper:"super is only allowed in object methods and classes",UnexpectedToken:"Unexpected token '%'",UnexpectedTokenUnaryExponentiation:"Illegal expression. Wrap left hand side or entire exponentiation in parentheses.",UnsupportedBind:"Binding should be performed on object property.",UnsupportedDecoratorExport:"A decorated export must export a class declaration",UnsupportedDefaultExport:"Only expressions, functions or classes are allowed as the `default` export.",UnsupportedImport:"import can only be used in import() or import.meta",UnsupportedMetaProperty:"The only valid meta property for %0 is %0.%1",UnsupportedParameterDecorator:"Decorators cannot be used to decorate parameters",UnsupportedPropertyDecorator:"Decorators cannot be used to decorate object literal properties",UnsupportedSuper:"super can only be used with function calls (i.e. super()) or in property accesses (i.e. super.prop or super[prop])",UnterminatedComment:"Unterminated comment",UnterminatedRegExp:"Unterminated regular expression",UnterminatedString:"Unterminated string constant",UnterminatedTemplate:"Unterminated template",VarRedeclaration:"Identifier '%0' has already been declared",YieldBindingIdentifier:"Can not use 'yield' as identifier inside a generator",YieldInParameter:"yield is not allowed in generator parameters",ZeroDigitNumericSeparator:"Numeric separator can not be used after leading 0"});function D(t){return null!=t&&"Property"===t.type&&"init"===t.kind&&!1===t.method}class y{constructor(t,e,s,i){this.token=t,this.isExpr=!!e,this.preserveSpace=!!s,this.override=i}}const x={braceStatement:new y("{",!1),braceExpression:new y("{",!0),templateQuasi:new y("${",!1),parenStatement:new y("(",!1),parenExpression:new y("(",!0),template:new y("`",!0,!0,t=>t.readTmplToken()),functionExpression:new y("function",!0),functionStatement:new y("function",!1)};n.parenR.updateContext=n.braceR.updateContext=function(){if(1===this.state.context.length)return void(this.state.exprAllowed=!0);let t=this.state.context.pop();t===x.braceStatement&&"function"===this.curContext().token&&(t=this.state.context.pop()),this.state.exprAllowed=!t.isExpr},n.name.updateContext=function(t){let e=!1;t!==n.dot&&("of"===this.state.value&&!this.state.exprAllowed||"yield"===this.state.value&&this.prodParam.hasYield)&&(e=!0),this.state.exprAllowed=e,this.state.isIterator&&(this.state.isIterator=!1)},n.braceL.updateContext=function(t){this.state.context.push(this.braceIsBlock(t)?x.braceStatement:x.braceExpression),this.state.exprAllowed=!0},n.dollarBraceL.updateContext=function(){this.state.context.push(x.templateQuasi),this.state.exprAllowed=!0},n.parenL.updateContext=function(t){const e=t===n._if||t===n._for||t===n._with||t===n._while;this.state.context.push(e?x.parenStatement:x.parenExpression),this.state.exprAllowed=!0},n.incDec.updateContext=function(){},n._function.updateContext=n._class.updateContext=function(t){!t.beforeExpr||t===n.semi||t===n._else||t===n._return&&o.test(this.input.slice(this.state.lastTokEnd,this.state.start))||(t===n.colon||t===n.braceL)&&this.curContext()===x.b_stat?this.state.context.push(x.functionStatement):this.state.context.push(x.functionExpression),this.state.exprAllowed=!1},n.backQuote.updateContext=function(){this.curContext()===x.template?this.state.context.pop():this.state.context.push(x.template),this.state.exprAllowed=!1};let g="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ",P="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";const E=new RegExp("["+g+"]"),C=new RegExp("["+g+P+"]");g=P=null;const b=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938],T=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function A(t,e){let s=65536;for(let i=0,r=e.length;it)return!1;if(s+=e[i+1],s>=t)return!0}return!1}function w(t){return t<65?36===t:t<=90||(t<97?95===t:t<=122||(t<=65535?t>=170&&E.test(String.fromCharCode(t)):A(t,b)))}function S(t){return t<48?36===t:t<58||!(t<65)&&(t<=90||(t<97?95===t:t<=122||(t<=65535?t>=170&&C.test(String.fromCharCode(t)):A(t,b)||A(t,T))))}const N=["implements","interface","let","package","private","protected","public","static","yield"],F=["eval","arguments"],k=new Set(["break","case","catch","continue","debugger","default","do","else","finally","for","function","if","return","switch","throw","try","var","const","while","with","new","this","super","class","extends","export","import","null","true","false","in","instanceof","typeof","void","delete"]),I=new Set(N),v=new Set(F);function L(t,e){return e&&"await"===t||"enum"===t}function B(t,e){return L(t,e)||I.has(t)}function M(t){return v.has(t)}function O(t,e){return B(t,e)||M(t)}const R=/^in(stanceof)?$/;const _=new Set(["_","any","bool","boolean","empty","extends","false","interface","mixed","null","number","static","string","true","typeof","void"]),j=Object.freeze({AmbiguousConditionalArrow:"Ambiguous expression: wrap the arrow functions in parentheses to disambiguate.",AmbiguousDeclareModuleKind:"Found both `declare module.exports` and `declare export` in the same module. Modules can only have 1 since they are either an ES module or they are a CommonJS module",AssignReservedType:"Cannot overwrite reserved type %0",DeclareClassElement:"The `declare` modifier can only appear on class fields.",DeclareClassFieldInitializer:"Initializers are not allowed in fields with the `declare` modifier.",DuplicateDeclareModuleExports:"Duplicate `declare module.exports` statement",EnumBooleanMemberNotInitialized:"Boolean enum members need to be initialized. Use either `%0 = true,` or `%0 = false,` in enum `%1`.",EnumDuplicateMemberName:"Enum member names need to be unique, but the name `%0` has already been used before in enum `%1`.",EnumInconsistentMemberValues:"Enum `%0` has inconsistent member initializers. Either use no initializers, or consistently use literals (either booleans, numbers, or strings) for all member initializers.",EnumInvalidExplicitType:"Enum type `%1` is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",EnumInvalidExplicitTypeUnknownSupplied:"Supplied enum type is not valid. Use one of `boolean`, `number`, `string`, or `symbol` in enum `%0`.",EnumInvalidMemberInitializerPrimaryType:"Enum `%0` has type `%2`, so the initializer of `%1` needs to be a %2 literal.",EnumInvalidMemberInitializerSymbolType:"Symbol enum members cannot be initialized. Use `%1,` in enum `%0`.",EnumInvalidMemberInitializerUnknownType:"The enum member initializer for `%1` needs to be a literal (either a boolean, number, or string) in enum `%0`.",EnumInvalidMemberName:"Enum member names cannot start with lowercase 'a' through 'z'. Instead of using `%0`, consider using `%1`, in enum `%2`.",EnumNumberMemberNotInitialized:"Number enum members need to be initialized, e.g. `%1 = 1` in enum `%0`.",EnumStringMemberInconsistentlyInitailized:"String enum members need to consistently either all use initializers, or use no initializers, in enum `%0`.",ImportTypeShorthandOnlyInPureImport:"The `type` and `typeof` keywords on named imports can only be used on regular `import` statements. It cannot be used with `import type` or `import typeof` statements",InexactInsideExact:"Explicit inexact syntax cannot appear inside an explicit exact object type",InexactInsideNonObject:"Explicit inexact syntax cannot appear in class or interface definitions",InexactVariance:"Explicit inexact syntax cannot have variance",InvalidNonTypeImportInDeclareModule:"Imports within a `declare module` body must always be `import type` or `import typeof`",MissingTypeParamDefault:"Type parameter declaration needs a default, since a preceding type parameter declaration has a default.",NestedDeclareModule:"`declare module` cannot be used inside another `declare module`",NestedFlowComment:"Cannot have a flow comment inside another flow comment",OptionalBindingPattern:"A binding pattern parameter cannot be optional in an implementation signature.",SpreadVariance:"Spread properties cannot have variance",TypeBeforeInitializer:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",TypeCastInPattern:"The type cast expression is expected to be wrapped with parenthesis",UnexpectedExplicitInexactInObject:"Explicit inexact syntax must appear at the end of an inexact object",UnexpectedReservedType:"Unexpected reserved type %0",UnexpectedReservedUnderscore:"`_` is only allowed as a type argument to call or new",UnexpectedSpaceBetweenModuloChecks:"Spaces between `%` and `checks` are not allowed here.",UnexpectedSpreadType:"Spread operator cannot appear in class or interface definitions",UnexpectedSubtractionOperand:'Unexpected token, expected "number" or "bigint"',UnexpectedTokenAfterTypeParameter:"Expected an arrow function after this type parameter declaration",UnsupportedDeclareExportKind:"`declare export %0` is not supported. Use `%1` instead",UnsupportedStatementInDeclareModule:"Only declares and type imports are allowed inside declare module",UnterminatedFlowComment:"Unterminated flow-comment"});function U(t){return"type"===t.importKind||"typeof"===t.importKind}function q(t){return(t.type===n.name||!!t.type.keyword)&&"from"!==t.value}const V={const:"declare export var",let:"declare export var",type:"export type",interface:"export interface"};const z=/\*?\s*@((?:no)?flow)\b/;const H={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"­",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"‌",zwj:"‍",lrm:"‎",rlm:"‏",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪",int:"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"},W=/^[\da-fA-F]+$/,K=/^\d+$/,J=Object.freeze({AttributeIsEmpty:"JSX attributes must only be assigned a non-empty expression",MissingClosingTagFragment:"Expected corresponding JSX closing tag for <>",MissingClosingTagElement:"Expected corresponding JSX closing tag for <%0>",UnsupportedJsxValue:"JSX value should be either an expression or a quoted JSX text",UnterminatedJsxContent:"Unterminated JSX contents",UnwrappedAdjacentJSXElements:"Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...?"});function X(t){return!!t&&("JSXOpeningFragment"===t.type||"JSXClosingFragment"===t.type)}function G(t){if("JSXIdentifier"===t.type)return t.name;if("JSXNamespacedName"===t.type)return t.namespace.name+":"+t.name.name;if("JSXMemberExpression"===t.type)return G(t.object)+"."+G(t.property);throw new Error("Node had unexpected type: "+t.type)}x.j_oTag=new y("...",!0,!0),n.jsxName=new s("jsxName"),n.jsxText=new s("jsxText",{beforeExpr:!0}),n.jsxTagStart=new s("jsxTagStart",{startsExpr:!0}),n.jsxTagEnd=new s("jsxTagEnd"),n.jsxTagStart.updateContext=function(){this.state.context.push(x.j_expr),this.state.context.push(x.j_oTag),this.state.exprAllowed=!1},n.jsxTagEnd.updateContext=function(t){const e=this.state.context.pop();e===x.j_oTag&&t===n.slash||e===x.j_cTag?(this.state.context.pop(),this.state.exprAllowed=this.curContext()===x.j_expr):this.state.exprAllowed=!0};class Q{constructor(t){this.var=[],this.lexical=[],this.functions=[],this.flags=t}}class Y{constructor(t,e){this.scopeStack=[],this.undefinedExports=new Map,this.undefinedPrivateNames=new Map,this.raise=t,this.inModule=e}get inFunction(){return(2&this.currentVarScope().flags)>0}get allowSuper(){return(16&this.currentThisScope().flags)>0}get allowDirectSuper(){return(32&this.currentThisScope().flags)>0}get inClass(){return(64&this.currentThisScope().flags)>0}get inNonArrowFunction(){return(2&this.currentThisScope().flags)>0}get treatFunctionsAsVar(){return this.treatFunctionsAsVarInScope(this.currentScope())}createScope(t){return new Q(t)}enter(t){this.scopeStack.push(this.createScope(t))}exit(){this.scopeStack.pop()}treatFunctionsAsVarInScope(t){return!!(2&t.flags||!this.inModule&&1&t.flags)}declareName(t,e,s){let i=this.currentScope();if(8&e||16&e)this.checkRedeclarationInScope(i,t,e,s),16&e?i.functions.push(t):i.lexical.push(t),8&e&&this.maybeExportDefined(i,t);else if(4&e)for(let r=this.scopeStack.length-1;r>=0&&(i=this.scopeStack[r],this.checkRedeclarationInScope(i,t,e,s),i.var.push(t),this.maybeExportDefined(i,t),!(131&i.flags));--r);this.inModule&&1&i.flags&&this.undefinedExports.delete(t)}maybeExportDefined(t,e){this.inModule&&1&t.flags&&this.undefinedExports.delete(e)}checkRedeclarationInScope(t,e,s,i){this.isRedeclaredInScope(t,e,s)&&this.raise(i,f.VarRedeclaration,e)}isRedeclaredInScope(t,e,s){return!!(1&s)&&(8&s?t.lexical.indexOf(e)>-1||t.functions.indexOf(e)>-1||t.var.indexOf(e)>-1:16&s?t.lexical.indexOf(e)>-1||!this.treatFunctionsAsVarInScope(t)&&t.var.indexOf(e)>-1:t.lexical.indexOf(e)>-1&&!(8&t.flags&&t.lexical[0]===e)||!this.treatFunctionsAsVarInScope(t)&&t.functions.indexOf(e)>-1)}checkLocalExport(t){-1===this.scopeStack[0].lexical.indexOf(t.name)&&-1===this.scopeStack[0].var.indexOf(t.name)&&-1===this.scopeStack[0].functions.indexOf(t.name)&&this.undefinedExports.set(t.name,t.start)}currentScope(){return this.scopeStack[this.scopeStack.length-1]}currentVarScope(){for(let t=this.scopeStack.length-1;;t--){const e=this.scopeStack[t];if(131&e.flags)return e}}currentThisScope(){for(let t=this.scopeStack.length-1;;t--){const e=this.scopeStack[t];if((131&e.flags||64&e.flags)&&!(4&e.flags))return e}}}class $ extends Q{constructor(...t){super(...t),this.types=[],this.enums=[],this.constEnums=[],this.classes=[],this.exportOnlyBindings=[]}}class Z extends Y{createScope(t){return new $(t)}declareName(t,e,s){const i=this.currentScope();if(1024&e)return this.maybeExportDefined(i,t),void i.exportOnlyBindings.push(t);super.declareName(...arguments),2&e&&(1&e||(this.checkRedeclarationInScope(i,t,e,s),this.maybeExportDefined(i,t)),i.types.push(t)),256&e&&i.enums.push(t),512&e&&i.constEnums.push(t),128&e&&i.classes.push(t)}isRedeclaredInScope(t,e,s){if(t.enums.indexOf(e)>-1){if(256&s){return!!(512&s)!==t.constEnums.indexOf(e)>-1}return!0}return 128&s&&t.classes.indexOf(e)>-1?t.lexical.indexOf(e)>-1&&!!(1&s):!!(2&s&&t.types.indexOf(e)>-1)||super.isRedeclaredInScope(...arguments)}checkLocalExport(t){-1===this.scopeStack[0].types.indexOf(t.name)&&-1===this.scopeStack[0].exportOnlyBindings.indexOf(t.name)&&super.checkLocalExport(t)}}class tt{constructor(){this.stacks=[]}enter(t){this.stacks.push(t)}exit(){this.stacks.pop()}currentFlags(){return this.stacks[this.stacks.length-1]}get hasAwait(){return(2&this.currentFlags())>0}get hasYield(){return(1&this.currentFlags())>0}get hasReturn(){return(4&this.currentFlags())>0}}function et(t,e){return(t?2:0)|(e?1:0)}function st(t){if(null==t)throw new Error("Unexpected ".concat(t," value."));return t}function it(t){if(!t)throw new Error("Assert fail")}const rt=Object.freeze({ClassMethodHasDeclare:"Class methods cannot have the 'declare' modifier",ClassMethodHasReadonly:"Class methods cannot have the 'readonly' modifier",DeclareClassFieldHasInitializer:"'declare' class fields cannot have an initializer",DuplicateModifier:"Duplicate modifier: '%0'",EmptyHeritageClauseType:"'%0' list cannot be empty.",IndexSignatureHasAbstract:"Index signatures cannot have the 'abstract' modifier",IndexSignatureHasAccessibility:"Index signatures cannot have an accessibility modifier ('%0')",IndexSignatureHasStatic:"Index signatures cannot have the 'static' modifier",OptionalTypeBeforeRequired:"A required element cannot follow an optional element.",PatternIsOptional:"A binding pattern parameter cannot be optional in an implementation signature.",PrivateElementHasAbstract:"Private elements cannot have the 'abstract' modifier.",PrivateElementHasAccessibility:"Private elements cannot have an accessibility modifier ('%0')",TemplateTypeHasSubstitution:"Template literal types cannot have any substitution",TypeAnnotationAfterAssign:"Type annotations must come before default assignments, e.g. instead of `age = 25: number` use `age: number = 25`",UnexpectedReadonly:"'readonly' type modifier is only permitted on array and tuple literal types.",UnexpectedTypeAnnotation:"Did not expect a type annotation here.",UnexpectedTypeCastInParameter:"Unexpected type cast in parameter position.",UnsupportedImportTypeArgument:"Argument in a type import must be a string literal",UnsupportedParameterPropertyKind:"A parameter property may not be declared using a binding pattern.",UnsupportedSignatureParameterKind:"Name in a signature must be an Identifier, ObjectPattern or ArrayPattern, instead got %0"});n.placeholder=new s("%%",{startsExpr:!0});function at(t,e){return t.some(t=>Array.isArray(t)?t[0]===e:t===e)}function nt(t,e,s){const i=t.find(t=>Array.isArray(t)?t[0]===e:t===e);return i&&Array.isArray(i)?i[1][s]:null}const ot=["minimal","smart","fsharp"],ht=["hash","bar"];const pt={estree:t=>class extends t{estreeParseRegExpLiteral({pattern:t,flags:e}){let s=null;try{s=new RegExp(t,e)}catch(t){}const i=this.estreeParseLiteral(s);return i.regex={pattern:t,flags:e},i}estreeParseBigIntLiteral(t){const e="undefined"!=typeof BigInt?BigInt(t):null,s=this.estreeParseLiteral(e);return s.bigint=String(s.value||t),s}estreeParseLiteral(t){return this.parseLiteral(t,"Literal")}directiveToStmt(t){const e=t.value,s=this.startNodeAt(t.start,t.loc.start),i=this.startNodeAt(e.start,e.loc.start);return i.value=e.value,i.raw=e.extra.raw,s.expression=this.finishNodeAt(i,"Literal",e.end,e.loc.end),s.directive=e.extra.raw.slice(1,-1),this.finishNodeAt(s,"ExpressionStatement",t.end,t.loc.end)}initFunction(t,e){super.initFunction(t,e),t.expression=!1}checkDeclaration(t){D(t)?this.checkDeclaration(t.value):super.checkDeclaration(t)}checkGetterSetterParams(t){const e=t,s="get"===e.kind?0:1,i=e.start;e.value.params.length!==s?"get"===t.kind?this.raise(i,f.BadGetterArity):this.raise(i,f.BadSetterArity):"set"===e.kind&&"RestElement"===e.value.params[0].type&&this.raise(i,f.BadSetterRestParameter)}checkLVal(t,e=64,s,i,r){switch(t.type){case"ObjectPattern":t.properties.forEach(t=>{this.checkLVal("Property"===t.type?t.value:t,e,s,"object destructuring pattern",r)});break;default:super.checkLVal(t,e,s,i,r)}}checkDuplicatedProto(t,e,s){if("SpreadElement"===t.type||t.computed||t.method||t.shorthand)return;const i=t.key;"__proto__"===("Identifier"===i.type?i.name:String(i.value))&&"init"===t.kind&&(e.used&&(s&&-1===s.doubleProto?s.doubleProto=i.start:this.raise(i.start,f.DuplicateProto)),e.used=!0)}isValidDirective(t){return!("ExpressionStatement"!==t.type||"Literal"!==t.expression.type||"string"!=typeof t.expression.value||t.expression.extra&&t.expression.extra.parenthesized)}stmtToDirective(t){const e=super.stmtToDirective(t),s=t.expression.value;return e.value.value=s,e}parseBlockBody(t,e,s,i){super.parseBlockBody(t,e,s,i);const r=t.directives.map(t=>this.directiveToStmt(t));t.body=r.concat(t.body),delete t.directives}pushClassMethod(t,e,s,i,r,a){this.parseMethod(e,s,i,r,a,"ClassMethod",!0),e.typeParameters&&(e.value.typeParameters=e.typeParameters,delete e.typeParameters),t.body.push(e)}parseExprAtom(t){switch(this.state.type){case n.num:case n.string:return this.estreeParseLiteral(this.state.value);case n.regexp:return this.estreeParseRegExpLiteral(this.state.value);case n.bigint:return this.estreeParseBigIntLiteral(this.state.value);case n._null:return this.estreeParseLiteral(null);case n._true:return this.estreeParseLiteral(!0);case n._false:return this.estreeParseLiteral(!1);default:return super.parseExprAtom(t)}}parseLiteral(t,e,s,i){const r=super.parseLiteral(t,e,s,i);return r.raw=r.extra.raw,delete r.extra,r}parseFunctionBody(t,e,s=!1){super.parseFunctionBody(t,e,s),t.expression="BlockStatement"!==t.body.type}parseMethod(t,e,s,i,r,a,n=!1){let o=this.startNode();return o.kind=t.kind,o=super.parseMethod(o,e,s,i,r,a,n),o.type="FunctionExpression",delete o.kind,t.value=o,a="ClassMethod"===a?"MethodDefinition":a,this.finishNode(t,a)}parseObjectMethod(t,e,s,i,r){const a=super.parseObjectMethod(t,e,s,i,r);return a&&(a.type="Property","method"===a.kind&&(a.kind="init"),a.shorthand=!1),a}parseObjectProperty(t,e,s,i,r){const a=super.parseObjectProperty(t,e,s,i,r);return a&&(a.kind="init",a.type="Property"),a}toAssignable(t){return D(t)?(this.toAssignable(t.value),t):super.toAssignable(t)}toAssignableObjectExpressionProp(t,e){if("get"===t.kind||"set"===t.kind)throw this.raise(t.key.start,f.PatternHasAccessor);if(t.method)throw this.raise(t.key.start,f.PatternHasMethod);super.toAssignableObjectExpressionProp(t,e)}finishCallExpression(t,e){return super.finishCallExpression(t,e),"Import"===t.callee.type&&(t.type="ImportExpression",t.source=t.arguments[0],delete t.arguments,delete t.callee),t}toReferencedListDeep(t,e){t&&super.toReferencedListDeep(t,e)}parseExport(t){switch(super.parseExport(t),t.type){case"ExportAllDeclaration":t.exported=null;break;case"ExportNamedDeclaration":1===t.specifiers.length&&"ExportNamespaceSpecifier"===t.specifiers[0].type&&(t.type="ExportAllDeclaration",t.exported=t.specifiers[0].exported,delete t.specifiers)}return t}},jsx:t=>class extends t{jsxReadToken(){let t="",e=this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,J.UnterminatedJsxContent);const s=this.input.charCodeAt(this.state.pos);switch(s){case 60:case 123:return this.state.pos===this.state.start?60===s&&this.state.exprAllowed?(++this.state.pos,this.finishToken(n.jsxTagStart)):super.getTokenFromCode(s):(t+=this.input.slice(e,this.state.pos),this.finishToken(n.jsxText,t));case 38:t+=this.input.slice(e,this.state.pos),t+=this.jsxReadEntity(),e=this.state.pos;break;default:p(s)?(t+=this.input.slice(e,this.state.pos),t+=this.jsxReadNewLine(!0),e=this.state.pos):++this.state.pos}}}jsxReadNewLine(t){const e=this.input.charCodeAt(this.state.pos);let s;return++this.state.pos,13===e&&10===this.input.charCodeAt(this.state.pos)?(++this.state.pos,s=t?"\n":"\r\n"):s=String.fromCharCode(e),++this.state.curLine,this.state.lineStart=this.state.pos,s}jsxReadString(t){let e="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,f.UnterminatedString);const i=this.input.charCodeAt(this.state.pos);if(i===t)break;38===i?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadEntity(),s=this.state.pos):p(i)?(e+=this.input.slice(s,this.state.pos),e+=this.jsxReadNewLine(!1),s=this.state.pos):++this.state.pos}return e+=this.input.slice(s,this.state.pos++),this.finishToken(n.string,e)}jsxReadEntity(){let t,e="",s=0,i=this.input[this.state.pos];const r=++this.state.pos;for(;this.state.posclass extends t{constructor(t,e){super(t,e),this.flowPragma=void 0}shouldParseTypes(){return this.getPluginOption("flow","all")||"flow"===this.flowPragma}shouldParseEnums(){return!!this.getPluginOption("flow","enums")}finishToken(t,e){return t!==n.string&&t!==n.semi&&t!==n.interpreterDirective&&void 0===this.flowPragma&&(this.flowPragma=null),super.finishToken(t,e)}addComment(t){if(void 0===this.flowPragma){const e=z.exec(t.value);if(e)if("flow"===e[1])this.flowPragma="flow";else{if("noflow"!==e[1])throw new Error("Unexpected flow pragma");this.flowPragma="noflow"}else;}return super.addComment(t)}flowParseTypeInitialiser(t){const e=this.state.inType;this.state.inType=!0,this.expect(t||n.colon);const s=this.flowParseType();return this.state.inType=e,s}flowParsePredicate(){const t=this.startNode(),e=this.state.startLoc,s=this.state.start;this.expect(n.modulo);const i=this.state.startLoc;return this.expectContextual("checks"),e.line===i.line&&e.column===i.column-1||this.raise(s,j.UnexpectedSpaceBetweenModuloChecks),this.eat(n.parenL)?(t.value=this.parseExpression(),this.expect(n.parenR),this.finishNode(t,"DeclaredPredicate")):this.finishNode(t,"InferredPredicate")}flowParseTypeAndPredicateInitialiser(){const t=this.state.inType;this.state.inType=!0,this.expect(n.colon);let e=null,s=null;return this.match(n.modulo)?(this.state.inType=t,s=this.flowParsePredicate()):(e=this.flowParseType(),this.state.inType=t,this.match(n.modulo)&&(s=this.flowParsePredicate())),[e,s]}flowParseDeclareClass(t){return this.next(),this.flowParseInterfaceish(t,!0),this.finishNode(t,"DeclareClass")}flowParseDeclareFunction(t){this.next();const e=t.id=this.parseIdentifier(),s=this.startNode(),i=this.startNode();this.isRelational("<")?s.typeParameters=this.flowParseTypeParameterDeclaration():s.typeParameters=null,this.expect(n.parenL);const r=this.flowParseFunctionTypeParams();return s.params=r.params,s.rest=r.rest,this.expect(n.parenR),[s.returnType,t.predicate]=this.flowParseTypeAndPredicateInitialiser(),i.typeAnnotation=this.finishNode(s,"FunctionTypeAnnotation"),e.typeAnnotation=this.finishNode(i,"TypeAnnotation"),this.resetEndLocation(e),this.semicolon(),this.finishNode(t,"DeclareFunction")}flowParseDeclare(t,e){if(this.match(n._class))return this.flowParseDeclareClass(t);if(this.match(n._function))return this.flowParseDeclareFunction(t);if(this.match(n._var))return this.flowParseDeclareVariable(t);if(this.eatContextual("module"))return this.match(n.dot)?this.flowParseDeclareModuleExports(t):(e&&this.raise(this.state.lastTokStart,j.NestedDeclareModule),this.flowParseDeclareModule(t));if(this.isContextual("type"))return this.flowParseDeclareTypeAlias(t);if(this.isContextual("opaque"))return this.flowParseDeclareOpaqueType(t);if(this.isContextual("interface"))return this.flowParseDeclareInterface(t);if(this.match(n._export))return this.flowParseDeclareExportDeclaration(t,e);throw this.unexpected()}flowParseDeclareVariable(t){return this.next(),t.id=this.flowParseTypeAnnotatableIdentifier(!0),this.scope.declareName(t.id.name,5,t.id.start),this.semicolon(),this.finishNode(t,"DeclareVariable")}flowParseDeclareModule(t){this.scope.enter(0),this.match(n.string)?t.id=this.parseExprAtom():t.id=this.parseIdentifier();const e=t.body=this.startNode(),s=e.body=[];for(this.expect(n.braceL);!this.match(n.braceR);){let t=this.startNode();this.match(n._import)?(this.next(),this.isContextual("type")||this.match(n._typeof)||this.raise(this.state.lastTokStart,j.InvalidNonTypeImportInDeclareModule),this.parseImport(t)):(this.expectContextual("declare",j.UnsupportedStatementInDeclareModule),t=this.flowParseDeclare(t,!0)),s.push(t)}this.scope.exit(),this.expect(n.braceR),this.finishNode(e,"BlockStatement");let i=null,r=!1;return s.forEach(t=>{!function(t){return"DeclareExportAllDeclaration"===t.type||"DeclareExportDeclaration"===t.type&&(!t.declaration||"TypeAlias"!==t.declaration.type&&"InterfaceDeclaration"!==t.declaration.type)}(t)?"DeclareModuleExports"===t.type&&(r&&this.raise(t.start,j.DuplicateDeclareModuleExports),"ES"===i&&this.raise(t.start,j.AmbiguousDeclareModuleKind),i="CommonJS",r=!0):("CommonJS"===i&&this.raise(t.start,j.AmbiguousDeclareModuleKind),i="ES")}),t.kind=i||"CommonJS",this.finishNode(t,"DeclareModule")}flowParseDeclareExportDeclaration(t,e){if(this.expect(n._export),this.eat(n._default))return this.match(n._function)||this.match(n._class)?t.declaration=this.flowParseDeclare(this.startNode()):(t.declaration=this.flowParseType(),this.semicolon()),t.default=!0,this.finishNode(t,"DeclareExportDeclaration");if(this.match(n._const)||this.isLet()||(this.isContextual("type")||this.isContextual("interface"))&&!e){const t=this.state.value,e=V[t];throw this.raise(this.state.start,j.UnsupportedDeclareExportKind,t,e)}if(this.match(n._var)||this.match(n._function)||this.match(n._class)||this.isContextual("opaque"))return t.declaration=this.flowParseDeclare(this.startNode()),t.default=!1,this.finishNode(t,"DeclareExportDeclaration");if(this.match(n.star)||this.match(n.braceL)||this.isContextual("interface")||this.isContextual("type")||this.isContextual("opaque"))return"ExportNamedDeclaration"===(t=this.parseExport(t)).type&&(t.type="ExportDeclaration",t.default=!1,delete t.exportKind),t.type="Declare"+t.type,t;throw this.unexpected()}flowParseDeclareModuleExports(t){return this.next(),this.expectContextual("exports"),t.typeAnnotation=this.flowParseTypeAnnotation(),this.semicolon(),this.finishNode(t,"DeclareModuleExports")}flowParseDeclareTypeAlias(t){return this.next(),this.flowParseTypeAlias(t),t.type="DeclareTypeAlias",t}flowParseDeclareOpaqueType(t){return this.next(),this.flowParseOpaqueType(t,!0),t.type="DeclareOpaqueType",t}flowParseDeclareInterface(t){return this.next(),this.flowParseInterfaceish(t),this.finishNode(t,"DeclareInterface")}flowParseInterfaceish(t,e=!1){if(t.id=this.flowParseRestrictedIdentifier(!e,!0),this.scope.declareName(t.id.name,e?17:9,t.id.start),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.extends=[],t.implements=[],t.mixins=[],this.eat(n._extends))do{t.extends.push(this.flowParseInterfaceExtends())}while(!e&&this.eat(n.comma));if(this.isContextual("mixins")){this.next();do{t.mixins.push(this.flowParseInterfaceExtends())}while(this.eat(n.comma))}if(this.isContextual("implements")){this.next();do{t.implements.push(this.flowParseInterfaceExtends())}while(this.eat(n.comma))}t.body=this.flowParseObjectType({allowStatic:e,allowExact:!1,allowSpread:!1,allowProto:e,allowInexact:!1})}flowParseInterfaceExtends(){const t=this.startNode();return t.id=this.flowParseQualifiedTypeIdentifier(),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,this.finishNode(t,"InterfaceExtends")}flowParseInterface(t){return this.flowParseInterfaceish(t),this.finishNode(t,"InterfaceDeclaration")}checkNotUnderscore(t){"_"===t&&this.raise(this.state.start,j.UnexpectedReservedUnderscore)}checkReservedType(t,e,s){_.has(t)&&this.raise(e,s?j.AssignReservedType:j.UnexpectedReservedType,t)}flowParseRestrictedIdentifier(t,e){return this.checkReservedType(this.state.value,this.state.start,e),this.parseIdentifier(t)}flowParseTypeAlias(t){return t.id=this.flowParseRestrictedIdentifier(!1,!0),this.scope.declareName(t.id.name,9,t.id.start),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.right=this.flowParseTypeInitialiser(n.eq),this.semicolon(),this.finishNode(t,"TypeAlias")}flowParseOpaqueType(t,e){return this.expectContextual("type"),t.id=this.flowParseRestrictedIdentifier(!0,!0),this.scope.declareName(t.id.name,9,t.id.start),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterDeclaration():t.typeParameters=null,t.supertype=null,this.match(n.colon)&&(t.supertype=this.flowParseTypeInitialiser(n.colon)),t.impltype=null,e||(t.impltype=this.flowParseTypeInitialiser(n.eq)),this.semicolon(),this.finishNode(t,"OpaqueType")}flowParseTypeParameter(t=!1){const e=this.state.start,s=this.startNode(),i=this.flowParseVariance(),r=this.flowParseTypeAnnotatableIdentifier();return s.name=r.name,s.variance=i,s.bound=r.typeAnnotation,this.match(n.eq)?(this.eat(n.eq),s.default=this.flowParseType()):t&&this.raise(e,j.MissingTypeParamDefault),this.finishNode(s,"TypeParameter")}flowParseTypeParameterDeclaration(){const t=this.state.inType,e=this.startNode();e.params=[],this.state.inType=!0,this.isRelational("<")||this.match(n.jsxTagStart)?this.next():this.unexpected();let s=!1;do{const t=this.flowParseTypeParameter(s);e.params.push(t),t.default&&(s=!0),this.isRelational(">")||this.expect(n.comma)}while(!this.isRelational(">"));return this.expectRelational(">"),this.state.inType=t,this.finishNode(e,"TypeParameterDeclaration")}flowParseTypeParameterInstantiation(){const t=this.startNode(),e=this.state.inType;t.params=[],this.state.inType=!0,this.expectRelational("<");const s=this.state.noAnonFunctionType;for(this.state.noAnonFunctionType=!1;!this.isRelational(">");)t.params.push(this.flowParseType()),this.isRelational(">")||this.expect(n.comma);return this.state.noAnonFunctionType=s,this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")}flowParseTypeParameterInstantiationCallOrNew(){const t=this.startNode(),e=this.state.inType;for(t.params=[],this.state.inType=!0,this.expectRelational("<");!this.isRelational(">");)t.params.push(this.flowParseTypeOrImplicitInstantiation()),this.isRelational(">")||this.expect(n.comma);return this.expectRelational(">"),this.state.inType=e,this.finishNode(t,"TypeParameterInstantiation")}flowParseInterfaceType(){const t=this.startNode();if(this.expectContextual("interface"),t.extends=[],this.eat(n._extends))do{t.extends.push(this.flowParseInterfaceExtends())}while(this.eat(n.comma));return t.body=this.flowParseObjectType({allowStatic:!1,allowExact:!1,allowSpread:!1,allowProto:!1,allowInexact:!1}),this.finishNode(t,"InterfaceTypeAnnotation")}flowParseObjectPropertyKey(){return this.match(n.num)||this.match(n.string)?this.parseExprAtom():this.parseIdentifier(!0)}flowParseObjectTypeIndexer(t,e,s){return t.static=e,this.lookahead().type===n.colon?(t.id=this.flowParseObjectPropertyKey(),t.key=this.flowParseTypeInitialiser()):(t.id=null,t.key=this.flowParseType()),this.expect(n.bracketR),t.value=this.flowParseTypeInitialiser(),t.variance=s,this.finishNode(t,"ObjectTypeIndexer")}flowParseObjectTypeInternalSlot(t,e){return t.static=e,t.id=this.flowParseObjectPropertyKey(),this.expect(n.bracketR),this.expect(n.bracketR),this.isRelational("<")||this.match(n.parenL)?(t.method=!0,t.optional=!1,t.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t.start,t.loc.start))):(t.method=!1,this.eat(n.question)&&(t.optional=!0),t.value=this.flowParseTypeInitialiser()),this.finishNode(t,"ObjectTypeInternalSlot")}flowParseObjectTypeMethodish(t){for(t.params=[],t.rest=null,t.typeParameters=null,this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration()),this.expect(n.parenL);!this.match(n.parenR)&&!this.match(n.ellipsis);)t.params.push(this.flowParseFunctionTypeParam()),this.match(n.parenR)||this.expect(n.comma);return this.eat(n.ellipsis)&&(t.rest=this.flowParseFunctionTypeParam()),this.expect(n.parenR),t.returnType=this.flowParseTypeInitialiser(),this.finishNode(t,"FunctionTypeAnnotation")}flowParseObjectTypeCallProperty(t,e){const s=this.startNode();return t.static=e,t.value=this.flowParseObjectTypeMethodish(s),this.finishNode(t,"ObjectTypeCallProperty")}flowParseObjectType({allowStatic:t,allowExact:e,allowSpread:s,allowProto:i,allowInexact:r}){const a=this.state.inType;this.state.inType=!0;const o=this.startNode();let h,p;o.callProperties=[],o.properties=[],o.indexers=[],o.internalSlots=[];let c=!1;for(e&&this.match(n.braceBarL)?(this.expect(n.braceBarL),h=n.braceBarR,p=!0):(this.expect(n.braceL),h=n.braceR,p=!1),o.exact=p;!this.match(h);){let e=!1,a=null,h=null;const u=this.startNode();if(i&&this.isContextual("proto")){const e=this.lookahead();e.type!==n.colon&&e.type!==n.question&&(this.next(),a=this.state.start,t=!1)}if(t&&this.isContextual("static")){const t=this.lookahead();t.type!==n.colon&&t.type!==n.question&&(this.next(),e=!0)}const l=this.flowParseVariance();if(this.eat(n.bracketL))null!=a&&this.unexpected(a),this.eat(n.bracketL)?(l&&this.unexpected(l.start),o.internalSlots.push(this.flowParseObjectTypeInternalSlot(u,e))):o.indexers.push(this.flowParseObjectTypeIndexer(u,e,l));else if(this.match(n.parenL)||this.isRelational("<"))null!=a&&this.unexpected(a),l&&this.unexpected(l.start),o.callProperties.push(this.flowParseObjectTypeCallProperty(u,e));else{let t="init";if(this.isContextual("get")||this.isContextual("set")){const e=this.lookahead();e.type!==n.name&&e.type!==n.string&&e.type!==n.num||(t=this.state.value,this.next())}const i=this.flowParseObjectTypeProperty(u,e,a,l,t,s,null!=r?r:!p);null===i?(c=!0,h=this.state.lastTokStart):o.properties.push(i)}this.flowObjectTypeSemicolon(),!h||this.match(n.braceR)||this.match(n.braceBarR)||this.raise(h,j.UnexpectedExplicitInexactInObject)}this.expect(h),s&&(o.inexact=c);const u=this.finishNode(o,"ObjectTypeAnnotation");return this.state.inType=a,u}flowParseObjectTypeProperty(t,e,s,i,r,a,o){if(this.eat(n.ellipsis)){return this.match(n.comma)||this.match(n.semi)||this.match(n.braceR)||this.match(n.braceBarR)?(a?o||this.raise(this.state.lastTokStart,j.InexactInsideExact):this.raise(this.state.lastTokStart,j.InexactInsideNonObject),i&&this.raise(i.start,j.InexactVariance),null):(a||this.raise(this.state.lastTokStart,j.UnexpectedSpreadType),null!=s&&this.unexpected(s),i&&this.raise(i.start,j.SpreadVariance),t.argument=this.flowParseType(),this.finishNode(t,"ObjectTypeSpreadProperty"))}{t.key=this.flowParseObjectPropertyKey(),t.static=e,t.proto=null!=s,t.kind=r;let a=!1;return this.isRelational("<")||this.match(n.parenL)?(t.method=!0,null!=s&&this.unexpected(s),i&&this.unexpected(i.start),t.value=this.flowParseObjectTypeMethodish(this.startNodeAt(t.start,t.loc.start)),"get"!==r&&"set"!==r||this.flowCheckGetterSetterParams(t)):("init"!==r&&this.unexpected(),t.method=!1,this.eat(n.question)&&(a=!0),t.value=this.flowParseTypeInitialiser(),t.variance=i),t.optional=a,this.finishNode(t,"ObjectTypeProperty")}}flowCheckGetterSetterParams(t){const e="get"===t.kind?0:1,s=t.start;t.value.params.length+(t.value.rest?1:0)!==e&&("get"===t.kind?this.raise(s,f.BadGetterArity):this.raise(s,f.BadSetterArity)),"set"===t.kind&&t.value.rest&&this.raise(s,f.BadSetterRestParameter)}flowObjectTypeSemicolon(){this.eat(n.semi)||this.eat(n.comma)||this.match(n.braceR)||this.match(n.braceBarR)||this.unexpected()}flowParseQualifiedTypeIdentifier(t,e,s){t=t||this.state.start,e=e||this.state.startLoc;let i=s||this.flowParseRestrictedIdentifier(!0);for(;this.eat(n.dot);){const s=this.startNodeAt(t,e);s.qualification=i,s.id=this.flowParseRestrictedIdentifier(!0),i=this.finishNode(s,"QualifiedTypeIdentifier")}return i}flowParseGenericType(t,e,s){const i=this.startNodeAt(t,e);return i.typeParameters=null,i.id=this.flowParseQualifiedTypeIdentifier(t,e,s),this.isRelational("<")&&(i.typeParameters=this.flowParseTypeParameterInstantiation()),this.finishNode(i,"GenericTypeAnnotation")}flowParseTypeofType(){const t=this.startNode();return this.expect(n._typeof),t.argument=this.flowParsePrimaryType(),this.finishNode(t,"TypeofTypeAnnotation")}flowParseTupleType(){const t=this.startNode();for(t.types=[],this.expect(n.bracketL);this.state.possuper.parseFunctionBody(t,!0,s)):super.parseFunctionBody(t,!1,s)}parseFunctionBodyAndFinish(t,e,s=!1){if(this.match(n.colon)){const e=this.startNode();[e.typeAnnotation,t.predicate]=this.flowParseTypeAndPredicateInitialiser(),t.returnType=e.typeAnnotation?this.finishNode(e,"TypeAnnotation"):null}super.parseFunctionBodyAndFinish(t,e,s)}parseStatement(t,e){if(this.state.strict&&this.match(n.name)&&"interface"===this.state.value){const t=this.startNode();return this.next(),this.flowParseInterface(t)}if(this.shouldParseEnums()&&this.isContextual("enum")){const t=this.startNode();return this.next(),this.flowParseEnumDeclaration(t)}{const s=super.parseStatement(t,e);return void 0!==this.flowPragma||this.isValidDirective(s)||(this.flowPragma=null),s}}parseExpressionStatement(t,e){if("Identifier"===e.type)if("declare"===e.name){if(this.match(n._class)||this.match(n.name)||this.match(n._function)||this.match(n._var)||this.match(n._export))return this.flowParseDeclare(t)}else if(this.match(n.name)){if("interface"===e.name)return this.flowParseInterface(t);if("type"===e.name)return this.flowParseTypeAlias(t);if("opaque"===e.name)return this.flowParseOpaqueType(t,!1)}return super.parseExpressionStatement(t,e)}shouldParseExportDeclaration(){return this.isContextual("type")||this.isContextual("interface")||this.isContextual("opaque")||this.shouldParseEnums()&&this.isContextual("enum")||super.shouldParseExportDeclaration()}isExportDefaultSpecifier(){return(!this.match(n.name)||!("type"===this.state.value||"interface"===this.state.value||"opaque"===this.state.value||this.shouldParseEnums()&&"enum"===this.state.value))&&super.isExportDefaultSpecifier()}parseExportDefaultExpression(){if(this.shouldParseEnums()&&this.isContextual("enum")){const t=this.startNode();return this.next(),this.flowParseEnumDeclaration(t)}return super.parseExportDefaultExpression()}parseConditional(t,e,s,i,r){if(!this.match(n.question))return t;if(r){const a=this.tryParse(()=>super.parseConditional(t,e,s,i));return a.node?(a.error&&(this.state=a.failState),a.node):(r.start=a.error.pos||this.state.start,t)}this.expect(n.question);const a=this.state.clone(),o=this.state.noArrowAt,h=this.startNodeAt(s,i);let{consequent:p,failed:c}=this.tryParseConditionalConsequent(),[u,l]=this.getArrowLikeExpressions(p);if(c||l.length>0){const t=[...o];if(l.length>0){this.state=a,this.state.noArrowAt=t;for(let e=0;e1&&this.raise(a.start,j.AmbiguousConditionalArrow),c&&1===u.length&&(this.state=a,this.state.noArrowAt=t.concat(u[0].start),({consequent:p,failed:c}=this.tryParseConditionalConsequent()))}return this.getArrowLikeExpressions(p,!0),this.state.noArrowAt=o,this.expect(n.colon),h.test=t,h.consequent=p,h.alternate=this.forwardNoArrowParamsConversionAt(h,()=>this.parseMaybeAssign(e,void 0,void 0,void 0)),this.finishNode(h,"ConditionalExpression")}tryParseConditionalConsequent(){this.state.noArrowParamsConversionAt.push(this.state.start);const t=this.parseMaybeAssign(),e=!this.match(n.colon);return this.state.noArrowParamsConversionAt.pop(),{consequent:t,failed:e}}getArrowLikeExpressions(t,e){const s=[t],i=[];for(;0!==s.length;){const t=s.pop();"ArrowFunctionExpression"===t.type?(t.typeParameters||!t.returnType?this.finishArrowValidation(t):i.push(t),s.push(t.body)):"ConditionalExpression"===t.type&&(s.push(t.consequent),s.push(t.alternate))}return e?(i.forEach(t=>this.finishArrowValidation(t)),[i,[]]):function(t,e){const s=[],i=[];for(let r=0;rt.params.every(t=>this.isAssignable(t,!0)))}finishArrowValidation(t){var e;this.toAssignableList(t.params,null==(e=t.extra)?void 0:e.trailingComma),this.scope.enter(6),super.checkParams(t,!1,!0),this.scope.exit()}forwardNoArrowParamsConversionAt(t,e){let s;return-1!==this.state.noArrowParamsConversionAt.indexOf(t.start)?(this.state.noArrowParamsConversionAt.push(this.state.start),s=e(),this.state.noArrowParamsConversionAt.pop()):s=e(),s}parseParenItem(t,e,s){if(t=super.parseParenItem(t,e,s),this.eat(n.question)&&(t.optional=!0,this.resetEndLocation(t)),this.match(n.colon)){const i=this.startNodeAt(e,s);return i.expression=t,i.typeAnnotation=this.flowParseTypeAnnotation(),this.finishNode(i,"TypeCastExpression")}return t}assertModuleNodeAllowed(t){"ImportDeclaration"===t.type&&("type"===t.importKind||"typeof"===t.importKind)||"ExportNamedDeclaration"===t.type&&"type"===t.exportKind||"ExportAllDeclaration"===t.type&&"type"===t.exportKind||super.assertModuleNodeAllowed(t)}parseExport(t){const e=super.parseExport(t);return"ExportNamedDeclaration"!==e.type&&"ExportAllDeclaration"!==e.type||(e.exportKind=e.exportKind||"value"),e}parseExportDeclaration(t){if(this.isContextual("type")){t.exportKind="type";const e=this.startNode();return this.next(),this.match(n.braceL)?(t.specifiers=this.parseExportSpecifiers(),this.parseExportFrom(t),null):this.flowParseTypeAlias(e)}if(this.isContextual("opaque")){t.exportKind="type";const e=this.startNode();return this.next(),this.flowParseOpaqueType(e,!1)}if(this.isContextual("interface")){t.exportKind="type";const e=this.startNode();return this.next(),this.flowParseInterface(e)}if(this.shouldParseEnums()&&this.isContextual("enum")){t.exportKind="value";const e=this.startNode();return this.next(),this.flowParseEnumDeclaration(e)}return super.parseExportDeclaration(t)}eatExportStar(t){return!!super.eatExportStar(...arguments)||!(!this.isContextual("type")||this.lookahead().type!==n.star)&&(t.exportKind="type",this.next(),this.next(),!0)}maybeParseExportNamespaceSpecifier(t){const e=this.state.start,s=super.maybeParseExportNamespaceSpecifier(t);return s&&"type"===t.exportKind&&this.unexpected(e),s}parseClassId(t,e,s){super.parseClassId(t,e,s),this.isRelational("<")&&(t.typeParameters=this.flowParseTypeParameterDeclaration())}parseClassMember(t,e,s,i){const r=this.state.start;if(this.isContextual("declare")){if(this.parseClassMemberFromModifier(t,e))return;e.declare=!0}super.parseClassMember(t,e,s,i),e.declare&&("ClassProperty"!==e.type&&"ClassPrivateProperty"!==e.type?this.raise(r,j.DeclareClassElement):e.value&&this.raise(e.value.start,j.DeclareClassFieldInitializer))}getTokenFromCode(t){const e=this.input.charCodeAt(this.state.pos+1);return 123===t&&124===e?this.finishOp(n.braceBarL,2):!this.state.inType||62!==t&&60!==t?function(t,e){return 64===t&&64===e}(t,e)?(this.state.isIterator=!0,super.readWord()):super.getTokenFromCode(t):this.finishOp(n.relational,1)}isAssignable(t,e){switch(t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":return!0;case"ObjectExpression":{const e=t.properties.length-1;return t.properties.every((t,s)=>"ObjectMethod"!==t.type&&(s===e||"SpreadElement"===t.type)&&this.isAssignable(t))}case"ObjectProperty":return this.isAssignable(t.value);case"SpreadElement":return this.isAssignable(t.argument);case"ArrayExpression":return t.elements.every(t=>this.isAssignable(t));case"AssignmentExpression":return"="===t.operator;case"ParenthesizedExpression":case"TypeCastExpression":return this.isAssignable(t.expression);case"MemberExpression":case"OptionalMemberExpression":return!e;default:return!1}}toAssignable(t){return"TypeCastExpression"===t.type?super.toAssignable(this.typeCastToParameter(t)):super.toAssignable(t)}toAssignableList(t,e){for(let e=0;e1)&&e||this.raise(i.typeAnnotation.start,j.TypeCastInPattern)}return t}checkLVal(t,e=64,s,i){if("TypeCastExpression"!==t.type)return super.checkLVal(t,e,s,i)}parseClassProperty(t){return this.match(n.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassProperty(t)}parseClassPrivateProperty(t){return this.match(n.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),super.parseClassPrivateProperty(t)}isClassMethod(){return this.isRelational("<")||super.isClassMethod()}isClassProperty(){return this.match(n.colon)||super.isClassProperty()}isNonstaticConstructor(t){return!this.match(n.colon)&&super.isNonstaticConstructor(t)}pushClassMethod(t,e,s,i,r,a){e.variance&&this.unexpected(e.variance.start),delete e.variance,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassMethod(t,e,s,i,r,a)}pushClassPrivateMethod(t,e,s,i){e.variance&&this.unexpected(e.variance.start),delete e.variance,this.isRelational("<")&&(e.typeParameters=this.flowParseTypeParameterDeclaration()),super.pushClassPrivateMethod(t,e,s,i)}parseClassSuper(t){if(super.parseClassSuper(t),t.superClass&&this.isRelational("<")&&(t.superTypeParameters=this.flowParseTypeParameterInstantiation()),this.isContextual("implements")){this.next();const e=t.implements=[];do{const t=this.startNode();t.id=this.flowParseRestrictedIdentifier(!0),this.isRelational("<")?t.typeParameters=this.flowParseTypeParameterInstantiation():t.typeParameters=null,e.push(this.finishNode(t,"ClassImplements"))}while(this.eat(n.comma))}}parsePropertyName(t,e){const s=this.flowParseVariance(),i=super.parsePropertyName(t,e);return t.variance=s,i}parseObjPropValue(t,e,s,i,r,a,o,h){let p;t.variance&&this.unexpected(t.variance.start),delete t.variance,this.isRelational("<")&&(p=this.flowParseTypeParameterDeclaration(),this.match(n.parenL)||this.unexpected()),super.parseObjPropValue(t,e,s,i,r,a,o,h),p&&((t.value||t).typeParameters=p)}parseAssignableListItemTypes(t){return this.eat(n.question)&&("Identifier"!==t.type&&this.raise(t.start,j.OptionalBindingPattern),t.optional=!0),this.match(n.colon)&&(t.typeAnnotation=this.flowParseTypeAnnotation()),this.resetEndLocation(t),t}parseMaybeDefault(t,e,s){const i=super.parseMaybeDefault(t,e,s);return"AssignmentPattern"===i.type&&i.typeAnnotation&&i.right.startsuper.parseMaybeAssign(t,e,s,i),a),!r.error)return r.node;const{context:n}=this.state;n[n.length-1]===x.j_oTag?n.length-=2:n[n.length-1]===x.j_expr&&(n.length-=1)}if(r&&r.error||this.isRelational("<")){let n;a=a||this.state.clone();const o=this.tryParse(()=>{n=this.flowParseTypeParameterDeclaration();const r=this.forwardNoArrowParamsConversionAt(n,()=>super.parseMaybeAssign(t,e,s,i));return r.typeParameters=n,this.resetStartLocationFromNode(r,n),r},a),h=o.node&&"ArrowFunctionExpression"===o.node.type?o.node:null;if(!o.error&&h)return h;if(r&&r.node)return this.state=r.failState,r.node;if(h)return this.state=o.failState,h;if(r&&r.thrown)throw r.error;if(o.thrown)throw o.error;throw this.raise(n.start,j.UnexpectedTokenAfterTypeParameter)}return super.parseMaybeAssign(t,e,s,i)}parseArrow(t){if(this.match(n.colon)){const e=this.tryParse(()=>{const e=this.state.noAnonFunctionType;this.state.noAnonFunctionType=!0;const s=this.startNode();return[s.typeAnnotation,t.predicate]=this.flowParseTypeAndPredicateInitialiser(),this.state.noAnonFunctionType=e,this.canInsertSemicolon()&&this.unexpected(),this.match(n.arrow)||this.unexpected(),s});if(e.thrown)return null;e.error&&(this.state=e.failState),t.returnType=e.node.typeAnnotation?this.finishNode(e.node,"TypeAnnotation"):null}return super.parseArrow(t)}shouldParseArrow(){return this.match(n.colon)||super.shouldParseArrow()}setArrowFunctionParameters(t,e){-1!==this.state.noArrowParamsConversionAt.indexOf(t.start)?t.params=e:super.setArrowFunctionParameters(t,e)}checkParams(t,e,s){if(!s||-1===this.state.noArrowParamsConversionAt.indexOf(t.start))return super.checkParams(...arguments)}parseParenAndDistinguishExpression(t){return super.parseParenAndDistinguishExpression(t&&-1===this.state.noArrowAt.indexOf(this.state.start))}parseSubscripts(t,e,s,i){if("Identifier"===t.type&&"async"===t.name&&-1!==this.state.noArrowAt.indexOf(e)){this.next();const i=this.startNodeAt(e,s);i.callee=t,i.arguments=this.parseCallExpressionArguments(n.parenR,!1),t=this.finishNode(i,"CallExpression")}else if("Identifier"===t.type&&"async"===t.name&&this.isRelational("<")){const r=this.state.clone(),a=this.tryParse(t=>this.parseAsyncArrowWithTypeParameters(e,s)||t(),r);if(!a.error&&!a.aborted)return a.node;const n=this.tryParse(()=>super.parseSubscripts(t,e,s,i),r);if(n.node&&!n.error)return n.node;if(a.node)return this.state=a.failState,a.node;if(n.node)return this.state=n.failState,n.node;throw a.error||n.error}return super.parseSubscripts(t,e,s,i)}parseSubscript(t,e,s,i,r){if(this.match(n.questionDot)&&this.isLookaheadRelational("<")){if(r.optionalChainMember=!0,i)return r.stop=!0,t;this.next();const a=this.startNodeAt(e,s);return a.callee=t,a.typeArguments=this.flowParseTypeParameterInstantiation(),this.expect(n.parenL),a.arguments=this.parseCallExpressionArguments(n.parenR,!1),a.optional=!0,this.finishCallExpression(a,!0)}if(!i&&this.shouldParseTypes()&&this.isRelational("<")){const i=this.startNodeAt(e,s);i.callee=t;const a=this.tryParse(()=>(i.typeArguments=this.flowParseTypeParameterInstantiationCallOrNew(),this.expect(n.parenL),i.arguments=this.parseCallExpressionArguments(n.parenR,!1),r.optionalChainMember&&(i.optional=!1),this.finishCallExpression(i,r.optionalChainMember)));if(a.node)return a.error&&(this.state=a.failState),a.node}return super.parseSubscript(t,e,s,i,r)}parseNewArguments(t){let e=null;this.shouldParseTypes()&&this.isRelational("<")&&(e=this.tryParse(()=>this.flowParseTypeParameterInstantiationCallOrNew()).node),t.typeArguments=e,super.parseNewArguments(t)}parseAsyncArrowWithTypeParameters(t,e){const s=this.startNodeAt(t,e);if(this.parseFunctionParams(s),this.parseArrow(s))return this.parseArrowExpression(s,void 0,!0)}readToken_mult_modulo(t){const e=this.input.charCodeAt(this.state.pos+1);if(42===t&&47===e&&this.state.hasFlowComment)return this.state.hasFlowComment=!1,this.state.pos+=2,void this.nextToken();super.readToken_mult_modulo(t)}readToken_pipe_amp(t){const e=this.input.charCodeAt(this.state.pos+1);124!==t||125!==e?super.readToken_pipe_amp(t):this.finishOp(n.braceBarR,2)}parseTopLevel(t,e){const s=super.parseTopLevel(t,e);return this.state.hasFlowComment&&this.raise(this.state.pos,j.UnterminatedFlowComment),s}skipBlockComment(){if(this.hasPlugin("flowComments")&&this.skipFlowComment())return this.state.hasFlowComment&&this.unexpected(null,j.NestedFlowComment),this.hasFlowCommentCompletion(),this.state.pos+=this.skipFlowComment(),void(this.state.hasFlowComment=!0);if(this.state.hasFlowComment){const t=this.input.indexOf("*-/",this.state.pos+=2);if(-1===t)throw this.raise(this.state.pos-2,f.UnterminatedComment);this.state.pos=t+3}else super.skipBlockComment()}skipFlowComment(){const{pos:t}=this.state;let e=2;for(;[32,9].includes(this.input.charCodeAt(t+e));)e++;const s=this.input.charCodeAt(e+t),i=this.input.charCodeAt(e+t+1);return 58===s&&58===i?e+2:"flow-include"===this.input.slice(e+t,e+t+12)?e+12:58===s&&58!==i&&e}hasFlowCommentCompletion(){if(-1===this.input.indexOf("*/",this.state.pos))throw this.raise(this.state.pos,f.UnterminatedComment)}flowEnumErrorBooleanMemberNotInitialized(t,{enumName:e,memberName:s}){this.raise(t,j.EnumBooleanMemberNotInitialized,s,e)}flowEnumErrorInvalidMemberName(t,{enumName:e,memberName:s}){const i=s[0].toUpperCase()+s.slice(1);this.raise(t,j.EnumInvalidMemberName,s,i,e)}flowEnumErrorDuplicateMemberName(t,{enumName:e,memberName:s}){this.raise(t,j.EnumDuplicateMemberName,s,e)}flowEnumErrorInconsistentMemberValues(t,{enumName:e}){this.raise(t,j.EnumInconsistentMemberValues,e)}flowEnumErrorInvalidExplicitType(t,{enumName:e,suppliedType:s}){return this.raise(t,null===s?j.EnumInvalidExplicitTypeUnknownSupplied:j.EnumInvalidExplicitType,e,s)}flowEnumErrorInvalidMemberInitializer(t,{enumName:e,explicitType:s,memberName:i}){let r=null;switch(s){case"boolean":case"number":case"string":r=j.EnumInvalidMemberInitializerPrimaryType;break;case"symbol":r=j.EnumInvalidMemberInitializerSymbolType;break;default:r=j.EnumInvalidMemberInitializerUnknownType}return this.raise(t,r,e,i,s)}flowEnumErrorNumberMemberNotInitialized(t,{enumName:e,memberName:s}){this.raise(t,j.EnumNumberMemberNotInitialized,e,s)}flowEnumErrorStringMemberInconsistentlyInitailized(t,{enumName:e}){this.raise(t,j.EnumStringMemberInconsistentlyInitailized,e)}flowEnumMemberInit(){const t=this.state.start,e=()=>this.match(n.comma)||this.match(n.braceR);switch(this.state.type){case n.num:{const s=this.parseLiteral(this.state.value,"NumericLiteral");return e()?{type:"number",pos:s.start,value:s}:{type:"invalid",pos:t}}case n.string:{const s=this.parseLiteral(this.state.value,"StringLiteral");return e()?{type:"string",pos:s.start,value:s}:{type:"invalid",pos:t}}case n._true:case n._false:{const s=this.parseBooleanLiteral();return e()?{type:"boolean",pos:s.start,value:s}:{type:"invalid",pos:t}}default:return{type:"invalid",pos:t}}}flowEnumMemberRaw(){const t=this.state.start;return{id:this.parseIdentifier(!0),init:this.eat(n.eq)?this.flowEnumMemberInit():{type:"none",pos:t}}}flowEnumCheckExplicitTypeMismatch(t,e,s){const{explicitType:i}=e;null!==i&&i!==s&&this.flowEnumErrorInvalidMemberInitializer(t,e)}flowEnumMembers({enumName:t,explicitType:e}){const s=new Set,i={booleanMembers:[],numberMembers:[],stringMembers:[],defaultedMembers:[]};for(;!this.match(n.braceR);){const r=this.startNode(),{id:a,init:o}=this.flowEnumMemberRaw(),h=a.name;if(""===h)continue;/^[a-z]/.test(h)&&this.flowEnumErrorInvalidMemberName(a.start,{enumName:t,memberName:h}),s.has(h)&&this.flowEnumErrorDuplicateMemberName(a.start,{enumName:t,memberName:h}),s.add(h);const p={enumName:t,explicitType:e,memberName:h};switch(r.id=a,o.type){case"boolean":this.flowEnumCheckExplicitTypeMismatch(o.pos,p,"boolean"),r.init=o.value,i.booleanMembers.push(this.finishNode(r,"EnumBooleanMember"));break;case"number":this.flowEnumCheckExplicitTypeMismatch(o.pos,p,"number"),r.init=o.value,i.numberMembers.push(this.finishNode(r,"EnumNumberMember"));break;case"string":this.flowEnumCheckExplicitTypeMismatch(o.pos,p,"string"),r.init=o.value,i.stringMembers.push(this.finishNode(r,"EnumStringMember"));break;case"invalid":throw this.flowEnumErrorInvalidMemberInitializer(o.pos,p);case"none":switch(e){case"boolean":this.flowEnumErrorBooleanMemberNotInitialized(o.pos,p);break;case"number":this.flowEnumErrorNumberMemberNotInitialized(o.pos,p);break;default:i.defaultedMembers.push(this.finishNode(r,"EnumDefaultedMember"))}}this.match(n.braceR)||this.expect(n.comma)}return i}flowEnumStringMembers(t,e,{enumName:s}){if(0===t.length)return e;if(0===e.length)return t;if(e.length>t.length){for(let e=0;e(t.members=[],this.expect(n.braceR),this.finishNode(t,"EnumStringBody"));t.explicitType=!1;const a=r.booleanMembers.length,o=r.numberMembers.length,h=r.stringMembers.length,p=r.defaultedMembers.length;if(a||o||h||p){if(a||o){if(!o&&!h&&a>=p){for(let t=0,s=r.defaultedMembers;t=p){for(let t=0,s=r.defaultedMembers;tclass extends t{getScopeHandler(){return Z}tsIsIdentifier(){return this.match(n.name)}tsNextTokenCanFollowModifier(){return this.next(),!(this.hasPrecedingLineBreak()||this.match(n.parenL)||this.match(n.parenR)||this.match(n.colon)||this.match(n.eq)||this.match(n.question)||this.match(n.bang))}tsParseModifier(t){if(!this.match(n.name))return;const e=this.state.value;return-1!==t.indexOf(e)&&this.tsTryParse(this.tsNextTokenCanFollowModifier.bind(this))?e:void 0}tsParseModifiers(t,e){for(;;){const s=this.state.start,i=this.tsParseModifier(e);if(!i)break;Object.hasOwnProperty.call(t,i)&&this.raise(s,rt.DuplicateModifier,i),t[i]=!0}}tsIsListTerminator(t){switch(t){case"EnumMembers":case"TypeMembers":return this.match(n.braceR);case"HeritageClauseElement":return this.match(n.braceL);case"TupleElementTypes":return this.match(n.bracketR);case"TypeParametersOrArguments":return this.isRelational(">")}throw new Error("Unreachable")}tsParseList(t,e){const s=[];for(;!this.tsIsListTerminator(t);)s.push(e());return s}tsParseDelimitedList(t,e){return st(this.tsParseDelimitedListWorker(t,e,!0))}tsParseDelimitedListWorker(t,e,s){const i=[];for(;!this.tsIsListTerminator(t);){const r=e();if(null==r)return;if(i.push(r),!this.eat(n.comma)){if(this.tsIsListTerminator(t))break;return void(s&&this.expect(n.comma))}}return i}tsParseBracketedList(t,e,s,i){i||(s?this.expect(n.bracketL):this.expectRelational("<"));const r=this.tsParseDelimitedList(t,e);return s?this.expect(n.bracketR):this.expectRelational(">"),r}tsParseImportType(){const t=this.startNode();return this.expect(n._import),this.expect(n.parenL),this.match(n.string)||this.raise(this.state.start,rt.UnsupportedImportTypeArgument),t.argument=this.parseExprAtom(),this.expect(n.parenR),this.eat(n.dot)&&(t.qualifier=this.tsParseEntityName(!0)),this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSImportType")}tsParseEntityName(t){let e=this.parseIdentifier();for(;this.eat(n.dot);){const s=this.startNodeAtNode(e);s.left=e,s.right=this.parseIdentifier(t),e=this.finishNode(s,"TSQualifiedName")}return e}tsParseTypeReference(){const t=this.startNode();return t.typeName=this.tsParseEntityName(!1),!this.hasPrecedingLineBreak()&&this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSTypeReference")}tsParseThisTypePredicate(t){this.next();const e=this.startNodeAtNode(t);return e.parameterName=t,e.typeAnnotation=this.tsParseTypeAnnotation(!1),this.finishNode(e,"TSTypePredicate")}tsParseThisTypeNode(){const t=this.startNode();return this.next(),this.finishNode(t,"TSThisType")}tsParseTypeQuery(){const t=this.startNode();return this.expect(n._typeof),this.match(n._import)?t.exprName=this.tsParseImportType():t.exprName=this.tsParseEntityName(!0),this.finishNode(t,"TSTypeQuery")}tsParseTypeParameter(){const t=this.startNode();return t.name=this.parseIdentifierName(t.start),t.constraint=this.tsEatThenParseType(n._extends),t.default=this.tsEatThenParseType(n.eq),this.finishNode(t,"TSTypeParameter")}tsTryParseTypeParameters(){if(this.isRelational("<"))return this.tsParseTypeParameters()}tsParseTypeParameters(){const t=this.startNode();return this.isRelational("<")||this.match(n.jsxTagStart)?this.next():this.unexpected(),t.params=this.tsParseBracketedList("TypeParametersOrArguments",this.tsParseTypeParameter.bind(this),!1,!0),this.finishNode(t,"TSTypeParameterDeclaration")}tsTryNextParseConstantContext(){return this.lookahead().type===n._const?(this.next(),this.tsParseTypeReference()):null}tsFillSignature(t,e){const s=t===n.arrow;e.typeParameters=this.tsTryParseTypeParameters(),this.expect(n.parenL),e.parameters=this.tsParseBindingListForSignature(),s?e.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(t):this.match(t)&&(e.typeAnnotation=this.tsParseTypeOrTypePredicateAnnotation(t))}tsParseBindingListForSignature(){return this.parseBindingList(n.parenR,41).map(t=>("Identifier"!==t.type&&"RestElement"!==t.type&&"ObjectPattern"!==t.type&&"ArrayPattern"!==t.type&&this.raise(t.start,rt.UnsupportedSignatureParameterKind,t.type),t))}tsParseTypeMemberSemicolon(){this.eat(n.comma)||this.semicolon()}tsParseSignatureMember(t,e){return this.tsFillSignature(n.colon,e),this.tsParseTypeMemberSemicolon(),this.finishNode(e,t)}tsIsUnambiguouslyIndexSignature(){return this.next(),this.eat(n.name)&&this.match(n.colon)}tsTryParseIndexSignature(t){if(!this.match(n.bracketL)||!this.tsLookAhead(this.tsIsUnambiguouslyIndexSignature.bind(this)))return;this.expect(n.bracketL);const e=this.parseIdentifier();e.typeAnnotation=this.tsParseTypeAnnotation(),this.resetEndLocation(e),this.expect(n.bracketR),t.parameters=[e];const s=this.tsTryParseTypeAnnotation();return s&&(t.typeAnnotation=s),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSIndexSignature")}tsParsePropertyOrMethodSignature(t,e){this.eat(n.question)&&(t.optional=!0);const s=t;if(e||!this.match(n.parenL)&&!this.isRelational("<")){const t=s;e&&(t.readonly=!0);const i=this.tsTryParseTypeAnnotation();return i&&(t.typeAnnotation=i),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSPropertySignature")}{const t=s;return this.tsFillSignature(n.colon,t),this.tsParseTypeMemberSemicolon(),this.finishNode(t,"TSMethodSignature")}}tsParseTypeMember(){const t=this.startNode();if(this.match(n.parenL)||this.isRelational("<"))return this.tsParseSignatureMember("TSCallSignatureDeclaration",t);if(this.match(n._new)){const e=this.startNode();return this.next(),this.match(n.parenL)||this.isRelational("<")?this.tsParseSignatureMember("TSConstructSignatureDeclaration",t):(t.key=this.createIdentifier(e,"new"),this.tsParsePropertyOrMethodSignature(t,!1))}const e=!!this.tsParseModifier(["readonly"]),s=this.tsTryParseIndexSignature(t);return s?(e&&(t.readonly=!0),s):(this.parsePropertyName(t,!1),this.tsParsePropertyOrMethodSignature(t,e))}tsParseTypeLiteral(){const t=this.startNode();return t.members=this.tsParseObjectTypeMembers(),this.finishNode(t,"TSTypeLiteral")}tsParseObjectTypeMembers(){this.expect(n.braceL);const t=this.tsParseList("TypeMembers",this.tsParseTypeMember.bind(this));return this.expect(n.braceR),t}tsIsStartOfMappedType(){return this.next(),this.eat(n.plusMin)?this.isContextual("readonly"):(this.isContextual("readonly")&&this.next(),!!this.match(n.bracketL)&&(this.next(),!!this.tsIsIdentifier()&&(this.next(),this.match(n._in))))}tsParseMappedTypeParameter(){const t=this.startNode();return t.name=this.parseIdentifierName(t.start),t.constraint=this.tsExpectThenParseType(n._in),this.finishNode(t,"TSTypeParameter")}tsParseMappedType(){const t=this.startNode();return this.expect(n.braceL),this.match(n.plusMin)?(t.readonly=this.state.value,this.next(),this.expectContextual("readonly")):this.eatContextual("readonly")&&(t.readonly=!0),this.expect(n.bracketL),t.typeParameter=this.tsParseMappedTypeParameter(),this.expect(n.bracketR),this.match(n.plusMin)?(t.optional=this.state.value,this.next(),this.expect(n.question)):this.eat(n.question)&&(t.optional=!0),t.typeAnnotation=this.tsTryParseType(),this.semicolon(),this.expect(n.braceR),this.finishNode(t,"TSMappedType")}tsParseTupleType(){const t=this.startNode();t.elementTypes=this.tsParseBracketedList("TupleElementTypes",this.tsParseTupleElementType.bind(this),!0,!1);let e=!1;return t.elementTypes.forEach(t=>{"TSOptionalType"===t.type?e=!0:e&&"TSRestType"!==t.type&&this.raise(t.start,rt.OptionalTypeBeforeRequired)}),this.finishNode(t,"TSTupleType")}tsParseTupleElementType(){if(this.match(n.ellipsis)){const t=this.startNode();return this.next(),t.typeAnnotation=this.tsParseType(),this.match(n.comma)&&93!==this.lookaheadCharCode()&&this.raiseRestNotLast(this.state.start),this.finishNode(t,"TSRestType")}const t=this.tsParseType();if(this.eat(n.question)){const e=this.startNodeAtNode(t);return e.typeAnnotation=t,this.finishNode(e,"TSOptionalType")}return t}tsParseParenthesizedType(){const t=this.startNode();return this.expect(n.parenL),t.typeAnnotation=this.tsParseType(),this.expect(n.parenR),this.finishNode(t,"TSParenthesizedType")}tsParseFunctionOrConstructorType(t){const e=this.startNode();return"TSConstructorType"===t&&this.expect(n._new),this.tsFillSignature(n.arrow,e),this.finishNode(e,t)}tsParseLiteralTypeNode(){const t=this.startNode();return t.literal=(()=>{switch(this.state.type){case n.num:case n.string:case n._true:case n._false:return this.parseExprAtom();default:throw this.unexpected()}})(),this.finishNode(t,"TSLiteralType")}tsParseTemplateLiteralType(){const t=this.startNode(),e=this.parseTemplate(!1);return e.expressions.length>0&&this.raise(e.expressions[0].start,rt.TemplateTypeHasSubstitution),t.literal=e,this.finishNode(t,"TSLiteralType")}tsParseThisTypeOrThisTypePredicate(){const t=this.tsParseThisTypeNode();return this.isContextual("is")&&!this.hasPrecedingLineBreak()?this.tsParseThisTypePredicate(t):t}tsParseNonArrayType(){switch(this.state.type){case n.name:case n._void:case n._null:{const t=this.match(n._void)?"TSVoidKeyword":this.match(n._null)?"TSNullKeyword":function(t){switch(t){case"any":return"TSAnyKeyword";case"boolean":return"TSBooleanKeyword";case"bigint":return"TSBigIntKeyword";case"never":return"TSNeverKeyword";case"number":return"TSNumberKeyword";case"object":return"TSObjectKeyword";case"string":return"TSStringKeyword";case"symbol":return"TSSymbolKeyword";case"undefined":return"TSUndefinedKeyword";case"unknown":return"TSUnknownKeyword";default:return}}(this.state.value);if(void 0!==t&&46!==this.lookaheadCharCode()){const e=this.startNode();return this.next(),this.finishNode(e,t)}return this.tsParseTypeReference()}case n.string:case n.num:case n._true:case n._false:return this.tsParseLiteralTypeNode();case n.plusMin:if("-"===this.state.value){const t=this.startNode();if(this.lookahead().type!==n.num)throw this.unexpected();return t.literal=this.parseMaybeUnary(),this.finishNode(t,"TSLiteralType")}break;case n._this:return this.tsParseThisTypeOrThisTypePredicate();case n._typeof:return this.tsParseTypeQuery();case n._import:return this.tsParseImportType();case n.braceL:return this.tsLookAhead(this.tsIsStartOfMappedType.bind(this))?this.tsParseMappedType():this.tsParseTypeLiteral();case n.bracketL:return this.tsParseTupleType();case n.parenL:return this.tsParseParenthesizedType();case n.backQuote:return this.tsParseTemplateLiteralType()}throw this.unexpected()}tsParseArrayTypeOrHigher(){let t=this.tsParseNonArrayType();for(;!this.hasPrecedingLineBreak()&&this.eat(n.bracketL);)if(this.match(n.bracketR)){const e=this.startNodeAtNode(t);e.elementType=t,this.expect(n.bracketR),t=this.finishNode(e,"TSArrayType")}else{const e=this.startNodeAtNode(t);e.objectType=t,e.indexType=this.tsParseType(),this.expect(n.bracketR),t=this.finishNode(e,"TSIndexedAccessType")}return t}tsParseTypeOperator(t){const e=this.startNode();return this.expectContextual(t),e.operator=t,e.typeAnnotation=this.tsParseTypeOperatorOrHigher(),"readonly"===t&&this.tsCheckTypeAnnotationForReadOnly(e),this.finishNode(e,"TSTypeOperator")}tsCheckTypeAnnotationForReadOnly(t){switch(t.typeAnnotation.type){case"TSTupleType":case"TSArrayType":return;default:this.raise(t.start,rt.UnexpectedReadonly)}}tsParseInferType(){const t=this.startNode();this.expectContextual("infer");const e=this.startNode();return e.name=this.parseIdentifierName(e.start),t.typeParameter=this.finishNode(e,"TSTypeParameter"),this.finishNode(t,"TSInferType")}tsParseTypeOperatorOrHigher(){const t=["keyof","unique","readonly"].find(t=>this.isContextual(t));return t?this.tsParseTypeOperator(t):this.isContextual("infer")?this.tsParseInferType():this.tsParseArrayTypeOrHigher()}tsParseUnionOrIntersectionType(t,e,s){this.eat(s);let i=e();if(this.match(s)){const r=[i];for(;this.eat(s);)r.push(e());const a=this.startNodeAtNode(i);a.types=r,i=this.finishNode(a,t)}return i}tsParseIntersectionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSIntersectionType",this.tsParseTypeOperatorOrHigher.bind(this),n.bitwiseAND)}tsParseUnionTypeOrHigher(){return this.tsParseUnionOrIntersectionType("TSUnionType",this.tsParseIntersectionTypeOrHigher.bind(this),n.bitwiseOR)}tsIsStartOfFunctionType(){return!!this.isRelational("<")||this.match(n.parenL)&&this.tsLookAhead(this.tsIsUnambiguouslyStartOfFunctionType.bind(this))}tsSkipParameterStart(){if(this.match(n.name)||this.match(n._this))return this.next(),!0;if(this.match(n.braceL)){let t=1;for(this.next();t>0;)this.match(n.braceL)?++t:this.match(n.braceR)&&--t,this.next();return!0}if(this.match(n.bracketL)){let t=1;for(this.next();t>0;)this.match(n.bracketL)?++t:this.match(n.bracketR)&&--t,this.next();return!0}return!1}tsIsUnambiguouslyStartOfFunctionType(){if(this.next(),this.match(n.parenR)||this.match(n.ellipsis))return!0;if(this.tsSkipParameterStart()){if(this.match(n.colon)||this.match(n.comma)||this.match(n.question)||this.match(n.eq))return!0;if(this.match(n.parenR)&&(this.next(),this.match(n.arrow)))return!0}return!1}tsParseTypeOrTypePredicateAnnotation(t){return this.tsInType(()=>{const e=this.startNode();this.expect(t);const s=this.tsTryParse(this.tsParseTypePredicateAsserts.bind(this));if(s&&this.match(n._this)){let t=this.tsParseThisTypeOrThisTypePredicate();if("TSThisType"===t.type){const s=this.startNodeAtNode(e);s.parameterName=t,s.asserts=!0,t=this.finishNode(s,"TSTypePredicate")}else t.asserts=!0;return e.typeAnnotation=t,this.finishNode(e,"TSTypeAnnotation")}const i=this.tsIsIdentifier()&&this.tsTryParse(this.tsParseTypePredicatePrefix.bind(this));if(!i){if(!s)return this.tsParseTypeAnnotation(!1,e);const t=this.startNodeAtNode(e);return t.parameterName=this.parseIdentifier(),t.asserts=s,e.typeAnnotation=this.finishNode(t,"TSTypePredicate"),this.finishNode(e,"TSTypeAnnotation")}const r=this.tsParseTypeAnnotation(!1),a=this.startNodeAtNode(e);return a.parameterName=i,a.typeAnnotation=r,a.asserts=s,e.typeAnnotation=this.finishNode(a,"TSTypePredicate"),this.finishNode(e,"TSTypeAnnotation")})}tsTryParseTypeOrTypePredicateAnnotation(){return this.match(n.colon)?this.tsParseTypeOrTypePredicateAnnotation(n.colon):void 0}tsTryParseTypeAnnotation(){return this.match(n.colon)?this.tsParseTypeAnnotation():void 0}tsTryParseType(){return this.tsEatThenParseType(n.colon)}tsParseTypePredicatePrefix(){const t=this.parseIdentifier();if(this.isContextual("is")&&!this.hasPrecedingLineBreak())return this.next(),t}tsParseTypePredicateAsserts(){if(!this.match(n.name)||"asserts"!==this.state.value||this.hasPrecedingLineBreak())return!1;const t=this.state.containsEsc;return this.next(),!(!this.match(n.name)&&!this.match(n._this))&&(t&&this.raise(this.state.lastTokStart,f.InvalidEscapedReservedWord,"asserts"),!0)}tsParseTypeAnnotation(t=!0,e=this.startNode()){return this.tsInType(()=>{t&&this.expect(n.colon),e.typeAnnotation=this.tsParseType()}),this.finishNode(e,"TSTypeAnnotation")}tsParseType(){it(this.state.inType);const t=this.tsParseNonConditionalType();if(this.hasPrecedingLineBreak()||!this.eat(n._extends))return t;const e=this.startNodeAtNode(t);return e.checkType=t,e.extendsType=this.tsParseNonConditionalType(),this.expect(n.question),e.trueType=this.tsParseType(),this.expect(n.colon),e.falseType=this.tsParseType(),this.finishNode(e,"TSConditionalType")}tsParseNonConditionalType(){return this.tsIsStartOfFunctionType()?this.tsParseFunctionOrConstructorType("TSFunctionType"):this.match(n._new)?this.tsParseFunctionOrConstructorType("TSConstructorType"):this.tsParseUnionTypeOrHigher()}tsParseTypeAssertion(){const t=this.startNode(),e=this.tsTryNextParseConstantContext();return t.typeAnnotation=e||this.tsNextThenParseType(),this.expectRelational(">"),t.expression=this.parseMaybeUnary(),this.finishNode(t,"TSTypeAssertion")}tsParseHeritageClause(t){const e=this.state.start,s=this.tsParseDelimitedList("HeritageClauseElement",this.tsParseExpressionWithTypeArguments.bind(this));return s.length||this.raise(e,rt.EmptyHeritageClauseType,t),s}tsParseExpressionWithTypeArguments(){const t=this.startNode();return t.expression=this.tsParseEntityName(!1),this.isRelational("<")&&(t.typeParameters=this.tsParseTypeArguments()),this.finishNode(t,"TSExpressionWithTypeArguments")}tsParseInterfaceDeclaration(t){t.id=this.parseIdentifier(),this.checkLVal(t.id,130,void 0,"typescript interface declaration"),t.typeParameters=this.tsTryParseTypeParameters(),this.eat(n._extends)&&(t.extends=this.tsParseHeritageClause("extends"));const e=this.startNode();return e.body=this.tsInType(this.tsParseObjectTypeMembers.bind(this)),t.body=this.finishNode(e,"TSInterfaceBody"),this.finishNode(t,"TSInterfaceDeclaration")}tsParseTypeAliasDeclaration(t){return t.id=this.parseIdentifier(),this.checkLVal(t.id,2,void 0,"typescript type alias"),t.typeParameters=this.tsTryParseTypeParameters(),t.typeAnnotation=this.tsExpectThenParseType(n.eq),this.semicolon(),this.finishNode(t,"TSTypeAliasDeclaration")}tsInNoContext(t){const e=this.state.context;this.state.context=[e[0]];try{return t()}finally{this.state.context=e}}tsInType(t){const e=this.state.inType;this.state.inType=!0;try{return t()}finally{this.state.inType=e}}tsEatThenParseType(t){return this.match(t)?this.tsNextThenParseType():void 0}tsExpectThenParseType(t){return this.tsDoThenParseType(()=>this.expect(t))}tsNextThenParseType(){return this.tsDoThenParseType(()=>this.next())}tsDoThenParseType(t){return this.tsInType(()=>(t(),this.tsParseType()))}tsParseEnumMember(){const t=this.startNode();return t.id=this.match(n.string)?this.parseExprAtom():this.parseIdentifier(!0),this.eat(n.eq)&&(t.initializer=this.parseMaybeAssign()),this.finishNode(t,"TSEnumMember")}tsParseEnumDeclaration(t,e){return e&&(t.const=!0),t.id=this.parseIdentifier(),this.checkLVal(t.id,e?779:267,void 0,"typescript enum declaration"),this.expect(n.braceL),t.members=this.tsParseDelimitedList("EnumMembers",this.tsParseEnumMember.bind(this)),this.expect(n.braceR),this.finishNode(t,"TSEnumDeclaration")}tsParseModuleBlock(){const t=this.startNode();return this.scope.enter(0),this.expect(n.braceL),this.parseBlockOrModuleBlockBody(t.body=[],void 0,!0,n.braceR),this.scope.exit(),this.finishNode(t,"TSModuleBlock")}tsParseModuleOrNamespaceDeclaration(t,e=!1){if(t.id=this.parseIdentifier(),e||this.checkLVal(t.id,1024,null,"module or namespace declaration"),this.eat(n.dot)){const e=this.startNode();this.tsParseModuleOrNamespaceDeclaration(e,!0),t.body=e}else this.scope.enter(128),this.prodParam.enter(0),t.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit();return this.finishNode(t,"TSModuleDeclaration")}tsParseAmbientExternalModuleDeclaration(t){return this.isContextual("global")?(t.global=!0,t.id=this.parseIdentifier()):this.match(n.string)?t.id=this.parseExprAtom():this.unexpected(),this.match(n.braceL)?(this.scope.enter(128),this.prodParam.enter(0),t.body=this.tsParseModuleBlock(),this.prodParam.exit(),this.scope.exit()):this.semicolon(),this.finishNode(t,"TSModuleDeclaration")}tsParseImportEqualsDeclaration(t,e){return t.isExport=e||!1,t.id=this.parseIdentifier(),this.checkLVal(t.id,9,void 0,"import equals declaration"),this.expect(n.eq),t.moduleReference=this.tsParseModuleReference(),this.semicolon(),this.finishNode(t,"TSImportEqualsDeclaration")}tsIsExternalModuleReference(){return this.isContextual("require")&&40===this.lookaheadCharCode()}tsParseModuleReference(){return this.tsIsExternalModuleReference()?this.tsParseExternalModuleReference():this.tsParseEntityName(!1)}tsParseExternalModuleReference(){const t=this.startNode();if(this.expectContextual("require"),this.expect(n.parenL),!this.match(n.string))throw this.unexpected();return t.expression=this.parseExprAtom(),this.expect(n.parenR),this.finishNode(t,"TSExternalModuleReference")}tsLookAhead(t){const e=this.state.clone(),s=t();return this.state=e,s}tsTryParseAndCatch(t){const e=this.tryParse(e=>t()||e());if(!e.aborted&&e.node)return e.error&&(this.state=e.failState),e.node}tsTryParse(t){const e=this.state.clone(),s=t();return void 0!==s&&!1!==s?s:void(this.state=e)}tsTryParseDeclare(t){if(this.isLineTerminator())return;let e,s=this.state.type;switch(this.isContextual("let")&&(s=n._var,e="let"),s){case n._function:return this.parseFunctionStatement(t,!1,!0);case n._class:return t.declare=!0,this.parseClass(t,!0,!1);case n._const:if(this.match(n._const)&&this.isLookaheadContextual("enum"))return this.expect(n._const),this.expectContextual("enum"),this.tsParseEnumDeclaration(t,!0);case n._var:return e=e||this.state.value,this.parseVarStatement(t,e);case n.name:{const e=this.state.value;return"global"===e?this.tsParseAmbientExternalModuleDeclaration(t):this.tsParseDeclaration(t,e,!0)}}}tsTryParseExportDeclaration(){return this.tsParseDeclaration(this.startNode(),this.state.value,!0)}tsParseExpressionStatement(t,e){switch(e.name){case"declare":{const e=this.tsTryParseDeclare(t);if(e)return e.declare=!0,e;break}case"global":if(this.match(n.braceL)){this.scope.enter(128),this.prodParam.enter(0);const s=t;return s.global=!0,s.id=e,s.body=this.tsParseModuleBlock(),this.scope.exit(),this.prodParam.exit(),this.finishNode(s,"TSModuleDeclaration")}break;default:return this.tsParseDeclaration(t,e.name,!1)}}tsParseDeclaration(t,e,s){switch(e){case"abstract":if(this.tsCheckLineTerminatorAndMatch(n._class,s)){const e=t;return e.abstract=!0,s&&(this.next(),this.match(n._class)||this.unexpected(null,n._class)),this.parseClass(e,!0,!1)}break;case"enum":if(s||this.match(n.name))return s&&this.next(),this.tsParseEnumDeclaration(t,!1);break;case"interface":if(this.tsCheckLineTerminatorAndMatch(n.name,s))return s&&this.next(),this.tsParseInterfaceDeclaration(t);break;case"module":if(s&&this.next(),this.match(n.string))return this.tsParseAmbientExternalModuleDeclaration(t);if(this.tsCheckLineTerminatorAndMatch(n.name,s))return this.tsParseModuleOrNamespaceDeclaration(t);break;case"namespace":if(this.tsCheckLineTerminatorAndMatch(n.name,s))return s&&this.next(),this.tsParseModuleOrNamespaceDeclaration(t);break;case"type":if(this.tsCheckLineTerminatorAndMatch(n.name,s))return s&&this.next(),this.tsParseTypeAliasDeclaration(t)}}tsCheckLineTerminatorAndMatch(t,e){return(e||this.match(t))&&!this.isLineTerminator()}tsTryParseGenericAsyncArrowFunction(t,e){if(!this.isRelational("<"))return;const s=this.state.maybeInArrowParameters,i=this.state.yieldPos,r=this.state.awaitPos;this.state.maybeInArrowParameters=!0,this.state.yieldPos=-1,this.state.awaitPos=-1;const a=this.tsTryParseAndCatch(()=>{const s=this.startNodeAt(t,e);return s.typeParameters=this.tsParseTypeParameters(),super.parseFunctionParams(s),s.returnType=this.tsTryParseTypeOrTypePredicateAnnotation(),this.expect(n.arrow),s});return this.state.maybeInArrowParameters=s,this.state.yieldPos=i,this.state.awaitPos=r,a?this.parseArrowExpression(a,null,!0):void 0}tsParseTypeArguments(){const t=this.startNode();return t.params=this.tsInType(()=>this.tsInNoContext(()=>(this.expectRelational("<"),this.tsParseDelimitedList("TypeParametersOrArguments",this.tsParseType.bind(this))))),this.state.exprAllowed=!1,this.expectRelational(">"),this.finishNode(t,"TSTypeParameterInstantiation")}tsIsDeclarationStart(){if(this.match(n.name))switch(this.state.value){case"abstract":case"declare":case"enum":case"interface":case"module":case"namespace":case"type":return!0}return!1}isExportDefaultSpecifier(){return!this.tsIsDeclarationStart()&&super.isExportDefaultSpecifier()}parseAssignableListItem(t,e){const s=this.state.start,i=this.state.startLoc;let r,a=!1;t&&(r=this.parseAccessModifier(),a=!!this.tsParseModifier(["readonly"]));const n=this.parseMaybeDefault();this.parseAssignableListItemTypes(n);const o=this.parseMaybeDefault(n.start,n.loc.start,n);if(r||a){const t=this.startNodeAt(s,i);return e.length&&(t.decorators=e),r&&(t.accessibility=r),a&&(t.readonly=a),"Identifier"!==o.type&&"AssignmentPattern"!==o.type&&this.raise(t.start,rt.UnsupportedParameterPropertyKind),t.parameter=o,this.finishNode(t,"TSParameterProperty")}return e.length&&(n.decorators=e),o}parseFunctionBodyAndFinish(t,e,s=!1){this.match(n.colon)&&(t.returnType=this.tsParseTypeOrTypePredicateAnnotation(n.colon));const i="FunctionDeclaration"===e?"TSDeclareFunction":"ClassMethod"===e?"TSDeclareMethod":void 0;i&&!this.match(n.braceL)&&this.isLineTerminator()?this.finishNode(t,i):super.parseFunctionBodyAndFinish(t,e,s)}registerFunctionStatementId(t){!t.body&&t.id?this.checkLVal(t.id,1024,null,"function name"):super.registerFunctionStatementId(...arguments)}parseSubscript(t,e,s,i,r){if(!this.hasPrecedingLineBreak()&&this.match(n.bang)){this.state.exprAllowed=!1,this.next();const i=this.startNodeAt(e,s);return i.expression=t,this.finishNode(i,"TSNonNullExpression")}if(this.isRelational("<")){const a=this.tsTryParseAndCatch(()=>{if(!i&&this.atPossibleAsyncArrow(t)){const t=this.tsTryParseGenericAsyncArrowFunction(e,s);if(t)return t}const a=this.startNodeAt(e,s);a.callee=t;const o=this.tsParseTypeArguments();if(o){if(!i&&this.eat(n.parenL))return a.arguments=this.parseCallExpressionArguments(n.parenR,!1),a.typeParameters=o,this.finishCallExpression(a,r.optionalChainMember);if(this.match(n.backQuote))return this.parseTaggedTemplateExpression(e,s,t,r,o)}this.unexpected()});if(a)return a}return super.parseSubscript(t,e,s,i,r)}parseNewArguments(t){if(this.isRelational("<")){const e=this.tsTryParseAndCatch(()=>{const t=this.tsParseTypeArguments();return this.match(n.parenL)||this.unexpected(),t});e&&(t.typeParameters=e)}super.parseNewArguments(t)}parseExprOp(t,e,s,i,r){if(st(n._in.binop)>i&&!this.hasPrecedingLineBreak()&&this.isContextual("as")){const a=this.startNodeAt(e,s);a.expression=t;const n=this.tsTryNextParseConstantContext();return a.typeAnnotation=n||this.tsNextThenParseType(),this.finishNode(a,"TSAsExpression"),this.parseExprOp(a,e,s,i,r)}return super.parseExprOp(t,e,s,i,r)}checkReservedWord(t,e,s,i){}checkDuplicateExports(){}parseImport(t){if(this.match(n.name)||this.match(n.star)||this.match(n.braceL)){const e=this.lookahead();if(this.match(n.name)&&e.type===n.eq)return this.tsParseImportEqualsDeclaration(t);!this.isContextual("type")||e.type===n.comma||e.type===n.name&&"from"===e.value?t.importKind="value":(t.importKind="type",this.next())}const e=super.parseImport(t);return"type"===e.importKind&&e.specifiers.length>1&&"ImportDefaultSpecifier"===e.specifiers[0].type&&this.raise(e.start,"A type-only import can specify a default import or named bindings, but not both."),e}parseExport(t){if(this.match(n._import))return this.expect(n._import),this.tsParseImportEqualsDeclaration(t,!0);if(this.eat(n.eq)){const e=t;return e.expression=this.parseExpression(),this.semicolon(),this.finishNode(e,"TSExportAssignment")}if(this.eatContextual("as")){const e=t;return this.expectContextual("namespace"),e.id=this.parseIdentifier(),this.semicolon(),this.finishNode(e,"TSNamespaceExportDeclaration")}return this.isContextual("type")&&this.lookahead().type===n.braceL?(this.next(),t.exportKind="type"):t.exportKind="value",super.parseExport(t)}isAbstractClass(){return this.isContextual("abstract")&&this.lookahead().type===n._class}parseExportDefaultExpression(){if(this.isAbstractClass()){const t=this.startNode();return this.next(),this.parseClass(t,!0,!0),t.abstract=!0,t}if("interface"===this.state.value){const t=this.tsParseDeclaration(this.startNode(),this.state.value,!0);if(t)return t}return super.parseExportDefaultExpression()}parseStatementContent(t,e){if(this.state.type===n._const){const t=this.lookahead();if(t.type===n.name&&"enum"===t.value){const t=this.startNode();return this.expect(n._const),this.expectContextual("enum"),this.tsParseEnumDeclaration(t,!0)}}return super.parseStatementContent(t,e)}parseAccessModifier(){return this.tsParseModifier(["public","protected","private"])}parseClassMember(t,e,s,i){this.tsParseModifiers(e,["declare"]);const r=this.parseAccessModifier();r&&(e.accessibility=r),this.tsParseModifiers(e,["declare"]),super.parseClassMember(t,e,s,i)}parseClassMemberWithIsStatic(t,e,s,i,r){this.tsParseModifiers(e,["abstract","readonly","declare"]);const a=this.tsTryParseIndexSignature(e);if(a)return t.body.push(a),e.abstract&&this.raise(e.start,rt.IndexSignatureHasAbstract),i&&this.raise(e.start,rt.IndexSignatureHasStatic),void(e.accessibility&&this.raise(e.start,rt.IndexSignatureHasAccessibility,e.accessibility));super.parseClassMemberWithIsStatic(t,e,s,i,r)}parsePostMemberNameModifiers(t){this.eat(n.question)&&(t.optional=!0),t.readonly&&this.match(n.parenL)&&this.raise(t.start,rt.ClassMethodHasReadonly),t.declare&&this.match(n.parenL)&&this.raise(t.start,rt.ClassMethodHasDeclare)}parseExpressionStatement(t,e){return("Identifier"===e.type?this.tsParseExpressionStatement(t,e):void 0)||super.parseExpressionStatement(t,e)}shouldParseExportDeclaration(){return!!this.tsIsDeclarationStart()||super.shouldParseExportDeclaration()}parseConditional(t,e,s,i,r){if(!r||!this.match(n.question))return super.parseConditional(t,e,s,i,r);const a=this.tryParse(()=>super.parseConditional(t,e,s,i));return a.node?(a.error&&(this.state=a.failState),a.node):(r.start=a.error.pos||this.state.start,t)}parseParenItem(t,e,s){if(t=super.parseParenItem(t,e,s),this.eat(n.question)&&(t.optional=!0,this.resetEndLocation(t)),this.match(n.colon)){const i=this.startNodeAt(e,s);return i.expression=t,i.typeAnnotation=this.tsParseTypeAnnotation(),this.finishNode(i,"TSTypeCastExpression")}return t}parseExportDeclaration(t){const e=this.state.start,s=this.state.startLoc,i=this.eatContextual("declare");let r;return this.match(n.name)&&(r=this.tsTryParseExportDeclaration()),r||(r=super.parseExportDeclaration(t)),r&&("TSInterfaceDeclaration"===r.type||"TSTypeAliasDeclaration"===r.type||i)&&(t.exportKind="type"),r&&i&&(this.resetStartLocation(r,e,s),r.declare=!0),r}parseClassId(t,e,s){if((!e||s)&&this.isContextual("implements"))return;super.parseClassId(t,e,s,t.declare?1024:139);const i=this.tsTryParseTypeParameters();i&&(t.typeParameters=i)}parseClassPropertyAnnotation(t){!t.optional&&this.eat(n.bang)&&(t.definite=!0);const e=this.tsTryParseTypeAnnotation();e&&(t.typeAnnotation=e)}parseClassProperty(t){return this.parseClassPropertyAnnotation(t),t.declare&&this.match(n.equal)&&this.raise(this.state.start,rt.DeclareClassFieldHasInitializer),super.parseClassProperty(t)}parseClassPrivateProperty(t){return t.abstract&&this.raise(t.start,rt.PrivateElementHasAbstract),t.accessibility&&this.raise(t.start,rt.PrivateElementHasAccessibility,t.accessibility),this.parseClassPropertyAnnotation(t),super.parseClassPrivateProperty(t)}pushClassMethod(t,e,s,i,r,a){const n=this.tsTryParseTypeParameters();n&&(e.typeParameters=n),super.pushClassMethod(t,e,s,i,r,a)}pushClassPrivateMethod(t,e,s,i){const r=this.tsTryParseTypeParameters();r&&(e.typeParameters=r),super.pushClassPrivateMethod(t,e,s,i)}parseClassSuper(t){super.parseClassSuper(t),t.superClass&&this.isRelational("<")&&(t.superTypeParameters=this.tsParseTypeArguments()),this.eatContextual("implements")&&(t.implements=this.tsParseHeritageClause("implements"))}parseObjPropValue(t,...e){const s=this.tsTryParseTypeParameters();s&&(t.typeParameters=s),super.parseObjPropValue(t,...e)}parseFunctionParams(t,e){const s=this.tsTryParseTypeParameters();s&&(t.typeParameters=s),super.parseFunctionParams(t,e)}parseVarId(t,e){super.parseVarId(t,e),"Identifier"===t.id.type&&this.eat(n.bang)&&(t.definite=!0);const s=this.tsTryParseTypeAnnotation();s&&(t.id.typeAnnotation=s,this.resetEndLocation(t.id))}parseAsyncArrowFromCallExpression(t,e){return this.match(n.colon)&&(t.returnType=this.tsParseTypeAnnotation()),super.parseAsyncArrowFromCallExpression(t,e)}parseMaybeAssign(...t){let e,s,i,r;if(this.match(n.jsxTagStart)){if(e=this.state.clone(),s=this.tryParse(()=>super.parseMaybeAssign(...t),e),!s.error)return s.node;const{context:i}=this.state;i[i.length-1]===x.j_oTag?i.length-=2:i[i.length-1]===x.j_expr&&(i.length-=1)}if(!(s&&s.error||this.isRelational("<")))return super.parseMaybeAssign(...t);e=e||this.state.clone();const a=this.tryParse(e=>{r=this.tsParseTypeParameters();const s=super.parseMaybeAssign(...t);return("ArrowFunctionExpression"!==s.type||s.extra&&s.extra.parenthesized)&&e(),r&&0!==r.params.length&&this.resetStartLocationFromNode(s,r),s.typeParameters=r,s},e);if(!a.error&&!a.aborted)return a.node;if(!s&&(it(!this.hasPlugin("jsx")),i=this.tryParse(()=>super.parseMaybeAssign(...t),e),!i.error))return i.node;if(s&&s.node)return this.state=s.failState,s.node;if(a.node)return this.state=a.failState,a.node;if(i&&i.node)return this.state=i.failState,i.node;if(s&&s.thrown)throw s.error;if(a.thrown)throw a.error;if(i&&i.thrown)throw i.error;throw s&&s.error||a.error||i&&i.error}parseMaybeUnary(t){return!this.hasPlugin("jsx")&&this.isRelational("<")?this.tsParseTypeAssertion():super.parseMaybeUnary(t)}parseArrow(t){if(this.match(n.colon)){const e=this.tryParse(t=>{const e=this.tsParseTypeOrTypePredicateAnnotation(n.colon);return!this.canInsertSemicolon()&&this.match(n.arrow)||t(),e});if(e.aborted)return;e.thrown||(e.error&&(this.state=e.failState),t.returnType=e.node)}return super.parseArrow(t)}parseAssignableListItemTypes(t){this.eat(n.question)&&("Identifier"!==t.type&&this.raise(t.start,rt.PatternIsOptional),t.optional=!0);const e=this.tsTryParseTypeAnnotation();return e&&(t.typeAnnotation=e),this.resetEndLocation(t),t}toAssignable(t){switch(t.type){case"TSTypeCastExpression":return super.toAssignable(this.typeCastToParameter(t));case"TSParameterProperty":return super.toAssignable(t);case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":return t.expression=this.toAssignable(t.expression),t;default:return super.toAssignable(t)}}checkLVal(t,e=64,s,i){switch(t.type){case"TSTypeCastExpression":return;case"TSParameterProperty":return void this.checkLVal(t.parameter,e,s,"parameter property");case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":return void this.checkLVal(t.expression,e,s,i);default:return void super.checkLVal(t,e,s,i)}}parseBindingAtom(){switch(this.state.type){case n._this:return this.parseIdentifier(!0);default:return super.parseBindingAtom()}}parseMaybeDecoratorArguments(t){if(this.isRelational("<")){const e=this.tsParseTypeArguments();if(this.match(n.parenL)){const s=super.parseMaybeDecoratorArguments(t);return s.typeParameters=e,s}this.unexpected(this.state.start,n.parenL)}return super.parseMaybeDecoratorArguments(t)}isClassMethod(){return this.isRelational("<")||super.isClassMethod()}isClassProperty(){return this.match(n.bang)||this.match(n.colon)||super.isClassProperty()}parseMaybeDefault(...t){const e=super.parseMaybeDefault(...t);return"AssignmentPattern"===e.type&&e.typeAnnotation&&e.right.startthis.tsParseTypeArguments());e&&(t.typeParameters=e)}return super.jsxParseOpeningElementAfterName(t)}getGetterSetterExpectedParamCount(t){const e=super.getGetterSetterExpectedParamCount(t),s=t.params[0];return s&&"Identifier"===s.type&&"this"===s.name?e+1:e}},v8intrinsic:t=>class extends t{parseV8Intrinsic(){if(this.match(n.modulo)){const t=this.state.start,e=this.startNode();if(this.eat(n.modulo),this.match(n.name)){const t=this.parseIdentifierName(this.state.start),s=this.createIdentifier(e,t);if(s.type="V8IntrinsicIdentifier",this.match(n.parenL))return s}this.unexpected(t)}}parseExprAtom(){return this.parseV8Intrinsic()||super.parseExprAtom(...arguments)}},placeholders:t=>class extends t{parsePlaceholder(t){if(this.match(n.placeholder)){const e=this.startNode();return this.next(),this.assertNoSpace("Unexpected space in placeholder."),e.name=super.parseIdentifier(!0),this.assertNoSpace("Unexpected space in placeholder."),this.expect(n.placeholder),this.finishPlaceholder(e,t)}}finishPlaceholder(t,e){const s=!(!t.expectedNode||"Placeholder"!==t.type);return t.expectedNode=e,s?t:this.finishNode(t,"Placeholder")}getTokenFromCode(t){return 37===t&&37===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.placeholder,2):super.getTokenFromCode(...arguments)}parseExprAtom(){return this.parsePlaceholder("Expression")||super.parseExprAtom(...arguments)}parseIdentifier(){return this.parsePlaceholder("Identifier")||super.parseIdentifier(...arguments)}checkReservedWord(t){void 0!==t&&super.checkReservedWord(...arguments)}parseBindingAtom(){return this.parsePlaceholder("Pattern")||super.parseBindingAtom(...arguments)}checkLVal(t){"Placeholder"!==t.type&&super.checkLVal(...arguments)}toAssignable(t){return t&&"Placeholder"===t.type&&"Expression"===t.expectedNode?(t.expectedNode="Pattern",t):super.toAssignable(...arguments)}verifyBreakContinue(t){t.label&&"Placeholder"===t.label.type||super.verifyBreakContinue(...arguments)}parseExpressionStatement(t,e){if("Placeholder"!==e.type||e.extra&&e.extra.parenthesized)return super.parseExpressionStatement(...arguments);if(this.match(n.colon)){const s=t;return s.label=this.finishPlaceholder(e,"Identifier"),this.next(),s.body=this.parseStatement("label"),this.finishNode(s,"LabeledStatement")}return this.semicolon(),t.name=e.name,this.finishPlaceholder(t,"Statement")}parseBlock(){return this.parsePlaceholder("BlockStatement")||super.parseBlock(...arguments)}parseFunctionId(){return this.parsePlaceholder("Identifier")||super.parseFunctionId(...arguments)}parseClass(t,e,s){const i=e?"ClassDeclaration":"ClassExpression";this.next(),this.takeDecorators(t);const r=this.parsePlaceholder("Identifier");if(r)if(this.match(n._extends)||this.match(n.placeholder)||this.match(n.braceL))t.id=r;else{if(s||!e)return t.id=null,t.body=this.finishPlaceholder(r,"ClassBody"),this.finishNode(t,i);this.unexpected(null,"A class name is required")}else this.parseClassId(t,e,s);return this.parseClassSuper(t),t.body=this.parsePlaceholder("ClassBody")||this.parseClassBody(!!t.superClass),this.finishNode(t,i)}parseExport(t){const e=this.parsePlaceholder("Identifier");if(!e)return super.parseExport(...arguments);if(!this.isContextual("from")&&!this.match(n.comma))return t.specifiers=[],t.source=null,t.declaration=this.finishPlaceholder(e,"Declaration"),this.finishNode(t,"ExportNamedDeclaration");this.expectPlugin("exportDefaultFrom");const s=this.startNode();return s.exported=e,t.specifiers=[this.finishNode(s,"ExportDefaultSpecifier")],super.parseExport(t)}maybeParseExportDefaultSpecifier(t){return!!(t.specifiers&&t.specifiers.length>0)||super.maybeParseExportDefaultSpecifier(...arguments)}checkExport(t){const{specifiers:e}=t;e&&e.length&&(t.specifiers=e.filter(t=>"Placeholder"===t.exported.type)),super.checkExport(t),t.specifiers=e}parseImport(t){const e=this.parsePlaceholder("Identifier");if(!e)return super.parseImport(...arguments);if(t.specifiers=[],!this.isContextual("from")&&!this.match(n.comma))return t.source=this.finishPlaceholder(e,"StringLiteral"),this.semicolon(),this.finishNode(t,"ImportDeclaration");const s=this.startNodeAtNode(e);if(s.local=e,this.finishNode(s,"ImportDefaultSpecifier"),t.specifiers.push(s),this.eat(n.comma)){this.maybeParseStarImportSpecifier(t)||this.parseNamedImportSpecifiers(t)}return this.expectContextual("from"),t.source=this.parseImportSource(),this.semicolon(),this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.parsePlaceholder("StringLiteral")||super.parseImportSource(...arguments)}}},ct=Object.keys(pt),ut={sourceType:"script",sourceFilename:void 0,startLine:1,allowAwaitOutsideFunction:!1,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowSuperOutsideMethod:!1,allowUndeclaredExports:!1,plugins:[],strictMode:null,ranges:!1,tokens:!1,createParenthesizedExpressions:!1,errorRecovery:!1};class lt{constructor(){this.errors=[],this.potentialArrowAt=-1,this.noArrowAt=[],this.noArrowParamsConversionAt=[],this.inParameters=!1,this.maybeInArrowParameters=!1,this.maybeInAsyncArrowHead=!1,this.inPipeline=!1,this.inType=!1,this.noAnonFunctionType=!1,this.inPropertyName=!1,this.hasFlowComment=!1,this.isIterator=!1,this.topicContext={maxNumOfResolvableTopics:0,maxTopicIndex:null},this.soloAwait=!1,this.inFSharpPipelineDirectBody=!1,this.labels=[],this.decoratorStack=[[]],this.yieldPos=-1,this.awaitPos=-1,this.comments=[],this.trailingComments=[],this.leadingComments=[],this.commentStack=[],this.commentPreviousNode=null,this.pos=0,this.lineStart=0,this.type=n.eof,this.value=null,this.start=0,this.end=0,this.lastTokEndLoc=null,this.lastTokStartLoc=null,this.lastTokStart=0,this.lastTokEnd=0,this.context=[x.braceStatement],this.exprAllowed=!0,this.containsEsc=!1,this.octalPositions=[],this.exportedIdentifiers=[],this.tokensLength=0}init(t){this.strict=!1!==t.strictMode&&"module"===t.sourceType,this.curLine=t.startLine,this.startLoc=this.endLoc=this.curPosition()}curPosition(){return new l(this.curLine,this.pos-this.lineStart)}clone(t){const e=new lt,s=Object.keys(this);for(let i=0,r=s.length;i=48&&t<=57};const mt=new Set(["g","m","s","i","y","u"]),ft={decBinOct:[46,66,69,79,95,98,101,111],hex:[46,88,95,120]},Dt={bin:[48,49]};Dt.oct=[...Dt.bin,50,51,52,53,54,55],Dt.dec=[...Dt.oct,56,57],Dt.hex=[...Dt.dec,65,66,67,68,69,70,97,98,99,100,101,102];class yt{constructor(t){this.type=t.type,this.value=t.value,this.start=t.start,this.end=t.end,this.loc=new d(t.startLoc,t.endLoc)}}class xt{constructor(){this.shorthandAssign=-1,this.doubleProto=-1}}class gt{constructor(t,e,s){this.type="",this.start=e,this.end=0,this.loc=new d(s),t&&t.options.ranges&&(this.range=[e,0]),t&&t.filename&&(this.loc.filename=t.filename)}__clone(){const t=new gt,e=Object.keys(this);for(let s=0,i=e.length;s"ParenthesizedExpression"===t.type?Pt(t.expression):t;const Et={kind:"loop"},Ct={kind:"switch"};class bt{constructor(){this.privateNames=new Set,this.loneAccessors=new Map,this.undefinedPrivateNames=new Map}}class Tt{constructor(t){this.stack=[],this.undefinedPrivateNames=new Map,this.raise=t}current(){return this.stack[this.stack.length-1]}enter(){this.stack.push(new bt)}exit(){const t=this.stack.pop(),e=this.current();for(let s=0,i=Array.from(t.undefinedPrivateNames);s0;)i=e[--r];if(null===i)return;for(let t=0;t0?i.trailingComments=a:void 0!==i.trailingComments&&(i.trailingComments=[])}processComment(t){if("Program"===t.type&&t.body.length>0)return;const e=this.state.commentStack;let s,i,r,a,n;if(this.state.trailingComments.length>0)this.state.trailingComments[0].start>=t.end?(r=this.state.trailingComments,this.state.trailingComments=[]):this.state.trailingComments.length=0;else if(e.length>0){const s=m(e);s.trailingComments&&s.trailingComments[0].start>=t.end&&(r=s.trailingComments,delete s.trailingComments)}for(e.length>0&&m(e).start>=t.start&&(s=e.pop());e.length>0&&m(e).start>=t.start;)i=e.pop();if(!i&&s&&(i=s),s)switch(t.type){case"ObjectExpression":this.adjustCommentsAfterTrailingComma(t,t.properties);break;case"ObjectPattern":this.adjustCommentsAfterTrailingComma(t,t.properties,!0);break;case"CallExpression":this.adjustCommentsAfterTrailingComma(t,t.arguments);break;case"ArrayExpression":this.adjustCommentsAfterTrailingComma(t,t.elements);break;case"ArrayPattern":this.adjustCommentsAfterTrailingComma(t,t.elements,!0)}else this.state.commentPreviousNode&&("ImportSpecifier"===this.state.commentPreviousNode.type&&"ImportSpecifier"!==t.type||"ExportSpecifier"===this.state.commentPreviousNode.type&&"ExportSpecifier"!==t.type)&&this.adjustCommentsAfterTrailingComma(t,[this.state.commentPreviousNode]);if(i){if(i.leadingComments)if(i!==t&&i.leadingComments.length>0&&m(i.leadingComments).end<=t.start)t.leadingComments=i.leadingComments,delete i.leadingComments;else for(a=i.leadingComments.length-2;a>=0;--a)if(i.leadingComments[a].end<=t.start){t.leadingComments=i.leadingComments.splice(0,a+1);break}}else if(this.state.leadingComments.length>0)if(m(this.state.leadingComments).end<=t.start){if(this.state.commentPreviousNode)for(n=0;n0&&(t.leadingComments=this.state.leadingComments,this.state.leadingComments=[])}else{for(a=0;at.start);a++);const e=this.state.leadingComments.slice(0,a);e.length&&(t.leadingComments=e),r=this.state.leadingComments.slice(a),0===r.length&&(r=null)}this.state.commentPreviousNode=t,r&&(r.length&&r[0].start>=t.start&&m(r).end<=t.end?t.innerComments=r:t.trailingComments=r),e.push(t)}}{getLocationForPosition(t){let e;return e=t===this.state.start?this.state.startLoc:t===this.state.lastTokStart?this.state.lastTokStartLoc:t===this.state.end?this.state.endLoc:t===this.state.lastTokEnd?this.state.lastTokEndLoc:function(t,e){let s,i=1,r=0;for(h.lastIndex=0;(s=h.exec(t))&&s.indexi[e])+" (".concat(r.line,":").concat(r.column,")");return this._raise(Object.assign({loc:r,pos:t},e),a)}_raise(t,e){const s=new SyntaxError(e);if(Object.assign(s,t),this.options.errorRecovery)return this.isLookahead||this.state.errors.push(s),s;throw s}}{constructor(t,e){super(),this.tokens=[],this.state=new lt,this.state.init(t),this.input=e,this.length=e.length,this.isLookahead=!1}pushToken(t){this.tokens.length=this.state.tokensLength,this.tokens.push(t),++this.state.tokensLength}next(){this.isLookahead||(this.checkKeywordEscapes(),this.options.tokens&&this.pushToken(new yt(this.state))),this.state.lastTokEnd=this.state.end,this.state.lastTokStart=this.state.start,this.state.lastTokEndLoc=this.state.endLoc,this.state.lastTokStartLoc=this.state.startLoc,this.nextToken()}eat(t){return!!this.match(t)&&(this.next(),!0)}match(t){return this.state.type===t}lookahead(){const t=this.state;this.state=t.clone(!0),this.isLookahead=!0,this.next(),this.isLookahead=!1;const e=this.state;return this.state=t,e}nextTokenStart(){const t=this.state.pos;return c.lastIndex=t,t+c.exec(this.input)[0].length}lookaheadCharCode(){return this.input.charCodeAt(this.nextTokenStart())}setStrict(t){if(this.state.strict=t,this.match(n.num)||this.match(n.string)){for(this.state.pos=this.state.start;this.state.pos=this.length)return void this.finishToken(n.eof);const e=null==t?void 0:t.override;e?e(this):this.getTokenFromCode(this.input.codePointAt(this.state.pos))}pushComment(t,e,s,i,r,a){const n={type:t?"CommentBlock":"CommentLine",value:e,start:s,end:i,loc:new d(r,a)};this.options.tokens&&this.pushToken(n),this.state.comments.push(n),this.addComment(n)}skipBlockComment(){const t=this.state.curPosition(),e=this.state.pos,s=this.input.indexOf("*/",this.state.pos+2);if(-1===s)throw this.raise(e,f.UnterminatedComment);let i;for(this.state.pos=s+2,h.lastIndex=e;(i=h.exec(this.input))&&i.index=48&&e<=57)throw this.raise(this.state.pos,f.UnexpectedDigitAfterHash);if(!this.hasPlugin("recordAndTuple")||123!==e&&91!==e){if(!this.hasPlugin("classPrivateProperties")&&!this.hasPlugin("classPrivateMethods")&&"smart"!==this.getPluginOption("pipelineOperator","proposal"))throw this.raise(this.state.pos,f.InvalidOrUnexpectedToken,"#");this.finishOp(n.hash,1)}else{if("hash"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,123===e?f.RecordExpressionHashIncorrectStartSyntaxType:f.TupleExpressionHashIncorrectStartSyntaxType);123===e?this.finishToken(n.braceHashL):this.finishToken(n.bracketHashL),this.state.pos+=2}}readToken_dot(){const t=this.input.charCodeAt(this.state.pos+1);t>=48&&t<=57?this.readNumber(!0):46===t&&46===this.input.charCodeAt(this.state.pos+2)?(this.state.pos+=3,this.finishToken(n.ellipsis)):(++this.state.pos,this.finishToken(n.dot))}readToken_slash(){if(this.state.exprAllowed&&!this.state.inType)return++this.state.pos,void this.readRegexp();61===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.assign,2):this.finishOp(n.slash,1)}readToken_interpreter(){if(0!==this.state.pos||this.length<2)return!1;let t=this.input.charCodeAt(this.state.pos+1);if(33!==t)return!1;const e=this.state.pos;for(this.state.pos+=1;!p(t)&&++this.state.pos=48&&e<=57?(++this.state.pos,this.finishToken(n.question)):(this.state.pos+=2,this.finishToken(n.questionDot)):61===e?this.finishOp(n.assign,3):this.finishOp(n.nullishCoalescing,2)}getTokenFromCode(t){switch(t){case 46:return void this.readToken_dot();case 40:return++this.state.pos,void this.finishToken(n.parenL);case 41:return++this.state.pos,void this.finishToken(n.parenR);case 59:return++this.state.pos,void this.finishToken(n.semi);case 44:return++this.state.pos,void this.finishToken(n.comma);case 91:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,f.TupleExpressionBarIncorrectStartSyntaxType);this.finishToken(n.bracketBarL),this.state.pos+=2}else++this.state.pos,this.finishToken(n.bracketL);return;case 93:return++this.state.pos,void this.finishToken(n.bracketR);case 123:if(this.hasPlugin("recordAndTuple")&&124===this.input.charCodeAt(this.state.pos+1)){if("bar"!==this.getPluginOption("recordAndTuple","syntaxType"))throw this.raise(this.state.pos,f.RecordExpressionBarIncorrectStartSyntaxType);this.finishToken(n.braceBarL),this.state.pos+=2}else++this.state.pos,this.finishToken(n.braceL);return;case 125:return++this.state.pos,void this.finishToken(n.braceR);case 58:return void(this.hasPlugin("functionBind")&&58===this.input.charCodeAt(this.state.pos+1)?this.finishOp(n.doubleColon,2):(++this.state.pos,this.finishToken(n.colon)));case 63:return void this.readToken_question();case 96:return++this.state.pos,void this.finishToken(n.backQuote);case 48:{const t=this.input.charCodeAt(this.state.pos+1);if(120===t||88===t)return void this.readRadixNumber(16);if(111===t||79===t)return void this.readRadixNumber(8);if(98===t||66===t)return void this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return void this.readNumber(!1);case 34:case 39:return void this.readString(t);case 47:return void this.readToken_slash();case 37:case 42:return void this.readToken_mult_modulo(t);case 124:case 38:return void this.readToken_pipe_amp(t);case 94:return void this.readToken_caret();case 43:case 45:return void this.readToken_plus_min(t);case 60:case 62:return void this.readToken_lt_gt(t);case 61:case 33:return void this.readToken_eq_excl(t);case 126:return void this.finishOp(n.tilde,1);case 64:return++this.state.pos,void this.finishToken(n.at);case 35:return void this.readToken_numberSign();case 92:return void this.readWord();default:if(w(t))return void this.readWord()}throw this.raise(this.state.pos,f.InvalidOrUnexpectedToken,String.fromCodePoint(t))}finishOp(t,e){const s=this.input.slice(this.state.pos,this.state.pos+e);this.state.pos+=e,this.finishToken(t,s)}readRegexp(){const t=this.state.pos;let e,s;for(;;){if(this.state.pos>=this.length)throw this.raise(t,f.UnterminatedRegExp);const i=this.input.charAt(this.state.pos);if(o.test(i))throw this.raise(t,f.UnterminatedRegExp);if(e)e=!1;else{if("["===i)s=!0;else if("]"===i&&s)s=!1;else if("/"===i&&!s)break;e="\\"===i}++this.state.pos}const i=this.input.slice(t,this.state.pos);++this.state.pos;let r="";for(;this.state.pos-1&&this.raise(this.state.pos+1,f.DuplicateRegExpFlags);else{if(!S(e)&&92!==e)break;this.raise(this.state.pos+1,f.MalformedRegExpFlags)}++this.state.pos,r+=t}this.finishToken(n.regexp,{pattern:i,flags:r})}readInt(t,e,s,i=!0){const r=this.state.pos,a=16===t?ft.hex:ft.decBinOct,n=16===t?Dt.hex:10===t?Dt.dec:8===t?Dt.oct:Dt.bin;let o=!1,h=0;for(let r=0,p=null==e?1/0:e;r-1||a.indexOf(e)>-1||Number.isNaN(e))&&this.raise(this.state.pos,f.UnexpectedNumericSeparator),i||this.raise(this.state.pos,f.NumericSeparatorInEscapeSequence),++this.state.pos}else{if(p=e>=97?e-97+10:e>=65?e-65+10:dt(e)?e-48:1/0,p>=t)if(this.options.errorRecovery&&p<=9)p=0,this.raise(this.state.start+r+2,f.InvalidDigit,t);else{if(!s)break;p=0,o=!0}++this.state.pos,h=h*t+p}}return this.state.pos===r||null!=e&&this.state.pos-r!==e||o?null:h}readRadixNumber(t){const e=this.state.pos;let s=!1;this.state.pos+=2;const i=this.readInt(t);if(null==i&&this.raise(this.state.start+2,f.InvalidDigit,t),110===this.input.charCodeAt(this.state.pos)&&(++this.state.pos,s=!0),w(this.input.codePointAt(this.state.pos)))throw this.raise(this.state.pos,f.NumberIdentifier);if(s){const t=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");this.finishToken(n.bigint,t)}else this.finishToken(n.num,i)}readNumber(t){const e=this.state.pos;let s=!1,i=!1,r=!1;t||null!==this.readInt(10)||this.raise(e,f.InvalidNumber);let a=this.state.pos-e>=2&&48===this.input.charCodeAt(e);a&&(this.state.strict&&this.raise(e,f.StrictOctalLiteral),/[89]/.test(this.input.slice(e,this.state.pos))&&(a=!1,r=!0));let o=this.input.charCodeAt(this.state.pos);if(46!==o||a||(++this.state.pos,this.readInt(10),s=!0,o=this.input.charCodeAt(this.state.pos)),69!==o&&101!==o||a||(o=this.input.charCodeAt(++this.state.pos),43!==o&&45!==o||++this.state.pos,null===this.readInt(10)&&this.raise(e,"Invalid number"),s=!0,o=this.input.charCodeAt(this.state.pos)),this.hasPlugin("numericSeparator")&&(a||r)){const t=this.input.slice(e,this.state.pos).indexOf("_");t>0&&this.raise(t+e,f.ZeroDigitNumericSeparator)}if(110===o&&((s||a||r)&&this.raise(e,"Invalid BigIntLiteral"),++this.state.pos,i=!0),w(this.input.codePointAt(this.state.pos)))throw this.raise(this.state.pos,f.NumberIdentifier);const h=this.input.slice(e,this.state.pos).replace(/[_n]/g,"");if(i)return void this.finishToken(n.bigint,h);const p=a?parseInt(h,8):parseFloat(h);this.finishToken(n.num,p)}readCodePoint(t){let e;if(123===this.input.charCodeAt(this.state.pos)){const s=++this.state.pos;if(e=this.readHexChar(this.input.indexOf("}",this.state.pos)-this.state.pos,!0,t),++this.state.pos,null!==e&&e>1114111){if(!t)return null;this.raise(s,f.InvalidCodePoint)}}else e=this.readHexChar(4,!1,t);return e}readString(t){let e="",s=++this.state.pos;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,f.UnterminatedString);const i=this.input.charCodeAt(this.state.pos);if(i===t)break;if(92===i)e+=this.input.slice(s,this.state.pos),e+=this.readEscapedChar(!1),s=this.state.pos;else if(8232===i||8233===i)++this.state.pos,++this.state.curLine,this.state.lineStart=this.state.pos;else{if(p(i))throw this.raise(this.state.start,f.UnterminatedString);++this.state.pos}}e+=this.input.slice(s,this.state.pos++),this.finishToken(n.string,e)}readTmplToken(){let t="",e=this.state.pos,s=!1;for(;;){if(this.state.pos>=this.length)throw this.raise(this.state.start,f.UnterminatedTemplate);const i=this.input.charCodeAt(this.state.pos);if(96===i||36===i&&123===this.input.charCodeAt(this.state.pos+1))return this.state.pos===this.state.start&&this.match(n.template)?36===i?(this.state.pos+=2,void this.finishToken(n.dollarBraceL)):(++this.state.pos,void this.finishToken(n.backQuote)):(t+=this.input.slice(e,this.state.pos),void this.finishToken(n.template,s?null:t));if(92===i){t+=this.input.slice(e,this.state.pos);const i=this.readEscapedChar(!0);null===i?s=!0:t+=i,e=this.state.pos}else if(p(i)){switch(t+=this.input.slice(e,this.state.pos),++this.state.pos,i){case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:t+="\n";break;default:t+=String.fromCharCode(i)}++this.state.curLine,this.state.lineStart=this.state.pos,e=this.state.pos}else++this.state.pos}}readEscapedChar(t){const e=!t,s=this.input.charCodeAt(++this.state.pos);switch(++this.state.pos,s){case 110:return"\n";case 114:return"\r";case 120:{const t=this.readHexChar(2,!1,e);return null===t?null:String.fromCharCode(t)}case 117:{const t=this.readCodePoint(e);return null===t?null:String.fromCodePoint(t)}case 116:return"\t";case 98:return"\b";case 118:return"\v";case 102:return"\f";case 13:10===this.input.charCodeAt(this.state.pos)&&++this.state.pos;case 10:this.state.lineStart=this.state.pos,++this.state.curLine;case 8232:case 8233:return"";case 56:case 57:if(t)return null;default:if(s>=48&&s<=55){const e=this.state.pos-1;let s=this.input.substr(this.state.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(s,8);i>255&&(s=s.slice(0,-1),i=parseInt(s,8)),this.state.pos+=s.length-1;const r=this.input.charCodeAt(this.state.pos);if("0"!==s||56===r||57===r){if(t)return null;this.state.strict?this.raise(e,f.StrictOctalLiteral):this.state.octalPositions.push(e)}return String.fromCharCode(i)}return String.fromCharCode(s)}}readHexChar(t,e,s){const i=this.state.pos,r=this.readInt(16,t,e,!1);return null===r&&(s?this.raise(i,f.InvalidEscapeSequence):this.state.pos=i-1),r}readWord1(){let t="";this.state.containsEsc=!1;const e=this.state.pos;let s=this.state.pos;for(;this.state.posthis.state.lastTokEnd&&this.raise(this.state.lastTokEnd,t)}unexpected(t,e="Unexpected token"){throw"string"!=typeof e&&(e='Unexpected token, expected "'.concat(e.label,'"')),this.raise(null!=t?t:this.state.start,e)}expectPlugin(t,e){if(!this.hasPlugin(t))throw this.raiseWithData(null!=e?e:this.state.start,{missingPlugin:[t]},"This experimental syntax requires enabling the parser plugin: '".concat(t,"'"));return!0}expectOnePlugin(t,e){if(!t.some(t=>this.hasPlugin(t)))throw this.raiseWithData(null!=e?e:this.state.start,{missingPlugin:t},"This experimental syntax requires enabling one of the following parser plugin(s): '".concat(t.join(", "),"'"))}checkYieldAwaitInDefaultParams(){-1!==this.state.yieldPos&&(-1===this.state.awaitPos||this.state.yieldPos{throw s.node=t,s});if(this.state.errors.length>e.errors.length){const t=this.state;return this.state=e,{node:i,error:t.errors[e.errors.length],thrown:!1,aborted:!1,failState:t}}return{node:i,error:null,thrown:!1,aborted:!1,failState:null}}catch(t){const i=this.state;if(this.state=e,t instanceof SyntaxError)return{node:null,error:t,thrown:!0,aborted:!1,failState:i};if(t===s)return{node:s.node,error:null,thrown:!1,aborted:!0,failState:i};throw t}}checkExpressionErrors(t,e){if(!t)return!1;const{shorthandAssign:s,doubleProto:i}=t;if(!e)return s>=0||i>=0;s>=0&&this.unexpected(s),i>=0&&this.raise(i,f.DuplicateProto)}}{startNode(){return new gt(this,this.state.start,this.state.startLoc)}startNodeAt(t,e){return new gt(this,t,e)}startNodeAtNode(t){return this.startNodeAt(t.start,t.loc.start)}finishNode(t,e){return this.finishNodeAt(t,e,this.state.lastTokEnd,this.state.lastTokEndLoc)}finishNodeAt(t,e,s,i){return t.type=e,t.end=s,t.loc.end=i,this.options.ranges&&(t.range[1]=s),this.processComment(t),t}resetStartLocation(t,e,s){t.start=e,t.loc.start=s,this.options.ranges&&(t.range[0]=e)}resetEndLocation(t,e=this.state.lastTokEnd,s=this.state.lastTokEndLoc){t.end=e,t.loc.end=s,this.options.ranges&&(t.range[1]=e)}resetStartLocationFromNode(t,e){this.resetStartLocation(t,e.start,e.loc.start)}}{toAssignable(t){var e,s;let i=void 0;switch(("ParenthesizedExpression"===t.type||(null==(e=t.extra)?void 0:e.parenthesized))&&(i=Pt(t),"Identifier"!==i.type&&"MemberExpression"!==i.type&&this.raise(t.start,f.InvalidParenthesizedAssignment)),t.type){case"Identifier":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":t.type="ObjectPattern";for(let e=0,s=t.properties.length,i=s-1;e=s.left.start&&(e.shorthandAssign=-1),this.checkLVal(h,void 0,void 0,"assignment expression"),this.next(),s.right=this.parseMaybeAssign(t),this.finishNode(s,"AssignmentExpression")}return o&&this.checkExpressionErrors(e,!0),h}parseMaybeConditional(t,e,s){const i=this.state.start,r=this.state.startLoc,a=this.state.potentialArrowAt,n=this.parseExprOps(t,e);return"ArrowFunctionExpression"===n.type&&n.start===a?n:this.checkExpressionErrors(e,!1)?n:this.parseConditional(n,t,i,r,s)}parseConditional(t,e,s,i,r){if(this.eat(n.question)){const r=this.startNodeAt(s,i);return r.test=t,r.consequent=this.parseMaybeAssign(),this.expect(n.colon),r.alternate=this.parseMaybeAssign(e),this.finishNode(r,"ConditionalExpression")}return t}parseExprOps(t,e){const s=this.state.start,i=this.state.startLoc,r=this.state.potentialArrowAt,a=this.parseMaybeUnary(e);return"ArrowFunctionExpression"===a.type&&a.start===r?a:this.checkExpressionErrors(e,!1)?a:this.parseExprOp(a,s,i,-1,t)}parseExprOp(t,e,s,i,r){let a=this.state.type.binop;if(!(null==a||r&&this.match(n._in))&&a>i){const o=this.state.value;if("|>"===o&&this.state.inFSharpPipelineDirectBody)return t;const h=this.startNodeAt(e,s);h.left=t,h.operator=o,"**"!==o||"UnaryExpression"!==t.type||!this.options.createParenthesizedExpressions&&t.extra&&t.extra.parenthesized||this.raise(t.argument.start,f.UnexpectedTokenUnaryExponentiation);const p=this.state.type,c=p===n.logicalOR||p===n.logicalAND,u=p===n.nullishCoalescing;if(p===n.pipeline?(this.expectPlugin("pipelineOperator"),this.state.inPipeline=!0,this.checkPipelineAtInfixOperator(t,e)):u&&(a=n.logicalAND.binop),this.next(),p===n.pipeline&&"minimal"===this.getPluginOption("pipelineOperator","proposal")&&this.match(n.name)&&"await"===this.state.value&&this.prodParam.hasAwait)throw this.raise(this.state.start,f.UnexpectedAwaitAfterPipelineBody);h.right=this.parseExprOpRightExpr(p,a,r),this.finishNode(h,c||u?"LogicalExpression":"BinaryExpression");const l=this.state.type;if(u&&(l===n.logicalOR||l===n.logicalAND)||c&&l===n.nullishCoalescing)throw this.raise(this.state.start,f.MixingCoalesceWithLogical);return this.parseExprOp(h,e,s,i,r)}return t}parseExprOpRightExpr(t,e,s){const i=this.state.start,r=this.state.startLoc;switch(t){case n.pipeline:switch(this.getPluginOption("pipelineOperator","proposal")){case"smart":return this.withTopicPermittingContext(()=>this.parseSmartPipelineBody(this.parseExprOpBaseRightExpr(t,e,s),i,r));case"fsharp":return this.withSoloAwaitPermittingContext(()=>this.parseFSharpPipelineBody(e,s))}default:return this.parseExprOpBaseRightExpr(t,e,s)}}parseExprOpBaseRightExpr(t,e,s){const i=this.state.start,r=this.state.startLoc;return this.parseExprOp(this.parseMaybeUnary(),i,r,t.rightAssociative?e-1:e,s)}parseMaybeUnary(t){if(this.isContextual("await")&&this.isAwaitAllowed())return this.parseAwait();if(this.state.type.prefix){const e=this.startNode(),s=this.match(n.incDec);if(e.operator=this.state.value,e.prefix=!0,"throw"===e.operator&&this.expectPlugin("throwExpressions"),this.next(),e.argument=this.parseMaybeUnary(),this.checkExpressionErrors(t,!0),s)this.checkLVal(e.argument,void 0,void 0,"prefix operation");else if(this.state.strict&&"delete"===e.operator){const t=e.argument;"Identifier"===t.type?this.raise(e.start,f.StrictDelete):"MemberExpression"===t.type&&"PrivateName"===t.property.type&&this.raise(e.start,f.DeletePrivateField)}return this.finishNode(e,s?"UpdateExpression":"UnaryExpression")}const e=this.state.start,s=this.state.startLoc;let i=this.parseExprSubscripts(t);if(this.checkExpressionErrors(t,!1))return i;for(;this.state.type.postfix&&!this.canInsertSemicolon();){const t=this.startNodeAt(e,s);t.operator=this.state.value,t.prefix=!1,t.argument=i,this.checkLVal(i,void 0,void 0,"postfix operation"),this.next(),i=this.finishNode(t,"UpdateExpression")}return i}parseExprSubscripts(t){const e=this.state.start,s=this.state.startLoc,i=this.state.potentialArrowAt,r=this.parseExprAtom(t);return"ArrowFunctionExpression"===r.type&&r.start===i?r:this.parseSubscripts(r,e,s)}parseSubscripts(t,e,s,i){const r={optionalChainMember:!1,maybeAsyncArrow:this.atPossibleAsyncArrow(t),stop:!1};do{const a=this.state.maybeInAsyncArrowHead;r.maybeAsyncArrow&&(this.state.maybeInAsyncArrowHead=!0),t=this.parseSubscript(t,e,s,i,r),r.maybeAsyncArrow=!1,this.state.maybeInAsyncArrowHead=a}while(!r.stop);return t}parseSubscript(t,e,s,i,r){if(!i&&this.eat(n.doubleColon)){const a=this.startNodeAt(e,s);return a.object=t,a.callee=this.parseNoCallExpr(),r.stop=!0,this.parseSubscripts(this.finishNode(a,"BindExpression"),e,s,i)}let a=!1;if(this.match(n.questionDot)){if(r.optionalChainMember=a=!0,i&&40===this.lookaheadCharCode())return r.stop=!0,t;this.next()}const o=this.eat(n.bracketL);if(a&&!this.match(n.parenL)&&!this.match(n.backQuote)||o||this.eat(n.dot)){const i=this.startNodeAt(e,s);return i.object=t,i.property=o?this.parseExpression():a?this.parseIdentifier(!0):this.parseMaybePrivateName(!0),i.computed=o,"PrivateName"===i.property.type&&("Super"===i.object.type&&this.raise(e,f.SuperPrivateField),this.classScope.usePrivateName(i.property.id.name,i.property.start)),o&&this.expect(n.bracketR),r.optionalChainMember?(i.optional=a,this.finishNode(i,"OptionalMemberExpression")):this.finishNode(i,"MemberExpression")}if(!i&&this.match(n.parenL)){const i=this.state.maybeInArrowParameters,o=this.state.yieldPos,h=this.state.awaitPos;this.state.maybeInArrowParameters=!0,this.state.yieldPos=-1,this.state.awaitPos=-1,this.next();let p=this.startNodeAt(e,s);return p.callee=t,a?(p.optional=!0,p.arguments=this.parseCallExpressionArguments(n.parenR,!1)):p.arguments=this.parseCallExpressionArguments(n.parenR,r.maybeAsyncArrow,"Import"===t.type,"Super"!==t.type,p),this.finishCallExpression(p,r.optionalChainMember),r.maybeAsyncArrow&&this.shouldParseAsyncArrow()&&!a?(r.stop=!0,p=this.parseAsyncArrowFromCallExpression(this.startNodeAt(e,s),p),this.checkYieldAwaitInDefaultParams(),this.state.yieldPos=o,this.state.awaitPos=h):(this.toReferencedListDeep(p.arguments),-1!==o&&(this.state.yieldPos=o),(this.isAwaitAllowed()||i)&&-1===h||(this.state.awaitPos=h)),this.state.maybeInArrowParameters=i,p}return this.match(n.backQuote)?this.parseTaggedTemplateExpression(e,s,t,r):(r.stop=!0,t)}parseTaggedTemplateExpression(t,e,s,i,r){const a=this.startNodeAt(t,e);return a.tag=s,a.quasi=this.parseTemplate(!0),r&&(a.typeParameters=r),i.optionalChainMember&&this.raise(t,f.OptionalChainingNoTemplate),this.finishNode(a,"TaggedTemplateExpression")}atPossibleAsyncArrow(t){return"Identifier"===t.type&&"async"===t.name&&this.state.lastTokEnd===t.end&&!this.canInsertSemicolon()&&t.end-t.start==5&&t.start===this.state.potentialArrowAt}finishCallExpression(t,e){if("Import"===t.callee.type)if(1!==t.arguments.length)this.raise(t.start,f.ImportCallArity);else{const e=t.arguments[0];e&&"SpreadElement"===e.type&&this.raise(e.start,f.ImportCallSpreadArgument)}return this.finishNode(t,e?"OptionalCallExpression":"CallExpression")}parseCallExpressionArguments(t,e,s,i,r){const a=[];let o,h=!0;const p=this.state.inFSharpPipelineDirectBody;for(this.state.inFSharpPipelineDirectBody=!1;!this.eat(t);){if(h)h=!1;else if(this.expect(n.comma),this.match(t)){s&&this.raise(this.state.lastTokStart,f.ImportCallArgumentTrailingComma),r&&this.addExtra(r,"trailingComma",this.state.lastTokStart),this.next();break}this.match(n.parenL)&&!o&&(o=this.state.start),a.push(this.parseExprListItem(!1,e?new xt:void 0,e?{start:0}:void 0,i))}return e&&o&&this.shouldParseAsyncArrow()&&this.unexpected(),this.state.inFSharpPipelineDirectBody=p,a}shouldParseAsyncArrow(){return this.match(n.arrow)&&!this.canInsertSemicolon()}parseAsyncArrowFromCallExpression(t,e){var s;return this.expect(n.arrow),this.parseArrowExpression(t,e.arguments,!0,null==(s=e.extra)?void 0:s.trailingComma),t}parseNoCallExpr(){const t=this.state.start,e=this.state.startLoc;return this.parseSubscripts(this.parseExprAtom(),t,e,!0)}parseExprAtom(t){this.state.type===n.slash&&this.readRegexp();const e=this.state.potentialArrowAt===this.state.start;let s;switch(this.state.type){case n._super:return s=this.startNode(),this.next(),!this.match(n.parenL)||this.scope.allowDirectSuper||this.options.allowSuperOutsideMethod?this.scope.allowSuper||this.options.allowSuperOutsideMethod||this.raise(s.start,f.UnexpectedSuper):this.raise(s.start,f.SuperNotAllowed),this.match(n.parenL)||this.match(n.bracketL)||this.match(n.dot)||this.raise(s.start,f.UnsupportedSuper),this.finishNode(s,"Super");case n._import:return s=this.startNode(),this.next(),this.match(n.dot)?this.parseImportMetaProperty(s):(this.match(n.parenL)||this.raise(this.state.lastTokStart,f.UnsupportedImport),this.finishNode(s,"Import"));case n._this:return s=this.startNode(),this.next(),this.finishNode(s,"ThisExpression");case n.name:{s=this.startNode();const t=this.state.containsEsc,i=this.parseIdentifier();if(!t&&"async"===i.name&&this.match(n._function)&&!this.canInsertSemicolon()){const t=this.state.context.length-1;if(this.state.context[t]!==x.functionStatement)throw new Error("Internal error");return this.state.context[t]=x.functionExpression,this.next(),this.parseFunction(s,void 0,!0)}if(e&&!t&&"async"===i.name&&this.match(n.name)&&!this.canInsertSemicolon()){const t=this.state.maybeInArrowParameters,e=this.state.maybeInAsyncArrowHead,i=this.state.yieldPos,r=this.state.awaitPos;this.state.maybeInArrowParameters=!0,this.state.maybeInAsyncArrowHead=!0,this.state.yieldPos=-1,this.state.awaitPos=-1;const a=[this.parseIdentifier()];return this.expect(n.arrow),this.checkYieldAwaitInDefaultParams(),this.state.maybeInArrowParameters=t,this.state.maybeInAsyncArrowHead=e,this.state.yieldPos=i,this.state.awaitPos=r,this.parseArrowExpression(s,a,!0),s}return e&&this.match(n.arrow)&&!this.canInsertSemicolon()?(this.next(),this.parseArrowExpression(s,[i],!1),s):i}case n._do:{this.expectPlugin("doExpressions");const t=this.startNode();this.next();const e=this.state.labels;return this.state.labels=[],t.body=this.parseBlock(),this.state.labels=e,this.finishNode(t,"DoExpression")}case n.regexp:{const t=this.state.value;return s=this.parseLiteral(t.value,"RegExpLiteral"),s.pattern=t.pattern,s.flags=t.flags,s}case n.num:return this.parseLiteral(this.state.value,"NumericLiteral");case n.bigint:return this.parseLiteral(this.state.value,"BigIntLiteral");case n.string:return this.parseLiteral(this.state.value,"StringLiteral");case n._null:return s=this.startNode(),this.next(),this.finishNode(s,"NullLiteral");case n._true:case n._false:return this.parseBooleanLiteral();case n.parenL:return this.parseParenAndDistinguishExpression(e);case n.bracketBarL:case n.bracketHashL:{this.expectPlugin("recordAndTuple");const e=this.state.inFSharpPipelineDirectBody,i=this.state.type===n.bracketBarL?n.bracketBarR:n.bracketR;return this.state.inFSharpPipelineDirectBody=!1,s=this.startNode(),this.next(),s.elements=this.parseExprList(i,!0,t,s),this.state.inFSharpPipelineDirectBody=e,this.finishNode(s,"TupleExpression")}case n.bracketL:{const e=this.state.inFSharpPipelineDirectBody;return this.state.inFSharpPipelineDirectBody=!1,s=this.startNode(),this.next(),s.elements=this.parseExprList(n.bracketR,!0,t,s),this.state.maybeInArrowParameters||this.toReferencedList(s.elements),this.state.inFSharpPipelineDirectBody=e,this.finishNode(s,"ArrayExpression")}case n.braceBarL:case n.braceHashL:{this.expectPlugin("recordAndTuple");const e=this.state.inFSharpPipelineDirectBody,s=this.state.type===n.braceBarL?n.braceBarR:n.braceR;this.state.inFSharpPipelineDirectBody=!1;const i=this.parseObj(s,!1,!0,t);return this.state.inFSharpPipelineDirectBody=e,i}case n.braceL:{const e=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!1;const s=this.parseObj(n.braceR,!1,!1,t);return this.state.inFSharpPipelineDirectBody=e,s}case n._function:return this.parseFunctionExpression();case n.at:this.parseDecorators();case n._class:return s=this.startNode(),this.takeDecorators(s),this.parseClass(s,!1);case n._new:return this.parseNew();case n.backQuote:return this.parseTemplate(!1);case n.doubleColon:{s=this.startNode(),this.next(),s.object=null;const t=s.callee=this.parseNoCallExpr();if("MemberExpression"===t.type)return this.finishNode(s,"BindExpression");throw this.raise(t.start,f.UnsupportedBind)}case n.hash:if(this.state.inPipeline)return s=this.startNode(),"smart"!==this.getPluginOption("pipelineOperator","proposal")&&this.raise(s.start,f.PrimaryTopicRequiresSmartPipeline),this.next(),this.primaryTopicReferenceIsAllowedInCurrentTopicContext()||this.raise(s.start,f.PrimaryTopicNotAllowed),this.registerTopicReference(),this.finishNode(s,"PipelinePrimaryTopicReference");default:throw this.unexpected()}}parseBooleanLiteral(){const t=this.startNode();return t.value=this.match(n._true),this.next(),this.finishNode(t,"BooleanLiteral")}parseMaybePrivateName(t){if(this.match(n.hash)){this.expectOnePlugin(["classPrivateProperties","classPrivateMethods"]),t||this.raise(this.state.pos,f.UnexpectedPrivateField);const e=this.startNode();return this.next(),this.assertNoSpace("Unexpected space between # and identifier"),e.id=this.parseIdentifier(!0),this.finishNode(e,"PrivateName")}return this.parseIdentifier(!0)}parseFunctionExpression(){const t=this.startNode();let e=this.startNode();return this.next(),e=this.createIdentifier(e,"function"),this.prodParam.hasYield&&this.eat(n.dot)?this.parseMetaProperty(t,e,"sent"):this.parseFunction(t)}parseMetaProperty(t,e,s){t.meta=e,"function"===e.name&&"sent"===s&&(this.isContextual(s)?this.expectPlugin("functionSent"):this.hasPlugin("functionSent")||this.unexpected());const i=this.state.containsEsc;return t.property=this.parseIdentifier(!0),(t.property.name!==s||i)&&this.raise(t.property.start,f.UnsupportedMetaProperty,e.name,s),this.finishNode(t,"MetaProperty")}parseImportMetaProperty(t){const e=this.createIdentifier(this.startNodeAtNode(t),"import");return this.expect(n.dot),this.isContextual("meta")?(this.expectPlugin("importMeta"),this.inModule||this.raiseWithData(e.start,{code:"BABEL_PARSER_SOURCETYPE_MODULE_REQUIRED"},f.ImportMetaOutsideModule),this.sawUnambiguousESM=!0):this.hasPlugin("importMeta")||this.raise(e.start,f.ImportCallArityLtOne),this.parseMetaProperty(t,e,"meta")}parseLiteral(t,e,s,i){s=s||this.state.start,i=i||this.state.startLoc;const r=this.startNodeAt(s,i);return this.addExtra(r,"rawValue",t),this.addExtra(r,"raw",this.input.slice(s,this.state.end)),r.value=t,this.next(),this.finishNode(r,e)}parseParenAndDistinguishExpression(t){const e=this.state.start,s=this.state.startLoc;let i;this.expect(n.parenL);const r=this.state.maybeInArrowParameters,a=this.state.yieldPos,o=this.state.awaitPos,h=this.state.inFSharpPipelineDirectBody;this.state.maybeInArrowParameters=!0,this.state.yieldPos=-1,this.state.awaitPos=-1,this.state.inFSharpPipelineDirectBody=!1;const p=this.state.start,c=this.state.startLoc,u=[],l=new xt,d={start:0};let m,f,D=!0;for(;!this.match(n.parenR);){if(D)D=!1;else if(this.expect(n.comma,d.start||null),this.match(n.parenR)){f=this.state.start;break}if(this.match(n.ellipsis)){const t=this.state.start,e=this.state.startLoc;m=this.state.start,u.push(this.parseParenItem(this.parseRestBinding(),t,e)),this.checkCommaAfterRest(41);break}u.push(this.parseMaybeAssign(!1,l,this.parseParenItem,d))}const y=this.state.start,x=this.state.startLoc;this.expect(n.parenR),this.state.maybeInArrowParameters=r,this.state.inFSharpPipelineDirectBody=h;let g=this.startNodeAt(e,s);if(t&&this.shouldParseArrow()&&(g=this.parseArrow(g))){this.isAwaitAllowed()||this.state.maybeInAsyncArrowHead||(this.state.awaitPos=o),this.checkYieldAwaitInDefaultParams(),this.state.yieldPos=a,this.state.awaitPos=o;for(let t=0;t1?(i=this.startNodeAt(p,c),i.expressions=u,this.finishNodeAt(i,"SequenceExpression",y,x)):i=u[0],!this.options.createParenthesizedExpressions)return this.addExtra(i,"parenthesized",!0),this.addExtra(i,"parenStart",e),i;const P=this.startNodeAt(e,s);return P.expression=i,this.finishNode(P,"ParenthesizedExpression"),P}shouldParseArrow(){return!this.canInsertSemicolon()}parseArrow(t){if(this.eat(n.arrow))return t}parseParenItem(t,e,s){return t}parseNew(){const t=this.startNode();let e=this.startNode();if(this.next(),e=this.createIdentifier(e,"new"),this.eat(n.dot)){const s=this.parseMetaProperty(t,e,"target");if(!this.scope.inNonArrowFunction&&!this.scope.inClass){let t=f.UnexpectedNewTarget;this.hasPlugin("classProperties")&&(t+=" or class properties"),this.raise(s.start,t)}return s}return t.callee=this.parseNoCallExpr(),"Import"===t.callee.type?this.raise(t.callee.start,f.ImportCallNotNewExpression):"OptionalMemberExpression"===t.callee.type||"OptionalCallExpression"===t.callee.type?this.raise(this.state.lastTokEnd,f.OptionalChainingNoNew):this.eat(n.questionDot)&&this.raise(this.state.start,f.OptionalChainingNoNew),this.parseNewArguments(t),this.finishNode(t,"NewExpression")}parseNewArguments(t){if(this.eat(n.parenL)){const e=this.parseExprList(n.parenR);this.toReferencedList(e),t.arguments=e}else t.arguments=[]}parseTemplateElement(t){const e=this.startNode();return null===this.state.value&&(t||this.raise(this.state.start+1,f.InvalidEscapeSequenceTemplate)),e.value={raw:this.input.slice(this.state.start,this.state.end).replace(/\r\n?/g,"\n"),cooked:this.state.value},this.next(),e.tail=this.match(n.backQuote),this.finishNode(e,"TemplateElement")}parseTemplate(t){const e=this.startNode();this.next(),e.expressions=[];let s=this.parseTemplateElement(t);for(e.quasis=[s];!s.tail;)this.expect(n.dollarBraceL),e.expressions.push(this.parseExpression()),this.expect(n.braceR),e.quasis.push(s=this.parseTemplateElement(t));return this.next(),this.finishNode(e,"TemplateLiteral")}parseObj(t,e,s,i){const r=Object.create(null);let a=!0;const o=this.startNode();for(o.properties=[],this.next();!this.eat(t);){if(a)a=!1;else if(this.expect(n.comma),this.match(t)){this.addExtra(o,"trailingComma",this.state.lastTokStart),this.next();break}const s=this.parseObjectMember(e,i);e||this.checkDuplicatedProto(s,r,i),s.shorthand&&this.addExtra(s,"shorthand",!0),o.properties.push(s)}let h="ObjectExpression";return e?h="ObjectPattern":s&&(h="RecordExpression"),this.finishNode(o,h)}isAsyncProp(t){return!t.computed&&"Identifier"===t.key.type&&"async"===t.key.name&&(this.match(n.name)||this.match(n.num)||this.match(n.string)||this.match(n.bracketL)||this.state.type.keyword||this.match(n.star))&&!this.hasPrecedingLineBreak()}parseObjectMember(t,e){let s=[];if(this.match(n.at))for(this.hasPlugin("decorators")&&this.raise(this.state.start,f.UnsupportedPropertyDecorator);this.match(n.at);)s.push(this.parseDecorator());const i=this.startNode();let r,a,o=!1,h=!1;if(this.match(n.ellipsis))return s.length&&this.unexpected(),t?(this.next(),i.argument=this.parseIdentifier(),this.checkCommaAfterRest(125),this.finishNode(i,"RestElement")):this.parseSpread();s.length&&(i.decorators=s,s=[]),i.method=!1,(t||e)&&(r=this.state.start,a=this.state.startLoc),t||(o=this.eat(n.star));const p=this.state.containsEsc;return this.parsePropertyName(i,!1),t||p||o||!this.isAsyncProp(i)?h=!1:(h=!0,o=this.eat(n.star),this.parsePropertyName(i,!1)),this.parseObjPropValue(i,r,a,o,h,t,e,p),i}isGetterOrSetterMethod(t,e){return!e&&!t.computed&&"Identifier"===t.key.type&&("get"===t.key.name||"set"===t.key.name)&&(this.match(n.string)||this.match(n.num)||this.match(n.bracketL)||this.match(n.name)||!!this.state.type.keyword)}getGetterSetterExpectedParamCount(t){return"get"===t.kind?0:1}checkGetterSetterParams(t){const e=this.getGetterSetterExpectedParamCount(t),s=t.start;t.params.length!==e&&("get"===t.kind?this.raise(s,f.BadGetterArity):this.raise(s,f.BadSetterArity)),"set"===t.kind&&"RestElement"===t.params[t.params.length-1].type&&this.raise(s,f.BadSetterRestParameter)}parseObjectMethod(t,e,s,i,r){return s||e||this.match(n.parenL)?(i&&this.unexpected(),t.kind="method",t.method=!0,this.parseMethod(t,e,s,!1,!1,"ObjectMethod")):!r&&this.isGetterOrSetterMethod(t,i)?((e||s)&&this.unexpected(),t.kind=t.key.name,this.parsePropertyName(t,!1),this.parseMethod(t,!1,!1,!1,!1,"ObjectMethod"),this.checkGetterSetterParams(t),t):void 0}parseObjectProperty(t,e,s,i,r){return t.shorthand=!1,this.eat(n.colon)?(t.value=i?this.parseMaybeDefault(this.state.start,this.state.startLoc):this.parseMaybeAssign(!1,r),this.finishNode(t,"ObjectProperty")):t.computed||"Identifier"!==t.key.type?void 0:(this.checkReservedWord(t.key.name,t.key.start,!0,!0),i?t.value=this.parseMaybeDefault(e,s,t.key.__clone()):this.match(n.eq)&&r?(-1===r.shorthandAssign&&(r.shorthandAssign=this.state.start),t.value=this.parseMaybeDefault(e,s,t.key.__clone())):t.value=t.key.__clone(),t.shorthand=!0,this.finishNode(t,"ObjectProperty"))}parseObjPropValue(t,e,s,i,r,a,n,o){const h=this.parseObjectMethod(t,i,r,a,o)||this.parseObjectProperty(t,e,s,a,n);return h||this.unexpected(),h}parsePropertyName(t,e){if(this.eat(n.bracketL))t.computed=!0,t.key=this.parseMaybeAssign(),this.expect(n.bracketR);else{const s=this.state.inPropertyName;this.state.inPropertyName=!0,t.key=this.match(n.num)||this.match(n.string)||this.match(n.bigint)?this.parseExprAtom():this.parseMaybePrivateName(e),"PrivateName"!==t.key.type&&(t.computed=!1),this.state.inPropertyName=s}return t.key}initFunction(t,e){t.id=null,t.generator=!1,t.async=!!e}parseMethod(t,e,s,i,r,a,n=!1){const o=this.state.yieldPos,h=this.state.awaitPos;this.state.yieldPos=-1,this.state.awaitPos=-1,this.initFunction(t,s),t.generator=!!e;const p=i;return this.scope.enter(18|(n?64:0)|(r?32:0)),this.prodParam.enter(et(s,t.generator)),this.parseFunctionParams(t,p),this.parseFunctionBodyAndFinish(t,a,!0),this.prodParam.exit(),this.scope.exit(),this.state.yieldPos=o,this.state.awaitPos=h,t}parseArrowExpression(t,e,s,i){this.scope.enter(6),this.prodParam.enter(et(s,!1)),this.initFunction(t,s);const r=this.state.maybeInArrowParameters,a=this.state.yieldPos,n=this.state.awaitPos;return e&&(this.state.maybeInArrowParameters=!0,this.setArrowFunctionParameters(t,e,i)),this.state.maybeInArrowParameters=!1,this.state.yieldPos=-1,this.state.awaitPos=-1,this.parseFunctionBody(t,!0),this.prodParam.exit(),this.scope.exit(),this.state.maybeInArrowParameters=r,this.state.yieldPos=a,this.state.awaitPos=n,this.finishNode(t,"ArrowFunctionExpression")}setArrowFunctionParameters(t,e,s){t.params=this.toAssignableList(e,s)}parseFunctionBodyAndFinish(t,e,s=!1){this.parseFunctionBody(t,!1,s),this.finishNode(t,e)}parseFunctionBody(t,e,s=!1){const i=e&&!this.match(n.braceL),r=this.state.inParameters;if(this.state.inParameters=!1,i)t.body=this.parseMaybeAssign(),this.checkParams(t,!1,e,!1);else{const i=this.state.strict,r=this.state.labels;this.state.labels=[],this.prodParam.enter(4|this.prodParam.currentFlags()),t.body=this.parseBlock(!0,!1,r=>{const a=!this.isSimpleParamList(t.params);if(r&&a){const e="method"!==t.kind&&"constructor"!==t.kind||!t.key?t.start:t.key.end;this.raise(e,f.IllegalLanguageModeDirective)}const n=!i&&this.state.strict;this.checkParams(t,!(this.state.strict||e||s||a),e,n),this.state.strict&&t.id&&this.checkLVal(t.id,65,void 0,"function name",void 0,n)}),this.prodParam.exit(),this.state.labels=r}this.state.inParameters=r}isSimpleParamList(t){for(let e=0,s=t.length;e=1}topicReferenceWasUsedInCurrentTopicContext(){return null!=this.state.topicContext.maxTopicIndex&&this.state.topicContext.maxTopicIndex>=0}parseFSharpPipelineBody(t,e){const s=this.state.start,i=this.state.startLoc;this.state.potentialArrowAt=this.state.start;const r=this.state.inFSharpPipelineDirectBody;this.state.inFSharpPipelineDirectBody=!0;const a=this.parseExprOp(this.parseMaybeUnary(),s,i,t,e);return this.state.inFSharpPipelineDirectBody=r,a}}{parseTopLevel(t,e){if(e.sourceType=this.options.sourceType,e.interpreter=this.parseInterpreterDirective(),this.parseBlockBody(e,!0,!0,n.eof),this.inModule&&!this.options.allowUndeclaredExports&&this.scope.undefinedExports.size>0)for(let t=0,e=Array.from(this.scope.undefinedExports);tthis.parseStatement("do")),this.state.labels.pop(),this.expect(n._while),t.test=this.parseHeaderExpression(),this.eat(n.semi),this.finishNode(t,"DoWhileStatement")}parseForStatement(t){this.next(),this.state.labels.push(Et);let e=-1;if(this.isAwaitAllowed()&&this.eatContextual("await")&&(e=this.state.lastTokStart),this.scope.enter(0),this.expect(n.parenL),this.match(n.semi))return e>-1&&this.unexpected(e),this.parseFor(t,null);const s=this.isLet();if(this.match(n._var)||this.match(n._const)||s){const i=this.startNode(),r=s?"let":this.state.value;return this.next(),this.parseVar(i,!0,r),this.finishNode(i,"VariableDeclaration"),(this.match(n._in)||this.isContextual("of"))&&1===i.declarations.length?this.parseForIn(t,i,e):(e>-1&&this.unexpected(e),this.parseFor(t,i))}const i=new xt,r=this.parseExpression(!0,i);if(this.match(n._in)||this.isContextual("of")){this.toAssignable(r);const s=this.isContextual("of")?"for-of statement":"for-in statement";return this.checkLVal(r,void 0,void 0,s),this.parseForIn(t,r,e)}return this.checkExpressionErrors(i,!0),e>-1&&this.unexpected(e),this.parseFor(t,r)}parseFunctionStatement(t,e,s){return this.next(),this.parseFunction(t,1|(s?0:2),e)}parseIfStatement(t){return this.next(),t.test=this.parseHeaderExpression(),t.consequent=this.parseStatement("if"),t.alternate=this.eat(n._else)?this.parseStatement("if"):null,this.finishNode(t,"IfStatement")}parseReturnStatement(t){return this.prodParam.hasReturn||this.options.allowReturnOutsideFunction||this.raise(this.state.start,f.IllegalReturn),this.next(),this.isLineTerminator()?t.argument=null:(t.argument=this.parseExpression(),this.semicolon()),this.finishNode(t,"ReturnStatement")}parseSwitchStatement(t){this.next(),t.discriminant=this.parseHeaderExpression();const e=t.cases=[];let s,i;for(this.expect(n.braceL),this.state.labels.push(Ct),this.scope.enter(0);!this.match(n.braceR);)if(this.match(n._case)||this.match(n._default)){const t=this.match(n._case);s&&this.finishNode(s,"SwitchCase"),e.push(s=this.startNode()),s.consequent=[],this.next(),t?s.test=this.parseExpression():(i&&this.raise(this.state.lastTokStart,f.MultipleDefaultsInSwitch),i=!0,s.test=null),this.expect(n.colon)}else s?s.consequent.push(this.parseStatement(null)):this.unexpected();return this.scope.exit(),s&&this.finishNode(s,"SwitchCase"),this.next(),this.state.labels.pop(),this.finishNode(t,"SwitchStatement")}parseThrowStatement(t){return this.next(),o.test(this.input.slice(this.state.lastTokEnd,this.state.start))&&this.raise(this.state.lastTokEnd,f.NewlineAfterThrow),t.argument=this.parseExpression(),this.semicolon(),this.finishNode(t,"ThrowStatement")}parseTryStatement(t){if(this.next(),t.block=this.parseBlock(),t.handler=null,this.match(n._catch)){const e=this.startNode();if(this.next(),this.match(n.parenL)){this.expect(n.parenL),e.param=this.parseBindingAtom();const t="Identifier"===e.param.type;this.scope.enter(t?8:0),this.checkLVal(e.param,9,null,"catch clause"),this.expect(n.parenR)}else e.param=null,this.scope.enter(0);e.body=this.withTopicForbiddingContext(()=>this.parseBlock(!1,!1)),this.scope.exit(),t.handler=this.finishNode(e,"CatchClause")}return t.finalizer=this.eat(n._finally)?this.parseBlock():null,t.handler||t.finalizer||this.raise(t.start,f.NoCatchOrFinally),this.finishNode(t,"TryStatement")}parseVarStatement(t,e){return this.next(),this.parseVar(t,!1,e),this.semicolon(),this.finishNode(t,"VariableDeclaration")}parseWhileStatement(t){return this.next(),t.test=this.parseHeaderExpression(),this.state.labels.push(Et),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("while")),this.state.labels.pop(),this.finishNode(t,"WhileStatement")}parseWithStatement(t){return this.state.strict&&this.raise(this.state.start,f.StrictWith),this.next(),t.object=this.parseHeaderExpression(),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("with")),this.finishNode(t,"WithStatement")}parseEmptyStatement(t){return this.next(),this.finishNode(t,"EmptyStatement")}parseLabeledStatement(t,e,s,i){for(let t=0,i=this.state.labels;t=0;e--){const s=this.state.labels[e];if(s.statementStart!==t.start)break;s.statementStart=this.state.start,s.kind=r}return this.state.labels.push({name:e,kind:r,statementStart:this.state.start}),t.body=this.parseStatement(i?-1===i.indexOf("label")?i+"label":i:"label"),this.state.labels.pop(),t.label=s,this.finishNode(t,"LabeledStatement")}parseExpressionStatement(t,e){return t.expression=e,this.semicolon(),this.finishNode(t,"ExpressionStatement")}parseBlock(t=!1,e=!0,s){const i=this.startNode();return this.expect(n.braceL),e&&this.scope.enter(0),this.parseBlockBody(i,t,!1,n.braceR,s),e&&this.scope.exit(),this.finishNode(i,"BlockStatement")}isValidDirective(t){return"ExpressionStatement"===t.type&&"StringLiteral"===t.expression.type&&!t.expression.extra.parenthesized}parseBlockBody(t,e,s,i,r){const a=t.body=[],n=t.directives=[];this.parseBlockOrModuleBlockBody(a,e?n:void 0,s,i,r)}parseBlockOrModuleBlockBody(t,e,s,i,r){const a=[],n=this.state.strict;let o=!1,h=!1;for(;!this.match(i);){!h&&this.state.octalPositions.length&&a.push(...this.state.octalPositions);const i=this.parseStatement(null,s);if(e&&!h&&this.isValidDirective(i)){const t=this.stmtToDirective(i);e.push(t),o||"use strict"!==t.value.value||(o=!0,this.setStrict(!0))}else h=!0,t.push(i)}if(this.state.strict&&a.length)for(let t=0;tthis.parseStatement("for")),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,"ForStatement")}parseForIn(t,e,s){const i=this.match(n._in);return this.next(),i?s>-1&&this.unexpected(s):t.await=s>-1,"VariableDeclaration"!==e.type||null==e.declarations[0].init||i&&!this.state.strict&&"var"===e.kind&&"Identifier"===e.declarations[0].id.type?"AssignmentPattern"===e.type&&this.raise(e.start,f.InvalidLhs,"for-loop"):this.raise(e.start,f.ForInOfLoopInitializer,i?"for-in":"for-of"),t.left=e,t.right=i?this.parseExpression():this.parseMaybeAssign(),this.expect(n.parenR),t.body=this.withTopicForbiddingContext(()=>this.parseStatement("for")),this.scope.exit(),this.state.labels.pop(),this.finishNode(t,i?"ForInStatement":"ForOfStatement")}parseVar(t,e,s){const i=t.declarations=[],r=this.hasPlugin("typescript");for(t.kind=s;;){const t=this.startNode();if(this.parseVarId(t,s),this.eat(n.eq)?t.init=this.parseMaybeAssign(e):("const"!==s||this.match(n._in)||this.isContextual("of")?"Identifier"===t.id.type||e&&(this.match(n._in)||this.isContextual("of"))||this.raise(this.state.lastTokEnd,f.DeclarationMissingInitializer,"Complex binding patterns"):r||this.unexpected(),t.init=null),i.push(this.finishNode(t,"VariableDeclarator")),!this.eat(n.comma))break}return t}parseVarId(t,e){t.id=this.parseBindingAtom(),this.checkLVal(t.id,"var"===e?5:9,void 0,"variable declaration","var"!==e)}parseFunction(t,e=0,s=!1){const i=1&e,r=2&e,a=!(!i||4&e);this.initFunction(t,s),this.match(n.star)&&r&&this.raise(this.state.start,f.GeneratorInSingleStatementContext),t.generator=this.eat(n.star),i&&(t.id=this.parseFunctionId(a));const o=this.state.maybeInArrowParameters,h=this.state.yieldPos,p=this.state.awaitPos;return this.state.maybeInArrowParameters=!1,this.state.yieldPos=-1,this.state.awaitPos=-1,this.scope.enter(2),this.prodParam.enter(et(s,t.generator)),i||(t.id=this.parseFunctionId()),this.parseFunctionParams(t),this.withTopicForbiddingContext(()=>{this.parseFunctionBodyAndFinish(t,i?"FunctionDeclaration":"FunctionExpression")}),this.prodParam.exit(),this.scope.exit(),i&&!r&&this.registerFunctionStatementId(t),this.state.maybeInArrowParameters=o,this.state.yieldPos=h,this.state.awaitPos=p,t}parseFunctionId(t){return t||this.match(n.name)?this.parseIdentifier():null}parseFunctionParams(t,e){const s=this.state.inParameters;this.state.inParameters=!0,this.expect(n.parenL),t.params=this.parseBindingList(n.parenR,41,!1,e),this.state.inParameters=s,this.checkYieldAwaitInDefaultParams()}registerFunctionStatementId(t){t.id&&this.scope.declareName(t.id.name,this.state.strict||t.generator||t.async?this.scope.treatFunctionsAsVar?5:9:17,t.id.start)}parseClass(t,e,s){this.next(),this.takeDecorators(t);const i=this.state.strict;return this.state.strict=!0,this.parseClassId(t,e,s),this.parseClassSuper(t),t.body=this.parseClassBody(!!t.superClass,i),this.state.strict=i,this.finishNode(t,e?"ClassDeclaration":"ClassExpression")}isClassProperty(){return this.match(n.eq)||this.match(n.semi)||this.match(n.braceR)}isClassMethod(){return this.match(n.parenL)}isNonstaticConstructor(t){return!(t.computed||t.static||"constructor"!==t.key.name&&"constructor"!==t.key.value)}parseClassBody(t,e){this.classScope.enter();const s={hadConstructor:!1};let i=[];const r=this.startNode();if(r.body=[],this.expect(n.braceL),this.withTopicForbiddingContext(()=>{for(;!this.match(n.braceR);){if(this.eat(n.semi)){if(i.length>0)throw this.raise(this.state.lastTokEnd,f.DecoratorSemicolon);continue}if(this.match(n.at)){i.push(this.parseDecorator());continue}const e=this.startNode();i.length&&(e.decorators=i,this.resetStartLocationFromNode(e,i[0]),i=[]),this.parseClassMember(r,e,s,t),"constructor"===e.kind&&e.decorators&&e.decorators.length>0&&this.raise(e.start,f.DecoratorConstructor)}}),e||(this.state.strict=!1),this.next(),i.length)throw this.raise(this.state.start,f.TrailingDecorator);return this.classScope.exit(),this.finishNode(r,"ClassBody")}parseClassMemberFromModifier(t,e){const s=this.state.containsEsc,i=this.parseIdentifier(!0);if(this.isClassMethod()){const s=e;return s.kind="method",s.computed=!1,s.key=i,s.static=!1,this.pushClassMethod(t,s,!1,!1,!1,!1),!0}if(this.isClassProperty()){const s=e;return s.computed=!1,s.key=i,s.static=!1,t.body.push(this.parseClassProperty(s)),!0}if(s)throw this.unexpected();return!1}parseClassMember(t,e,s,i){const r=this.isContextual("static");r&&this.parseClassMemberFromModifier(t,e)||this.parseClassMemberWithIsStatic(t,e,s,r,i)}parseClassMemberWithIsStatic(t,e,s,i,r){const a=e,o=e,h=e,p=e,c=a,u=a;if(e.static=i,this.eat(n.star))return c.kind="method",this.parseClassPropertyName(c),"PrivateName"===c.key.type?void this.pushClassPrivateMethod(t,o,!0,!1):(this.isNonstaticConstructor(a)&&this.raise(a.key.start,f.ConstructorIsGenerator),void this.pushClassMethod(t,a,!0,!1,!1,!1));const l=this.state.containsEsc,d=this.parseClassPropertyName(e),m="PrivateName"===d.type,D="Identifier"===d.type,y=this.state.start;if(this.parsePostMemberNameModifiers(u),this.isClassMethod()){if(c.kind="method",m)return void this.pushClassPrivateMethod(t,o,!1,!1);const e=this.isNonstaticConstructor(a);let i=!1;e&&(a.kind="constructor",s.hadConstructor&&!this.hasPlugin("typescript")&&this.raise(d.start,f.DuplicateConstructor),s.hadConstructor=!0,i=r),this.pushClassMethod(t,a,!1,!1,e,i)}else if(this.isClassProperty())m?this.pushClassPrivateProperty(t,p):this.pushClassProperty(t,h);else if(!D||"async"!==d.name||l||this.isLineTerminator())!D||"get"!==d.name&&"set"!==d.name||l||this.match(n.star)&&this.isLineTerminator()?this.isLineTerminator()?m?this.pushClassPrivateProperty(t,p):this.pushClassProperty(t,h):this.unexpected():(c.kind=d.name,this.parseClassPropertyName(a),"PrivateName"===c.key.type?this.pushClassPrivateMethod(t,o,!1,!1):(this.isNonstaticConstructor(a)&&this.raise(a.key.start,f.ConstructorIsAccessor),this.pushClassMethod(t,a,!1,!1,!1,!1)),this.checkGetterSetterParams(a));else{const e=this.eat(n.star);u.optional&&this.unexpected(y),c.kind="method",this.parseClassPropertyName(c),this.parsePostMemberNameModifiers(u),"PrivateName"===c.key.type?this.pushClassPrivateMethod(t,o,e,!0):(this.isNonstaticConstructor(a)&&this.raise(a.key.start,f.ConstructorIsAsync),this.pushClassMethod(t,a,e,!0,!1,!1))}}parseClassPropertyName(t){const e=this.parsePropertyName(t,!0);return t.computed||!t.static||"prototype"!==e.name&&"prototype"!==e.value||this.raise(e.start,f.StaticPrototype),"PrivateName"===e.type&&"constructor"===e.id.name&&this.raise(e.start,f.ConstructorClassPrivateField),e}pushClassProperty(t,e){e.computed||"constructor"!==e.key.name&&"constructor"!==e.key.value||this.raise(e.key.start,f.ConstructorClassField),t.body.push(this.parseClassProperty(e))}pushClassPrivateProperty(t,e){this.expectPlugin("classPrivateProperties",e.key.start);const s=this.parseClassPrivateProperty(e);t.body.push(s),this.classScope.declarePrivateName(s.key.id.name,0,s.key.start)}pushClassMethod(t,e,s,i,r,a){t.body.push(this.parseMethod(e,s,i,r,a,"ClassMethod",!0))}pushClassPrivateMethod(t,e,s,i){this.expectPlugin("classPrivateMethods",e.key.start);const r=this.parseMethod(e,s,i,!1,!1,"ClassPrivateMethod",!0);t.body.push(r);const a="get"===r.kind?r.static?6:2:"set"===r.kind?r.static?5:1:0;this.classScope.declarePrivateName(r.key.id.name,a,r.key.start)}parsePostMemberNameModifiers(t){}parseAccessModifier(){}parseClassPrivateProperty(t){return this.scope.enter(80),this.prodParam.enter(0),t.value=this.eat(n.eq)?this.parseMaybeAssign():null,this.semicolon(),this.prodParam.exit(),this.scope.exit(),this.finishNode(t,"ClassPrivateProperty")}parseClassProperty(t){return t.typeAnnotation||this.expectPlugin("classProperties"),this.scope.enter(80),this.prodParam.enter(0),this.match(n.eq)?(this.expectPlugin("classProperties"),this.next(),t.value=this.parseMaybeAssign()):t.value=null,this.semicolon(),this.prodParam.exit(),this.scope.exit(),this.finishNode(t,"ClassProperty")}parseClassId(t,e,s,i=139){this.match(n.name)?(t.id=this.parseIdentifier(),e&&this.checkLVal(t.id,i,void 0,"class name")):s||!e?t.id=null:this.unexpected(null,f.MissingClassName)}parseClassSuper(t){t.superClass=this.eat(n._extends)?this.parseExprSubscripts():null}parseExport(t){const e=this.maybeParseExportDefaultSpecifier(t),s=!e||this.eat(n.comma),i=s&&this.eatExportStar(t),r=i&&this.maybeParseExportNamespaceSpecifier(t),a=s&&(!r||this.eat(n.comma)),o=e||i;if(i&&!r)return e&&this.unexpected(),this.parseExportFrom(t,!0),this.finishNode(t,"ExportAllDeclaration");const h=this.maybeParseExportNamedSpecifiers(t);if(e&&s&&!i&&!h||r&&a&&!h)throw this.unexpected(null,n.braceL);let p;if(o||h?(p=!1,this.parseExportFrom(t,o)):p=this.maybeParseExportDeclaration(t),o||h||p)return this.checkExport(t,!0,!1,!!t.source),this.finishNode(t,"ExportNamedDeclaration");if(this.eat(n._default))return t.declaration=this.parseExportDefaultExpression(),this.checkExport(t,!0,!0),this.finishNode(t,"ExportDefaultDeclaration");throw this.unexpected(null,n.braceL)}eatExportStar(t){return this.eat(n.star)}maybeParseExportDefaultSpecifier(t){if(this.isExportDefaultSpecifier()){this.expectPlugin("exportDefaultFrom");const e=this.startNode();return e.exported=this.parseIdentifier(!0),t.specifiers=[this.finishNode(e,"ExportDefaultSpecifier")],!0}return!1}maybeParseExportNamespaceSpecifier(t){if(this.isContextual("as")){t.specifiers||(t.specifiers=[]);const e=this.startNodeAt(this.state.lastTokStart,this.state.lastTokStartLoc);return this.next(),e.exported=this.parseIdentifier(!0),t.specifiers.push(this.finishNode(e,"ExportNamespaceSpecifier")),!0}return!1}maybeParseExportNamedSpecifiers(t){return!!this.match(n.braceL)&&(t.specifiers||(t.specifiers=[]),t.specifiers.push(...this.parseExportSpecifiers()),t.source=null,t.declaration=null,!0)}maybeParseExportDeclaration(t){if(this.shouldParseExportDeclaration()){if(this.isContextual("async")){const t=this.nextTokenStart();this.isUnparsedContextual(t,"function")||this.unexpected(t,n._function)}return t.specifiers=[],t.source=null,t.declaration=this.parseExportDeclaration(t),!0}return!1}isAsyncFunction(){if(!this.isContextual("async"))return!1;const t=this.nextTokenStart();return!o.test(this.input.slice(this.state.pos,t))&&this.isUnparsedContextual(t,"function")}parseExportDefaultExpression(){const t=this.startNode(),e=this.isAsyncFunction();if(this.match(n._function)||e)return this.next(),e&&this.next(),this.parseFunction(t,5,e);if(this.match(n._class))return this.parseClass(t,!0,!0);if(this.match(n.at))return this.hasPlugin("decorators")&&this.getPluginOption("decorators","decoratorsBeforeExport")&&this.raise(this.state.start,f.DecoratorBeforeExport),this.parseDecorators(!1),this.parseClass(t,!0,!0);if(this.match(n._const)||this.match(n._var)||this.isLet())throw this.raise(this.state.start,f.UnsupportedDefaultExport);{const t=this.parseMaybeAssign();return this.semicolon(),t}}parseExportDeclaration(t){return this.parseStatement(null)}isExportDefaultSpecifier(){if(this.match(n.name))return"async"!==this.state.value&&"let"!==this.state.value;if(!this.match(n._default))return!1;const t=this.nextTokenStart();return 44===this.input.charCodeAt(t)||this.isUnparsedContextual(t,"from")}parseExportFrom(t,e){this.eatContextual("from")?(t.source=this.parseImportSource(),this.checkExport(t)):e?this.unexpected():t.source=null,this.semicolon()}shouldParseExportDeclaration(){if(this.match(n.at)&&(this.expectOnePlugin(["decorators","decorators-legacy"]),this.hasPlugin("decorators"))){if(!this.getPluginOption("decorators","decoratorsBeforeExport"))return!0;this.unexpected(this.state.start,f.DecoratorBeforeExport)}return"var"===this.state.type.keyword||"const"===this.state.type.keyword||"function"===this.state.type.keyword||"class"===this.state.type.keyword||this.isLet()||this.isAsyncFunction()}checkExport(t,e,s,i){if(e)if(s)this.checkDuplicateExports(t,"default");else if(t.specifiers&&t.specifiers.length)for(let e=0,s=t.specifiers;e-1&&this.raise(t.start,"default"===e?f.DuplicateDefaultExport:f.DuplicateExport,e),this.state.exportedIdentifiers.push(e)}parseExportSpecifiers(){const t=[];let e=!0;for(this.expect(n.braceL);!this.eat(n.braceR);){if(e)e=!1;else if(this.expect(n.comma),this.eat(n.braceR))break;const s=this.startNode();s.local=this.parseIdentifier(!0),s.exported=this.eatContextual("as")?this.parseIdentifier(!0):s.local.__clone(),t.push(this.finishNode(s,"ExportSpecifier"))}return t}parseImport(t){if(t.specifiers=[],!this.match(n.string)){const e=!this.maybeParseDefaultImportSpecifier(t)||this.eat(n.comma),s=e&&this.maybeParseStarImportSpecifier(t);e&&!s&&this.parseNamedImportSpecifiers(t),this.expectContextual("from")}return t.source=this.parseImportSource(),this.semicolon(),this.finishNode(t,"ImportDeclaration")}parseImportSource(){return this.match(n.string)||this.unexpected(),this.parseExprAtom()}shouldParseDefaultImport(t){return this.match(n.name)}parseImportSpecifierLocal(t,e,s,i){e.local=this.parseIdentifier(),this.checkLVal(e.local,9,void 0,i),t.specifiers.push(this.finishNode(e,s))}maybeParseDefaultImportSpecifier(t){return!!this.shouldParseDefaultImport(t)&&(this.parseImportSpecifierLocal(t,this.startNode(),"ImportDefaultSpecifier","default import specifier"),!0)}maybeParseStarImportSpecifier(t){if(this.match(n.star)){const e=this.startNode();return this.next(),this.expectContextual("as"),this.parseImportSpecifierLocal(t,e,"ImportNamespaceSpecifier","import namespace specifier"),!0}return!1}parseNamedImportSpecifiers(t){let e=!0;for(this.expect(n.braceL);!this.eat(n.braceR);){if(e)e=!1;else{if(this.eat(n.colon))throw this.raise(this.state.start,f.DestructureNamedImport);if(this.expect(n.comma),this.eat(n.braceR))break}this.parseImportSpecifier(t)}}parseImportSpecifier(t){const e=this.startNode();e.imported=this.parseIdentifier(!0),this.eatContextual("as")?e.local=this.parseIdentifier():(this.checkReservedWord(e.imported.name,e.start,!0,!0),e.local=e.imported.__clone()),this.checkLVal(e.local,9,void 0,"import specifier"),t.specifiers.push(this.finishNode(e,"ImportSpecifier"))}}{constructor(t,e){super(t=function(t){const e={};for(let s=0,i=Object.keys(ut);s"'".concat(t,"'")).join(", "));if(at(t,"recordAndTuple")&&!ht.includes(nt(t,"recordAndTuple","syntaxType")))throw new Error("'recordAndTuple' requires 'syntaxType' option whose value should be one of: "+ht.map(t=>"'".concat(t,"'")).join(", "))}(t.plugins),s=function(t){const e=ct.filter(e=>at(t,e)),s=e.join("/");let i=St[s];if(!i){i=At;for(let t=0;t{const n=Kt;let o;try{o=function(t,e){let s;for(let i=0;in[t](i,e),s.map(Xt))}catch(t){throw e(t.message.replace(/ \(.*\)/,""),{start:{line:t.loc.line,column:t.loc.column+1}})}return delete o.tokens,Wt(o,Object.assign({},a,{originalText:i}))}}const Qt=Gt("parse",["jsx","flow"]),Yt=Gt("parse",["jsx",["flow",{all:!0,enums:!0}]]),$t=Gt("parse",["jsx","typescript"],["typescript"]),Zt=Gt("parseExpression",["jsx"]);function te(t,s){switch(t.type){case"ArrayExpression":return t.elements.forEach(i);case"ObjectExpression":return t.properties.forEach(i);case"ObjectProperty":if(t.computed)throw r("computed");if(t.shorthand)throw r("shorthand");return[t.key,t.value].forEach(i);case"UnaryExpression":switch(t.operator){case"+":case"-":return i(t.argument);default:throw r("operator")}case"Identifier":if(s&&"ObjectProperty"===s.type&&s.key===t)return;throw r();case"NullLiteral":case"BooleanLiteral":case"NumericLiteral":case"StringLiteral":return;default:throw r()}function i(e){return te(e,t)}function r(s){const i=s?"".concat(t.type," with ").concat(s,"=").concat(JSON.stringify(t[s])):t.type;return e("".concat(i," is not allowed in JSON."),{start:{line:t.loc.start.line,column:t.loc.start.column+1}})}}const ee=Object.assign({parse:Qt,astFormat:"estree",hasPragma:Jt},m),se=Object.assign({},ee,{parse:Yt}),ie=Object.assign({},ee,{parse:$t}),re=Object.assign({},ee,{parse:Zt});var ae={parsers:{babel:ee,"babel-flow":se,"babel-ts":ie,json:Object.assign({},re,{hasPragma:()=>!0}),json5:re,"json-stringify":Object.assign({parse:function(t,e,s){const i=Zt(t,e,s);return i.comments.forEach(te),te(i),i},astFormat:"estree-json"},m),__js_expression:re,__vue_expression:re,__vue_event_binding:ee}},ne=ae.parsers;t.default=ae,t.parsers=ne,Object.defineProperty(t,"__esModule",{value:!0})})); },{}],91:[function(require,module,exports){ (function (global){ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.prettier = factory()); }(this, (function () { 'use strict'; var name = "prettier"; var version = "2.0.5"; var description = "Prettier is an opinionated code formatter"; var bin = "./bin/prettier.js"; var repository = "prettier/prettier"; var homepage = "https://prettier.io"; var author = "James Long"; var license = "MIT"; var main = "./index.js"; var engines = { node: ">=10.13.0" }; var dependencies = { "@angular/compiler": "9.0.5", "@babel/code-frame": "7.8.0", "@babel/parser": "7.9.4", "@glimmer/syntax": "0.50.0", "@iarna/toml": "2.2.3", "@typescript-eslint/typescript-estree": "2.26.0", "angular-estree-parser": "1.3.0", "angular-html-parser": "1.4.0", camelcase: "5.3.1", chalk: "4.0.0", "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", "cjk-regex": "2.0.0", cosmiconfig: "6.0.0", dashify: "2.0.0", dedent: "0.7.0", diff: "4.0.2", editorconfig: "0.15.3", "editorconfig-to-prettier": "0.1.1", "escape-string-regexp": "2.0.0", esutils: "2.0.3", "fast-glob": "3.2.2", "find-parent-dir": "0.3.0", "find-project-root": "1.1.1", "flow-parser": "0.122.0", "get-stream": "5.1.0", globby: "11.0.0", graphql: "15.0.0", "html-element-attributes": "2.2.1", "html-styles": "1.0.0", "html-tag-names": "1.1.5", ignore: "4.0.6", "jest-docblock": "25.2.6", "json-stable-stringify": "1.0.1", leven: "3.1.0", "lines-and-columns": "1.1.6", "linguist-languages": "7.9.0", lodash: "4.17.15", mem: "6.0.1", minimatch: "3.0.4", minimist: "1.2.5", "n-readlines": "1.0.0", "please-upgrade-node": "3.2.0", "postcss-less": "3.1.4", "postcss-media-query-parser": "0.2.3", "postcss-scss": "2.0.0", "postcss-selector-parser": "2.2.3", "postcss-values-parser": "2.0.1", "regexp-util": "1.2.2", "remark-math": "1.0.6", "remark-parse": "5.0.0", resolve: "1.16.1", semver: "7.1.3", srcset: "2.0.1", "string-width": "4.2.0", typescript: "3.8.3", "unicode-regex": "3.0.0", unified: "9.0.0", vnopts: "1.0.2", "yaml-unist-parser": "1.1.1" }; var devDependencies = { "@babel/core": "7.9.0", "@babel/preset-env": "7.9.0", "@rollup/plugin-alias": "3.0.1", "@rollup/plugin-commonjs": "11.0.2", "@rollup/plugin-json": "4.0.2", "@rollup/plugin-node-resolve": "7.1.1", "@rollup/plugin-replace": "2.3.1", "babel-loader": "8.1.0", benchmark: "2.1.4", "builtin-modules": "3.1.0", codecov: "3.6.5", "cross-env": "7.0.2", cspell: "4.0.55", eslint: "6.8.0", "eslint-config-prettier": "6.10.1", "eslint-formatter-friendly": "7.0.0", "eslint-plugin-import": "2.20.2", "eslint-plugin-prettier": "3.1.2", "eslint-plugin-react": "7.19.0", "eslint-plugin-unicorn": "18.0.1", execa: "4.0.0", jest: "25.2.7", "jest-snapshot-serializer-ansi": "1.0.0", "jest-snapshot-serializer-raw": "1.1.0", "jest-watch-typeahead": "0.5.0", prettier: "2.0.4", rimraf: "3.0.2", rollup: "2.3.2", "rollup-plugin-babel": "4.4.0", "rollup-plugin-node-globals": "1.4.0", "rollup-plugin-terser": "5.3.0", shelljs: "0.8.3", "snapshot-diff": "0.7.0", "strip-ansi": "6.0.0", "synchronous-promise": "2.0.10", tempy: "0.5.0", "terser-webpack-plugin": "2.3.5", webpack: "4.42.1" }; var scripts = { prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1", "prepare-release": "yarn && yarn build && yarn test:dist", test: "jest", "test:dist": "cross-env NODE_ENV=production jest", "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest tests/", "test:integration": "jest tests_integration", "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", "lint:typecheck": "tsc", "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly", "lint:changelog": "node ./scripts/lint-changelog.js", "lint:prettier": "prettier \"**/*.{md,json,yml,html,css}\" --check", "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"", "lint:spellcheck": "cspell {bin,scripts,src,website}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md", "lint:deps": "node ./scripts/check-deps.js", build: "node --max-old-space-size=3072 ./scripts/build/build.js", "build-docs": "node ./scripts/build-docs.js" }; var _package = { name: name, version: version, description: description, bin: bin, repository: repository, homepage: homepage, author: author, license: license, main: main, engines: engines, dependencies: dependencies, devDependencies: devDependencies, scripts: scripts }; var _package$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name, version: version, description: description, bin: bin, repository: repository, homepage: homepage, author: author, license: license, main: main, engines: engines, dependencies: dependencies, devDependencies: devDependencies, scripts: scripts, 'default': _package }); function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0, i.e. the content starts with the same values var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { var basePath = void 0; var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { basePath = clonePath(removePath); self.pushComponent(basePath.components, undefined, true); } else { basePath = addPath; // No need to clone, we've pulled it from the list basePath.newPos++; self.pushComponent(basePath.components, true, undefined); } _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced. if (callback) { (function exec() { setTimeout(function () { // This should not happen, but we want to be safe. /* istanbul ignore next */ if (editLength > maxEditLength) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength) { var ret = execEditLength(); if (ret) { return ret; } } } }, pushComponent: function pushComponent(components, added, removed) { var last = components[components.length - 1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; } else { components.push({ count: 1, added: added, removed: removed }); } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.components.push({ count: commonCount }); } basePath.newPos = newPos; return oldPos; }, equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return value.split(''); }, join: function join(chars) { return chars.join(''); } }; function buildValues(diff, components, newString, oldString, useLongestToken) { var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var lastComponent = components[componentLen - 1]; if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { components[componentLen - 2].value += lastComponent.value; components.pop(); } return components; } function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new Diff(); wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } var lineDiff = new Diff(); lineDiff.tokenize = function (value) { var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value) { var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function parsePatch(uniDiff) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: +chunkHeader[2] || 1, newStart: +chunkHeader[3], newLines: +chunkHeader[4] || 1, lines: [], linedelimiters: [] }; var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator(start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; if (_toPos < 0) { // Creating a new file _toPos = 0; } for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters[j]; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = diffLines(oldStr, newStr, options); diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop(i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds) { // special case: old has no eol and no trailing context; no-nl can end up before adds curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); var ret = []; if (oldFileName == newFileName) { ret.push('Index: ' + oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } var index_es6 = /*#__PURE__*/Object.freeze({ __proto__: null, Diff: Diff, diffChars: diffChars, diffWords: diffWords, diffWordsWithSpace: diffWordsWithSpace, diffLines: diffLines, diffTrimmedLines: diffTrimmedLines, diffSentences: diffSentences, diffCss: diffCss, diffJson: diffJson, diffArrays: diffArrays, structuredPatch: structuredPatch, createTwoFilesPatch: createTwoFilesPatch, createPatch: createPatch, applyPatch: applyPatch, applyPatches: applyPatches, parsePatch: parsePatch, merge: merge, convertChangesToDMP: convertChangesToDMP, convertChangesToXML: convertChangesToXML, canonicalize: canonicalize }); var _shim_fs = {}; var _shim_fs$1 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': _shim_fs }); const sep = /[\\/]/; function extname(path) { const filename = basename(path); const dotIndex = filename.lastIndexOf("."); if (dotIndex === -1) return ""; return filename.slice(dotIndex); } function basename(path) { return path.split(sep).pop(); } function isAbsolute() { return true; } var path = /*#__PURE__*/Object.freeze({ __proto__: null, extname: extname, basename: basename, isAbsolute: isAbsolute }); var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var inited = false; function init() { inited = true; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; } function toByteArray(b64) { if (!inited) { init(); } var i, j, l, tmp, placeHolders, arr; var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len; var L = 0; for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[L++] = tmp >> 16 & 0xFF; arr[L++] = tmp >> 8 & 0xFF; arr[L++] = tmp & 0xFF; } if (placeHolders === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[L++] = tmp & 0xFF; } else if (placeHolders === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[L++] = tmp >> 8 & 0xFF; arr[L++] = tmp & 0xFF; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { if (!inited) { init(); } var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var output = ''; var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; output += lookup[tmp >> 2]; output += lookup[tmp << 4 & 0x3F]; output += '=='; } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; output += lookup[tmp >> 10]; output += lookup[tmp >> 4 & 0x3F]; output += lookup[tmp << 2 & 0x3F]; output += '='; } parts.push(output); return parts.join(''); } function read(buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & (1 << -nBits) - 1; s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); } function write(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; } var toString = {}.toString; var isArray = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; var INSPECT_MAX_BYTES = 50; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength() { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; } function createBuffer(that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length'); } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length); } that.length = length; } return that; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length); } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error('If encoding is specified then the first argument must be a string'); } return allocUnsafe(this, arg); } return from(this, arg, encodingOrOffset, length); } Buffer.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype; return arr; }; function from(that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number'); } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length); } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset); } return fromObject(that, value); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length); }; if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype; Buffer.__proto__ = Uint8Array; } function assertSize(size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number'); } else if (size < 0) { throw new RangeError('"size" argument must not be negative'); } } function alloc(that, size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(that, size); } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); } return createBuffer(that, size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding); }; function allocUnsafe(that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } } return that; } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size); }; function fromString(that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding'); } var length = byteLength(string, encoding) | 0; that = createBuffer(that, length); var actual = that.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual); } return that; } function fromArrayLike(that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; that = createBuffer(that, length); for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255; } return that; } function fromArrayBuffer(that, array, byteOffset, length) { array.byteLength; // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds'); } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array); } else if (length === undefined) { array = new Uint8Array(array, byteOffset); } else { array = new Uint8Array(array, byteOffset, length); } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); } return that; } function fromObject(that, obj) { if (internalIsBuffer(obj)) { var len = checked(obj.length) | 0; that = createBuffer(that, len); if (that.length === 0) { return that; } obj.copy(that, 0, 0, len); return that; } if (obj) { if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0); } return fromArrayLike(that, obj); } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data); } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.'); } function checked(length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes'); } return length | 0; } Buffer.isBuffer = isBuffer; function internalIsBuffer(b) { return !!(b != null && b._isBuffer); } Buffer.compare = function compare(a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers'); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (!internalIsBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } buf.copy(buffer, pos); pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (internalIsBuffer(string)) { return string.length; } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength; } if (typeof string !== 'string') { string = '' + string; } var len = string.length; if (len === 0) return 0; // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) return utf8ToBytes(string).length; // assume utf8 encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits'); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits'); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits'); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length | 0; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.equals = function equals(b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); if (this.length > max) str += ' ... '; } return ''; }; Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer'); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (internalIsBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } // must be an even number of digits var strLen = string.length; if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (isNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function latin1Write(buf, string, offset, length) { return asciiWrite(buf, string, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0; if (isFinite(length)) { length = length | 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': return asciiWrite(this, string, offset, length); case 'latin1': case 'binary': return latin1Write(this, string, offset, length); case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return fromByteArray(buf); } else { return fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf; if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); newBuf.__proto__ = Buffer.prototype; } else { var sliceLen = end - start; newBuf = new Buffer(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } } return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; }; Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | this[offset + 1] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | this[offset] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = value & 0xff; return offset + 1; }; function objectWriteUInt16(buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; } } Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; } else { objectWriteUInt16(this, value, offset, true); } return offset + 2; }; Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 8; this[offset + 1] = value & 0xff; } else { objectWriteUInt16(this, value, offset, false); } return offset + 2; }; function objectWriteUInt32(buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; } } Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; } else { objectWriteUInt32(this, value, offset, true); } return offset + 4; }; Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; } else { objectWriteUInt32(this, value, offset, false); } return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; } else { objectWriteUInt16(this, value, offset, true); } return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 8; this[offset + 1] = value & 0xff; } else { objectWriteUInt16(this, value, offset, false); } return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; } else { objectWriteUInt32(this, value, offset, true); } return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; } else { objectWriteUInt32(this, value, offset, false); } return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4); } write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8); } write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy(target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; var i; if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; } } else { Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); } return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill(val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (val.length === 1) { var code = val.charCodeAt(0); if (code < 256) { val = code; } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } } else if (typeof val === 'number') { val = val & 255; } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; function base64clean(str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str; } function stringtrim(str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } // valid lead leadSurrogate = codePoint; continue; } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue; } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else { throw new Error('Invalid code point'); } } return bytes; } function asciiToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray; } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } function isnan(val) { return val !== val; // eslint-disable-line no-self-compare } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); } function isFastBuffer(obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); } // For Node v0.10 support. Remove this eventually. function isSlowBuffer(obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } var fs = getCjsExportFromNamespace(_shim_fs$1); /** * @class */ class LineByLine { constructor(file, options) { options = options || {}; if (!options.readChunk) options.readChunk = 1024; if (!options.newLineCharacter) { options.newLineCharacter = 0x0a; //linux line ending } else { options.newLineCharacter = options.newLineCharacter.charCodeAt(0); } if (typeof file === 'number') { this.fd = file; } else { this.fd = fs.openSync(file, 'r'); } this.options = options; this.newLineCharacter = options.newLineCharacter; this.reset(); } _searchInBuffer(buffer, hexNeedle) { let found = -1; for (let i = 0; i <= buffer.length; i++) { let b_byte = buffer[i]; if (b_byte === hexNeedle) { found = i; break; } } return found; } reset() { this.eofReached = false; this.linesCache = []; this.fdPosition = 0; } close() { fs.closeSync(this.fd); this.fd = null; } _extractLines(buffer) { let line; const lines = []; let bufferPosition = 0; let lastNewLineBufferPosition = 0; while (true) { let bufferPositionValue = buffer[bufferPosition++]; if (bufferPositionValue === this.newLineCharacter) { line = buffer.slice(lastNewLineBufferPosition, bufferPosition); lines.push(line); lastNewLineBufferPosition = bufferPosition; } else if (!bufferPositionValue) { break; } } let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition); if (leftovers.length) { lines.push(leftovers); } return lines; } _readChunk(lineLeftovers) { let totalBytesRead = 0; let bytesRead; const buffers = []; do { const readBuffer = new Buffer(this.options.readChunk); bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition); totalBytesRead = totalBytesRead + bytesRead; this.fdPosition = this.fdPosition + bytesRead; buffers.push(readBuffer); } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1); let bufferData = Buffer.concat(buffers); if (bytesRead < this.options.readChunk) { this.eofReached = true; bufferData = bufferData.slice(0, totalBytesRead); } if (totalBytesRead) { this.linesCache = this._extractLines(bufferData); if (lineLeftovers) { this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]); } } return totalBytesRead; } next() { if (!this.fd) return false; let line = false; if (this.eofReached && this.linesCache.length === 0) { return line; } let bytesRead; if (!this.linesCache.length) { bytesRead = this._readChunk(); } if (this.linesCache.length) { line = this.linesCache.shift(); const lastLineCharacter = line[line.length - 1]; if (lastLineCharacter !== 0x0a) { bytesRead = this._readChunk(line); if (bytesRead) { line = this.linesCache.shift(); } } } if (this.eofReached && this.linesCache.length === 0) { this.close(); } if (line && line[line.length - 1] === this.newLineCharacter) { line = line.slice(0, line.length - 1); } return line; } } var readlines = LineByLine; /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } var fromPairs_1 = fromPairs; class ConfigError extends Error {} class DebugError extends Error {} class UndefinedParserError extends Error {} var errors = { ConfigError, DebugError, UndefinedParserError }; function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd() { return '/'; } function chdir(dir) { throw new Error('process.chdir is not supported'); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { var clocktime = performanceNow.call(performance) * 1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor(clocktime % 1 * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; var debug_1 = debug; // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0'; const MAX_LENGTH = 256; const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16; var constants = { SEMVER_SPEC_VERSION, MAX_LENGTH, MAX_SAFE_INTEGER, MAX_SAFE_COMPONENT_LENGTH }; var re_1 = createCommonjsModule(function (module, exports) { const { MAX_SAFE_COMPONENT_LENGTH } = constants; exports = module.exports = {}; // The actual regexps go on exports.re const re = exports.re = []; const src = exports.src = []; const t = exports.t = {}; let R = 0; const createToken = (name, value, isGlobal) => { const index = R++; debug_1(index, value); t[name] = index; src[index] = value; re[index] = new RegExp(value, isGlobal ? 'g' : undefined); }; // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")")); createToken('MAINVERSIONLOOSE', "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")")); // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', "(?:".concat(src[t.NUMERICIDENTIFIER], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); createToken('PRERELEASEIDENTIFIERLOOSE', "(?:".concat(src[t.NUMERICIDENTIFIERLOOSE], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', "(?:-(".concat(src[t.PRERELEASEIDENTIFIER], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIER], ")*))")); createToken('PRERELEASELOOSE', "(?:-?(".concat(src[t.PRERELEASEIDENTIFIERLOOSE], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIERLOOSE], ")*))")); // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', "(?:\\+(".concat(src[t.BUILDIDENTIFIER], "(?:\\.").concat(src[t.BUILDIDENTIFIER], ")*))")); // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', "v?".concat(src[t.MAINVERSION]).concat(src[t.PRERELEASE], "?").concat(src[t.BUILD], "?")); createToken('FULL', "^".concat(src[t.FULLPLAIN], "$")); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', "[v=\\s]*".concat(src[t.MAINVERSIONLOOSE]).concat(src[t.PRERELEASELOOSE], "?").concat(src[t.BUILD], "?")); createToken('LOOSE', "^".concat(src[t.LOOSEPLAIN], "$")); createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', "".concat(src[t.NUMERICIDENTIFIERLOOSE], "|x|X|\\*")); createToken('XRANGEIDENTIFIER', "".concat(src[t.NUMERICIDENTIFIER], "|x|X|\\*")); createToken('XRANGEPLAIN', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:".concat(src[t.PRERELEASE], ")?").concat(src[t.BUILD], "?") + ")?)?"); createToken('XRANGEPLAINLOOSE', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:".concat(src[t.PRERELEASELOOSE], ")?").concat(src[t.BUILD], "?") + ")?)?"); createToken('XRANGE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAIN], "$")); createToken('XRANGELOOSE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAINLOOSE], "$")); // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', "".concat('(^|[^\\d])' + '(\\d{1,').concat(MAX_SAFE_COMPONENT_LENGTH, "})") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:$|[^\\d])"); createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)'); createToken('TILDETRIM', "(\\s*)".concat(src[t.LONETILDE], "\\s+"), true); exports.tildeTrimReplace = '$1~'; createToken('TILDE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAIN], "$")); createToken('TILDELOOSE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAINLOOSE], "$")); // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)'); createToken('CARETTRIM', "(\\s*)".concat(src[t.LONECARET], "\\s+"), true); exports.caretTrimReplace = '$1^'; createToken('CARET', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAIN], "$")); createToken('CARETLOOSE', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAINLOOSE], "$")); // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], ")$|^$")); createToken('COMPARATOR', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.FULLPLAIN], ")$|^$")); // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', "(\\s*)".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], "|").concat(src[t.XRANGEPLAIN], ")"), true); exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', "^\\s*(".concat(src[t.XRANGEPLAIN], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAIN], ")") + "\\s*$"); createToken('HYPHENRANGELOOSE', "^\\s*(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s*$"); // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*'); }); var re_2 = re_1.re; var re_3 = re_1.src; var re_4 = re_1.t; var re_5 = re_1.tildeTrimReplace; var re_6 = re_1.caretTrimReplace; var re_7 = re_1.comparatorTrimReplace; const numeric = /^[0-9]+$/; const compareIdentifiers = (a, b) => { const anum = numeric.test(a); const bnum = numeric.test(b); if (anum && bnum) { a = +a; b = +b; } return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; }; const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); var identifiers = { compareIdentifiers, rcompareIdentifiers }; const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1 } = constants; const { re, t } = re_1; const { compareIdentifiers: compareIdentifiers$1 } = identifiers; class SemVer { constructor(version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false }; } if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version; } else { version = version.version; } } else if (typeof version !== 'string') { throw new TypeError("Invalid Version: ".concat(version)); } if (version.length > MAX_LENGTH$1) { throw new TypeError("version is longer than ".concat(MAX_LENGTH$1, " characters")); } debug_1('SemVer', version, options); this.options = options; this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease; const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); if (!m) { throw new TypeError("Invalid Version: ".concat(version)); } this.raw = version; // these are actually numbers this.major = +m[1]; this.minor = +m[2]; this.patch = +m[3]; if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) { throw new TypeError('Invalid major version'); } if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) { throw new TypeError('Invalid minor version'); } if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) { throw new TypeError('Invalid patch version'); } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = []; } else { this.prerelease = m[4].split('.').map(id => { if (/^[0-9]+$/.test(id)) { const num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER$1) { return num; } } return id; }); } this.build = m[5] ? m[5].split('.') : []; this.format(); } format() { this.version = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (this.prerelease.length) { this.version += "-".concat(this.prerelease.join('.')); } return this.version; } toString() { return this.version; } compare(other) { debug_1('SemVer.compare', this.version, this.options, other); if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0; } other = new SemVer(other, this.options); } if (other.version === this.version) { return 0; } return this.compareMain(other) || this.comparePre(other); } compareMain(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch); } comparePre(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1; } else if (!this.prerelease.length && other.prerelease.length) { return 1; } else if (!this.prerelease.length && !other.prerelease.length) { return 0; } let i = 0; do { const a = this.prerelease[i]; const b = other.prerelease[i]; debug_1('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0; } else if (b === undefined) { return 1; } else if (a === undefined) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers$1(a, b); } } while (++i); } compareBuild(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; debug_1('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0; } else if (b === undefined) { return 1; } else if (a === undefined) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers$1(a, b); } } while (++i); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc('pre', identifier); break; case 'preminor': this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc('pre', identifier); break; case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0; this.inc('patch', identifier); this.inc('pre', identifier); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier); } this.inc('pre', identifier); break; case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0]; } else { let i = this.prerelease.length; while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++; i = -2; } } if (i === -1) { // didn't increment anything this.prerelease.push(0); } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0]; } } else { this.prerelease = [identifier, 0]; } } break; default: throw new Error("invalid increment argument: ".concat(release)); } this.format(); this.raw = this.version; return this; } } var semver = SemVer; const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose)); var compare_1 = compare; const lt = (a, b, loose) => compare_1(a, b, loose) < 0; var lt_1 = lt; const gte = (a, b, loose) => compare_1(a, b, loose) >= 0; var gte_1 = gte; var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({ [keyName]: key }, value)); var dedent_1 = createCommonjsModule(function (module) { function dedent(strings) { var raw = void 0; if (typeof strings === "string") { // dedent can be used as a plain function raw = [strings]; } else { raw = strings.raw; } // first, perform interpolation var result = ""; for (var i = 0; i < raw.length; i++) { result += raw[i]. // join lines when there is a suppressed newline replace(/\\\n[ \t]*/g, ""). // handle escaped backticks replace(/\\`/g, "`"); if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; } } // now strip indentation var lines = result.split("\n"); var mindent = null; lines.forEach(function (l) { var m = l.match(/^(\s+)\S+/); if (m) { var indent = m[1].length; if (!mindent) { // this is the first indented line mindent = indent; } else { mindent = Math.min(mindent, indent); } } }); if (mindent !== null) { result = lines.map(function (l) { return l[0] === " " ? l.slice(mindent) : l; }).join("\n"); } // dedent eats leading and trailing whitespace too result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too return result.replace(/\\n/g, "\n"); } { module.exports = dedent; } }); function _templateObject6() { const data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]); _templateObject6 = function _templateObject6() { return data; }; return data; } function _templateObject5() { const data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]); _templateObject5 = function _templateObject5() { return data; }; return data; } function _templateObject4() { const data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]); _templateObject4 = function _templateObject4() { return data; }; return data; } function _templateObject3() { const data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]); _templateObject3 = function _templateObject3() { return data; }; return data; } function _templateObject2() { const data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]); _templateObject2 = function _templateObject2() { return data; }; return data; } function _templateObject() { const data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]); _templateObject = function _templateObject() { return data; }; return data; } const CATEGORY_CONFIG = "Config"; const CATEGORY_EDITOR = "Editor"; const CATEGORY_FORMAT = "Format"; const CATEGORY_OTHER = "Other"; const CATEGORY_OUTPUT = "Output"; const CATEGORY_GLOBAL = "Global"; const CATEGORY_SPECIAL = "Special"; /** * @typedef {Object} OptionInfo * @property {string} [since] - available since version * @property {string} category * @property {'int' | 'boolean' | 'choice' | 'path'} type * @property {boolean} [array] - indicate it's an array of the specified type * @property {OptionValueInfo} [default] * @property {OptionRangeInfo} [range] - for type int * @property {string} description * @property {string} [deprecated] - deprecated since version * @property {OptionRedirectInfo} [redirect] - redirect deprecated option * @property {(value: any) => boolean} [exception] * @property {OptionChoiceInfo[]} [choices] - for type choice * @property {string} [cliName] * @property {string} [cliCategory] * @property {string} [cliDescription] * * @typedef {number | boolean | string} OptionValue * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo * * @typedef {Object} OptionRedirectInfo * @property {string} option * @property {OptionValue} value * * @typedef {Object} OptionRangeInfo * @property {number} start - recommended range start * @property {number} end - recommended range end * @property {number} step - recommended range step * * @typedef {Object} OptionChoiceInfo * @property {boolean | string} value - boolean for the option that is originally boolean type * @property {string} description * @property {string} [since] - undefined if available since the first version of the option * @property {string} [deprecated] - deprecated since version * @property {OptionValueInfo} [redirect] - redirect deprecated value */ /** @type {{ [name: string]: OptionInfo }} */ const options = { cursorOffset: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "int", default: -1, range: { start: -1, end: Infinity, step: 1 }, description: dedent_1(_templateObject()), cliCategory: CATEGORY_EDITOR }, endOfLine: { since: "1.15.0", category: CATEGORY_GLOBAL, type: "choice", default: [{ since: "1.15.0", value: "auto" }, { since: "2.0.0", value: "lf" }], description: "Which end of line characters to apply.", choices: [{ value: "lf", description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" }, { value: "crlf", description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows" }, { value: "cr", description: "Carriage Return character only (\\r), used very rarely" }, { value: "auto", description: dedent_1(_templateObject2()) }] }, filepath: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "path", description: "Specify the input filepath. This will be used to do parser inference.", cliName: "stdin-filepath", cliCategory: CATEGORY_OTHER, cliDescription: "Path to the file to pretend that stdin comes from." }, insertPragma: { since: "1.8.0", category: CATEGORY_SPECIAL, type: "boolean", default: false, description: "Insert @format pragma into file's first docblock comment.", cliCategory: CATEGORY_OTHER }, parser: { since: "0.0.10", category: CATEGORY_GLOBAL, type: "choice", default: [{ since: "0.0.10", value: "babylon" }, { since: "1.13.0", value: undefined }], description: "Which parser to use.", exception: value => typeof value === "string" || typeof value === "function", choices: [{ value: "flow", description: "Flow" }, { value: "babel", since: "1.16.0", description: "JavaScript" }, { value: "babel-flow", since: "1.16.0", description: "Flow" }, { value: "babel-ts", since: "2.0.0", description: "TypeScript" }, { value: "typescript", since: "1.4.0", description: "TypeScript" }, { value: "css", since: "1.7.1", description: "CSS" }, { value: "less", since: "1.7.1", description: "Less" }, { value: "scss", since: "1.7.1", description: "SCSS" }, { value: "json", since: "1.5.0", description: "JSON" }, { value: "json5", since: "1.13.0", description: "JSON5" }, { value: "json-stringify", since: "1.13.0", description: "JSON.stringify" }, { value: "graphql", since: "1.5.0", description: "GraphQL" }, { value: "markdown", since: "1.8.0", description: "Markdown" }, { value: "mdx", since: "1.15.0", description: "MDX" }, { value: "vue", since: "1.10.0", description: "Vue" }, { value: "yaml", since: "1.14.0", description: "YAML" }, { value: "glimmer", since: null, description: "Handlebars" }, { value: "html", since: "1.15.0", description: "HTML" }, { value: "angular", since: "1.15.0", description: "Angular" }, { value: "lwc", since: "1.17.0", description: "Lightning Web Components" }] }, plugins: { since: "1.10.0", type: "path", array: true, default: [{ value: [] }], category: CATEGORY_GLOBAL, description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", exception: value => typeof value === "string" || typeof value === "object", cliName: "plugin", cliCategory: CATEGORY_CONFIG }, pluginSearchDirs: { since: "1.13.0", type: "path", array: true, default: [{ value: [] }], category: CATEGORY_GLOBAL, description: dedent_1(_templateObject3()), exception: value => typeof value === "string" || typeof value === "object", cliName: "plugin-search-dir", cliCategory: CATEGORY_CONFIG }, printWidth: { since: "0.0.0", category: CATEGORY_GLOBAL, type: "int", default: 80, description: "The line length where Prettier will try wrap.", range: { start: 0, end: Infinity, step: 1 } }, rangeEnd: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "int", default: Infinity, range: { start: 0, end: Infinity, step: 1 }, description: dedent_1(_templateObject4()), cliCategory: CATEGORY_EDITOR }, rangeStart: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "int", default: 0, range: { start: 0, end: Infinity, step: 1 }, description: dedent_1(_templateObject5()), cliCategory: CATEGORY_EDITOR }, requirePragma: { since: "1.7.0", category: CATEGORY_SPECIAL, type: "boolean", default: false, description: dedent_1(_templateObject6()), cliCategory: CATEGORY_OTHER }, tabWidth: { type: "int", category: CATEGORY_GLOBAL, default: 2, description: "Number of spaces per indentation level.", range: { start: 0, end: Infinity, step: 1 } }, useTabs: { since: "1.0.0", category: CATEGORY_GLOBAL, type: "boolean", default: false, description: "Indent with tabs instead of spaces." } }; var coreOptions = { CATEGORY_CONFIG, CATEGORY_EDITOR, CATEGORY_FORMAT, CATEGORY_OTHER, CATEGORY_OUTPUT, CATEGORY_GLOBAL, CATEGORY_SPECIAL, options }; var require$$0 = getCjsExportFromNamespace(_package$1); const semver$1 = { compare: compare_1, lt: lt_1, gte: gte_1 }; const currentVersion = require$$0.version; const coreOptions$1 = coreOptions.options; /** * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version * of this function created by `withPlugins`. Don't pass them here directly. * @param {object} param0 * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`. * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`. * @param {boolean=} param0.showUnreleased * @param {boolean=} param0.showDeprecated * @param {boolean=} param0.showInternal */ function getSupportInfo({ plugins = [], showUnreleased = false, showDeprecated = false, showInternal = false } = {}) { // pre-release version is smaller than the normal version in semver, // we need to treat it as the normal one so as to test new features. const version = currentVersion.split("-", 1)[0]; const options = arrayify(Object.assign({}, ...plugins.map(({ options }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => { option = Object.assign({}, option); if (Array.isArray(option.default)) { option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value; } if (Array.isArray(option.choices)) { option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option)); } const filteredPlugins = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined); const pluginDefaults = filteredPlugins.reduce((reduced, plugin) => { reduced[plugin.name] = plugin.defaultOptions[option.name]; return reduced; }, {}); return Object.assign({}, option, { pluginDefaults }); }); const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince); return { languages, options }; function filterSince(object) { return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since); } function filterDeprecated(object) { return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated); } function mapInternal(object) { if (showInternal) { return object; } const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]); return newObject; } } var support = { getSupportInfo }; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var _extendStatics = function extendStatics(d, b) { _extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return _extendStatics(d, b); }; function __extends(d, b) { _extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var _assign = function __assign() { _assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return _assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function sent() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function next() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } var tslib_es6 = /*#__PURE__*/Object.freeze({ __proto__: null, __extends: __extends, get __assign () { return _assign; }, __rest: __rest, __decorate: __decorate, __param: __param, __metadata: __metadata, __awaiter: __awaiter, __generator: __generator, __exportStar: __exportStar, __values: __values, __read: __read, __spread: __spread, __spreadArrays: __spreadArrays, __await: __await, __asyncGenerator: __asyncGenerator, __asyncDelegator: __asyncDelegator, __asyncValues: __asyncValues, __makeTemplateObject: __makeTemplateObject, __importStar: __importStar, __importDefault: __importDefault }); var api = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.apiDescriptor = { key: _key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key), value(value) { if (value === null || typeof value !== 'object') { return JSON.stringify(value); } if (Array.isArray(value)) { return "[".concat(value.map(subValue => exports.apiDescriptor.value(subValue)).join(', '), "]"); } const keys = Object.keys(value); return keys.length === 0 ? '{}' : "{ ".concat(keys.map(key => "".concat(exports.apiDescriptor.key(key), ": ").concat(exports.apiDescriptor.value(value[key]))).join(', '), " }"); }, pair: ({ key, value }) => exports.apiDescriptor.value({ [key]: value }) }; }); unwrapExports(api); var api_1 = api.apiDescriptor; var tslib_1 = getCjsExportFromNamespace(tslib_es6); var descriptors = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(api, exports); }); unwrapExports(descriptors); var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function escapeStringRegexp(str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; var colorName = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName) { if (colorName.hasOwnProperty(key)) { reverseKeywords[colorName[key]] = key; } } var convert = module.exports = { rgb: { channels: 3, labels: 'rgb' }, hsl: { channels: 3, labels: 'hsl' }, hsv: { channels: 3, labels: 'hsv' }, hwb: { channels: 3, labels: 'hwb' }, cmyk: { channels: 4, labels: 'cmyk' }, xyz: { channels: 3, labels: 'xyz' }, lab: { channels: 3, labels: 'lab' }, lch: { channels: 3, labels: 'lch' }, hex: { channels: 1, labels: ['hex'] }, keyword: { channels: 1, labels: ['keyword'] }, ansi16: { channels: 1, labels: ['ansi16'] }, ansi256: { channels: 1, labels: ['ansi256'] }, hcg: { channels: 3, labels: ['h', 'c', 'g'] }, apple: { channels: 3, labels: ['r16', 'g16', 'b16'] }, gray: { channels: 1, labels: ['gray'] } }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', { value: channels }); Object.defineProperty(convert[model], 'labels', { value: labels }); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function diffc(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = 1 / 3 + rdif - bdif; } else if (b === v) { h = 2 / 3 + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [h * 360, s * 100, v * 100]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName) { if (colorName.hasOwnProperty(keyword)) { var value = colorName[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; var x = r * 0.4124 + g * 0.3576 + b * 0.1805; var y = r * 0.2126 + g * 0.7152 + b * 0.0722; var z = r * 0.0193 + g * 0.1192 + b * 0.9505; return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= l <= 1 ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - s * f); var t = 255 * v * (1 - s * (1 - f)); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= lmin <= 1 ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = x * 3.2406 + y * -1.5372 + z * -0.4986; g = x * -0.9689 + y * 1.8758 + z * 0.0415; b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round((r - 8) / 247 * 24) + 232; } var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = (color & 1) * mult * 255; var g = (color >> 1 & 1) * mult * 255; var b = (color >> 2 & 1) * mult * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = rem % 6 / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = integer >> 16 & 0xFF; var g = integer >> 8 & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = max - min; var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = (g - b) / chroma % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = h % 1 * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; }; convert.rgb.apple = function (rgb) { return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; }); var conversions_1 = conversions.rgb; var conversions_2 = conversions.hsl; var conversions_3 = conversions.hsv; var conversions_4 = conversions.hwb; var conversions_5 = conversions.cmyk; var conversions_6 = conversions.xyz; var conversions_7 = conversions.lab; var conversions_8 = conversions.lch; var conversions_9 = conversions.hex; var conversions_10 = conversions.keyword; var conversions_11 = conversions.ansi16; var conversions_12 = conversions.ansi256; var conversions_13 = conversions.hcg; var conversions_14 = conversions.apple; var conversions_15 = conversions.gray; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { var graph = buildGraph(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route = function route(fromModel) { var graph = deriveBFS(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', { value: conversions[fromModel].channels }); Object.defineProperty(convert[fromModel], 'labels', { value: conversions[fromModel].labels }); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); var colorConvert = convert; var ansiStyles = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return "\x1B[".concat(code + offset, "m"); }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert, arguments); return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], // Bright color redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: "\x1B[".concat(style[0], "m"), close: "\x1B[".concat(style[1], "m") }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert)) { if (typeof colorConvert[key] !== 'object') { continue; } const suite = colorConvert[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); var require$$0$1 = { EOL: "\n" }; var hasFlag = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; const env$1 = process.env; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = true; } if ('FORCE_COLOR' in env$1) { forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } const min = forceColor ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = require$$0$1.release().split('.'); if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$1) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$1) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; } if (env$1.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$1) { const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$1.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$1.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { return 1; } if ('COLORTERM' in env$1) { return 1; } if (env$1.TERM === 'dumb') { return min; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream); return translateLevel(level); } var supportsColor_1 = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); function unescape(c) { if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if (matches = chunk.match(STRING_REGEX)) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); } else { throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error("Unknown Chalk style: ".concat(styleName)); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } var templates = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); styles.push({ inverse, styles: parseStyle(style) }); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); throw new Error(errMsg); } return chunks.join(''); }; var chalk = createCommonjsModule(function (module) { const stdoutColor = supportsColor_1.stdout; const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles)) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); for (const model of Object.keys(ansiStyles.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.color.close, closeRe: ansiStyles.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.bgColor.close, closeRe: ansiStyles.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function builder() { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return templates(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }); var chalk_1 = chalk.supportsColor; var common = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.commonDeprecatedHandler = (keyOrPair, redirectTo, { descriptor }) => { const messages = ["".concat(chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair)), " is deprecated")]; if (redirectTo) { messages.push("we now treat it as ".concat(chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo)))); } return messages.join('; ') + '.'; }; }); unwrapExports(common); var common_1 = common.commonDeprecatedHandler; var deprecated = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(common, exports); }); unwrapExports(deprecated); var common$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.commonInvalidHandler = (key, value, utils) => ["Invalid ".concat(chalk.default.red(utils.descriptor.key(key)), " value."), "Expected ".concat(chalk.default.blue(utils.schemas[key].expected(utils)), ","), "but received ".concat(chalk.default.red(utils.descriptor.value(value)), ".")].join(' '); }); unwrapExports(common$1); var common_1$1 = common$1.commonInvalidHandler; var invalid = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(common$1, exports); }); unwrapExports(invalid); /* eslint-disable no-nested-ternary */ var arr = []; var charCodeCache = []; var leven = function leven(a, b) { if (a === b) { return 0; } var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (a.length > b.length) { a = b; b = swap; } var aLen = a.length; var bLen = b.length; if (aLen === 0) { return bLen; } if (bLen === 0) { return aLen; } // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) { aLen--; bLen--; } if (aLen === 0) { return bLen; } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all var start = 0; while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) { start++; } aLen -= start; bLen -= start; if (aLen === 0) { return bLen; } var bCharCode; var ret; var tmp; var tmp2; var i = 0; var j = 0; while (i < aLen) { charCodeCache[start + i] = a.charCodeAt(start + i); arr[i] = ++i; } while (j < bLen) { bCharCode = b.charCodeAt(start + j); tmp = j++; ret = j; for (i = 0; i < aLen; i++) { tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; tmp = arr[i]; ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; } } return ret; }; var leven_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.levenUnknownHandler = (key, value, { descriptor, logger, schemas }) => { const messages = ["Ignored unknown option ".concat(chalk.default.yellow(descriptor.pair({ key, value })), ".")]; const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3); if (suggestion) { messages.push("Did you mean ".concat(chalk.default.blue(descriptor.key(suggestion)), "?")); } logger.warn(messages.join(' ')); }; }); unwrapExports(leven_1); var leven_2 = leven_1.levenUnknownHandler; var unknown = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(leven_1, exports); }); unwrapExports(unknown); var handlers = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(deprecated, exports); tslib_1.__exportStar(invalid, exports); tslib_1.__exportStar(unknown, exports); }); unwrapExports(handlers); var schema = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess']; function createSchema(SchemaConstructor, parameters) { const schema = new SchemaConstructor(parameters); const subSchema = Object.create(schema); for (const handlerKey of HANDLER_KEYS) { if (handlerKey in parameters) { subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length); } } return subSchema; } exports.createSchema = createSchema; class Schema { constructor(parameters) { this.name = parameters.name; } static create(parameters) { // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863 return createSchema(this, parameters); } default(_utils) { return undefined; } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` expected(_utils) { return 'nothing'; } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` validate(_value, _utils) { return false; } deprecated(_value, _utils) { return false; } forward(_value, _utils) { return undefined; } redirect(_value, _utils) { return undefined; } overlap(currentValue, _newValue, _utils) { return currentValue; } preprocess(value, _utils) { return value; } postprocess(value, _utils) { return value; } } exports.Schema = Schema; function normalizeHandler(handler, superSchema, handlerArgumentsLength) { return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler; } }); unwrapExports(schema); var schema_1 = schema.createSchema; var schema_2 = schema.Schema; var alias = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class AliasSchema extends schema.Schema { constructor(parameters) { super(parameters); this._sourceName = parameters.sourceName; } expected(utils) { return utils.schemas[this._sourceName].expected(utils); } validate(value, utils) { return utils.schemas[this._sourceName].validate(value, utils); } redirect(_value, _utils) { return this._sourceName; } } exports.AliasSchema = AliasSchema; }); unwrapExports(alias); var alias_1 = alias.AliasSchema; var any = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class AnySchema extends schema.Schema { expected() { return 'anything'; } validate() { return true; } } exports.AnySchema = AnySchema; }); unwrapExports(any); var any_1 = any.AnySchema; var array = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class ArraySchema extends schema.Schema { constructor(_a) { var { valueSchema, name = valueSchema.name } = _a, handlers = tslib_1.__rest(_a, ["valueSchema", "name"]); super(Object.assign({}, handlers, { name })); this._valueSchema = valueSchema; } expected(utils) { return "an array of ".concat(this._valueSchema.expected(utils)); } validate(value, utils) { if (!Array.isArray(value)) { return false; } const invalidValues = []; for (const subValue of value) { const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue); if (subValidateResult !== true) { invalidValues.push(subValidateResult.value); } } return invalidValues.length === 0 ? true : { value: invalidValues }; } deprecated(value, utils) { const deprecatedResult = []; for (const subValue of value) { const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue); if (subDeprecatedResult !== false) { deprecatedResult.push(...subDeprecatedResult.map(({ value: deprecatedValue }) => ({ value: [deprecatedValue] }))); } } return deprecatedResult; } forward(value, utils) { const forwardResult = []; for (const subValue of value) { const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue); forwardResult.push(...subForwardResult.map(wrapTransferResult)); } return forwardResult; } redirect(value, utils) { const remain = []; const redirect = []; for (const subValue of value) { const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue); if ('remain' in subRedirectResult) { remain.push(subRedirectResult.remain); } redirect.push(...subRedirectResult.redirect.map(wrapTransferResult)); } return remain.length === 0 ? { redirect } : { redirect, remain }; } overlap(currentValue, newValue) { return currentValue.concat(newValue); } } exports.ArraySchema = ArraySchema; function wrapTransferResult({ from, to }) { return { from: [from], to }; } }); unwrapExports(array); var array_1 = array.ArraySchema; var boolean_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class BooleanSchema extends schema.Schema { expected() { return 'true or false'; } validate(value) { return typeof value === 'boolean'; } } exports.BooleanSchema = BooleanSchema; }); unwrapExports(boolean_1); var boolean_2 = boolean_1.BooleanSchema; var utils = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); function recordFromArray(array, mainKey) { const record = Object.create(null); for (const value of array) { const key = value[mainKey]; // istanbul ignore next if (record[key]) { throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); } // @ts-ignore record[key] = value; } return record; } exports.recordFromArray = recordFromArray; function mapFromArray(array, mainKey) { const map = new Map(); for (const value of array) { const key = value[mainKey]; // istanbul ignore next if (map.has(key)) { throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); } map.set(key, value); } return map; } exports.mapFromArray = mapFromArray; function createAutoChecklist() { const map = Object.create(null); return id => { const idString = JSON.stringify(id); if (map[idString]) { return true; } map[idString] = true; return false; }; } exports.createAutoChecklist = createAutoChecklist; function partition(array, predicate) { const trueArray = []; const falseArray = []; for (const value of array) { if (predicate(value)) { trueArray.push(value); } else { falseArray.push(value); } } return [trueArray, falseArray]; } exports.partition = partition; function isInt(value) { return value === Math.floor(value); } exports.isInt = isInt; function comparePrimitive(a, b) { if (a === b) { return 0; } const typeofA = typeof a; const typeofB = typeof b; const orders = ['undefined', 'object', 'boolean', 'number', 'string']; if (typeofA !== typeofB) { return orders.indexOf(typeofA) - orders.indexOf(typeofB); } if (typeofA !== 'string') { return Number(a) - Number(b); } return a.localeCompare(b); } exports.comparePrimitive = comparePrimitive; function normalizeDefaultResult(result) { return result === undefined ? {} : result; } exports.normalizeDefaultResult = normalizeDefaultResult; function normalizeValidateResult(result, value) { return result === true ? true : result === false ? { value } : result; } exports.normalizeValidateResult = normalizeValidateResult; function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) { return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{ value }] : 'value' in result ? [result] : result.length === 0 ? false : result; } exports.normalizeDeprecatedResult = normalizeDeprecatedResult; function normalizeTransferResult(result, value) { return typeof result === 'string' || 'key' in result ? { from: value, to: result } : 'from' in result ? { from: result.from, to: result.to } : { from: value, to: result.to }; } exports.normalizeTransferResult = normalizeTransferResult; function normalizeForwardResult(result, value) { return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)]; } exports.normalizeForwardResult = normalizeForwardResult; function normalizeRedirectResult(result, value) { const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value); return redirect.length === 0 ? { remain: value, redirect } : typeof result === 'object' && 'remain' in result ? { remain: result.remain, redirect } : { redirect }; } exports.normalizeRedirectResult = normalizeRedirectResult; }); unwrapExports(utils); var utils_1 = utils.recordFromArray; var utils_2 = utils.mapFromArray; var utils_3 = utils.createAutoChecklist; var utils_4 = utils.partition; var utils_5 = utils.isInt; var utils_6 = utils.comparePrimitive; var utils_7 = utils.normalizeDefaultResult; var utils_8 = utils.normalizeValidateResult; var utils_9 = utils.normalizeDeprecatedResult; var utils_10 = utils.normalizeTransferResult; var utils_11 = utils.normalizeForwardResult; var utils_12 = utils.normalizeRedirectResult; var choice = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class ChoiceSchema extends schema.Schema { constructor(parameters) { super(parameters); this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : { value: choice }), 'value'); } expected({ descriptor }) { const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value); const head = choiceValues.slice(0, -2); const tail = choiceValues.slice(-2); return head.concat(tail.join(' or ')).join(', '); } validate(value) { return this._choices.has(value); } deprecated(value) { const choiceInfo = this._choices.get(value); return choiceInfo && choiceInfo.deprecated ? { value } : false; } forward(value) { const choiceInfo = this._choices.get(value); return choiceInfo ? choiceInfo.forward : undefined; } redirect(value) { const choiceInfo = this._choices.get(value); return choiceInfo ? choiceInfo.redirect : undefined; } } exports.ChoiceSchema = ChoiceSchema; }); unwrapExports(choice); var choice_1 = choice.ChoiceSchema; var number = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class NumberSchema extends schema.Schema { expected() { return 'a number'; } validate(value, _utils) { return typeof value === 'number'; } } exports.NumberSchema = NumberSchema; }); unwrapExports(number); var number_1 = number.NumberSchema; var integer = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class IntegerSchema extends number.NumberSchema { expected() { return 'an integer'; } validate(value, utils$1) { return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value); } } exports.IntegerSchema = IntegerSchema; }); unwrapExports(integer); var integer_1 = integer.IntegerSchema; var string = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class StringSchema extends schema.Schema { expected() { return 'a string'; } validate(value) { return typeof value === 'string'; } } exports.StringSchema = StringSchema; }); unwrapExports(string); var string_1 = string.StringSchema; var schemas = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(alias, exports); tslib_1.__exportStar(any, exports); tslib_1.__exportStar(array, exports); tslib_1.__exportStar(boolean_1, exports); tslib_1.__exportStar(choice, exports); tslib_1.__exportStar(integer, exports); tslib_1.__exportStar(number, exports); tslib_1.__exportStar(string, exports); }); unwrapExports(schemas); var defaults = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultDescriptor = api.apiDescriptor; exports.defaultUnknownHandler = leven_1.levenUnknownHandler; exports.defaultInvalidHandler = invalid.commonInvalidHandler; exports.defaultDeprecatedHandler = common.commonDeprecatedHandler; }); unwrapExports(defaults); var defaults_1 = defaults.defaultDescriptor; var defaults_2 = defaults.defaultUnknownHandler; var defaults_3 = defaults.defaultInvalidHandler; var defaults_4 = defaults.defaultDeprecatedHandler; var normalize = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options); class Normalizer { constructor(schemas, opts) { // istanbul ignore next const { logger = console, descriptor = defaults.defaultDescriptor, unknown = defaults.defaultUnknownHandler, invalid = defaults.defaultInvalidHandler, deprecated = defaults.defaultDeprecatedHandler } = opts || {}; this._utils = { descriptor, logger: /* istanbul ignore next */ logger || { warn: () => {} }, schemas: utils.recordFromArray(schemas, 'name'), normalizeDefaultResult: utils.normalizeDefaultResult, normalizeDeprecatedResult: utils.normalizeDeprecatedResult, normalizeForwardResult: utils.normalizeForwardResult, normalizeRedirectResult: utils.normalizeRedirectResult, normalizeValidateResult: utils.normalizeValidateResult }; this._unknownHandler = unknown; this._invalidHandler = invalid; this._deprecatedHandler = deprecated; this.cleanHistory(); } cleanHistory() { this._hasDeprecationWarned = utils.createAutoChecklist(); } normalize(options) { const normalized = {}; const restOptionsArray = [options]; const applyNormalization = () => { while (restOptionsArray.length !== 0) { const currentOptions = restOptionsArray.shift(); const transferredOptionsArray = this._applyNormalization(currentOptions, normalized); restOptionsArray.push(...transferredOptionsArray); } }; applyNormalization(); for (const key of Object.keys(this._utils.schemas)) { const schema = this._utils.schemas[key]; if (!(key in normalized)) { const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils)); if ('value' in defaultResult) { restOptionsArray.push({ [key]: defaultResult.value }); } } } applyNormalization(); for (const key of Object.keys(this._utils.schemas)) { const schema = this._utils.schemas[key]; if (key in normalized) { normalized[key] = schema.postprocess(normalized[key], this._utils); } } return normalized; } _applyNormalization(options, normalized) { const transferredOptionsArray = []; const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas); for (const key of knownOptionNames) { const schema = this._utils.schemas[key]; const value = schema.preprocess(options[key], this._utils); const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value); if (validateResult !== true) { const { value: invalidValue } = validateResult; const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils); throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) : /* istanbul ignore next*/ errorMessageOrError; } const appendTransferredOptions = ({ from, to }) => { transferredOptionsArray.push(typeof to === 'string' ? { [to]: from } : { [to.key]: to.value }); }; const warnDeprecated = ({ value: currentValue, redirectTo }) => { const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value, /* doNotNormalizeTrue */ true); if (deprecatedResult === false) { return; } if (deprecatedResult === true) { if (!this._hasDeprecationWarned(key)) { this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils)); } } else { for (const { value: deprecatedValue } of deprecatedResult) { const pair = { key, value: deprecatedValue }; if (!this._hasDeprecationWarned(pair)) { const redirectToPair = typeof redirectTo === 'string' ? { key: redirectTo, value: deprecatedValue } : redirectTo; this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils)); } } } }; const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value); forwardResult.forEach(appendTransferredOptions); const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value); redirectResult.redirect.forEach(appendTransferredOptions); if ('remain' in redirectResult) { const remainingValue = redirectResult.remain; normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue; warnDeprecated({ value: remainingValue }); } for (const { from, to } of redirectResult.redirect) { warnDeprecated({ value: from, redirectTo: to }); } } for (const key of unknownOptionNames) { const value = options[key]; const unknownResult = this._unknownHandler(key, value, this._utils); if (unknownResult) { for (const unknownKey of Object.keys(unknownResult)) { const unknownOption = { [unknownKey]: unknownResult[unknownKey] }; if (unknownKey in this._utils.schemas) { transferredOptionsArray.push(unknownOption); } else { Object.assign(normalized, unknownOption); } } } } return transferredOptionsArray; } } exports.Normalizer = Normalizer; }); unwrapExports(normalize); var normalize_1 = normalize.normalize; var normalize_2 = normalize.Normalizer; var lib = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(descriptors, exports); tslib_1.__exportStar(handlers, exports); tslib_1.__exportStar(schemas, exports); tslib_1.__exportStar(normalize, exports); tslib_1.__exportStar(schema, exports); }); unwrapExports(lib); const array$1 = []; const charCodeCache$1 = []; const leven$1 = (left, right) => { if (left === right) { return 0; } const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (left.length > right.length) { left = right; right = swap; } let leftLength = left.length; let rightLength = right.length; // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) { leftLength--; rightLength--; } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all let start = 0; while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) { start++; } leftLength -= start; rightLength -= start; if (leftLength === 0) { return rightLength; } let bCharCode; let result; let temp; let temp2; let i = 0; let j = 0; while (i < leftLength) { charCodeCache$1[i] = left.charCodeAt(start + i); array$1[i] = ++i; } while (j < rightLength) { bCharCode = right.charCodeAt(start + j); temp = j++; result = j; for (i = 0; i < leftLength; i++) { temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1; temp = array$1[i]; // eslint-disable-next-line no-multi-assign result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2; } } return result; }; var leven_1$1 = leven$1; // TODO: Remove this for the next major release var default_1 = leven$1; leven_1$1.default = default_1; var colorName$1 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /* MIT license */ /* eslint-disable no-mixed-operators */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(colorName$1)) { reverseKeywords[colorName$1[key]] = key; } const convert$1 = { rgb: { channels: 3, labels: 'rgb' }, hsl: { channels: 3, labels: 'hsl' }, hsv: { channels: 3, labels: 'hsv' }, hwb: { channels: 3, labels: 'hwb' }, cmyk: { channels: 4, labels: 'cmyk' }, xyz: { channels: 3, labels: 'xyz' }, lab: { channels: 3, labels: 'lab' }, lch: { channels: 3, labels: 'lch' }, hex: { channels: 1, labels: ['hex'] }, keyword: { channels: 1, labels: ['keyword'] }, ansi16: { channels: 1, labels: ['ansi16'] }, ansi256: { channels: 1, labels: ['ansi256'] }, hcg: { channels: 3, labels: ['h', 'c', 'g'] }, apple: { channels: 3, labels: ['r16', 'g16', 'b16'] }, gray: { channels: 1, labels: ['gray'] } }; var conversions$1 = convert$1; // Hide .channels and .labels properties for (const model of Object.keys(convert$1)) { if (!('channels' in convert$1[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert$1[model])) { throw new Error('missing channel labels property: ' + model); } if (convert$1[model].labels.length !== convert$1[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const { channels, labels } = convert$1[model]; delete convert$1[model].channels; delete convert$1[model].labels; Object.defineProperty(convert$1[model], 'channels', { value: channels }); Object.defineProperty(convert$1[model], 'labels', { value: labels }); } convert$1.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert$1.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function diffc(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = 1 / 3 + rdif - bdif; } else if (b === v) { h = 2 / 3 + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [h * 360, s * 100, v * 100]; }; convert$1.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert$1.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert$1.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; } convert$1.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(colorName$1)) { const value = colorName$1[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert$1.keyword.rgb = function (keyword) { return colorName$1[keyword]; }; convert$1.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92; g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92; b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92; const x = r * 0.4124 + g * 0.3576 + b * 0.1805; const y = r * 0.2126 + g * 0.7152 + b * 0.0722; const z = r * 0.0193 + g * 0.1192 + b * 0.9505; return [x * 100, y * 100, z * 100]; }; convert$1.rgb.lab = function (rgb) { const xyz = convert$1.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116; const l = 116 * y - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$1.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert$1.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= l <= 1 ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); return [h, sv * 100, v * 100]; }; convert$1.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - s * f); const t = 255 * v * (1 - s * (1 - f)); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert$1.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= lmin <= 1 ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert$1.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert$1.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = x * 3.2406 + y * -1.5372 + z * -0.4986; g = x * -0.9689 + y * 1.8758 + z * 0.0415; b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92; g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92; b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116; const l = 116 * y - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$1.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert$1.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert$1.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert$1.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert$1.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); }; convert$1.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round((r - 8) / 247 * 24) + 232; } const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); return ansi; }; convert$1.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = (color & 1) * mult * 255; const g = (color >> 1 & 1) * mult * 255; const b = (color >> 2 & 1) * mult * 255; return [r, g, b]; }; convert$1.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = rem % 6 / 5 * 255; return [r, g, b]; }; convert$1.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = integer >> 16 & 0xFF; const g = integer >> 8 & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert$1.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = max - min; let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = (g - b) / chroma % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert$1.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert$1.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert$1.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = h % 1 * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; }; convert$1.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert$1.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert$1.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert$1.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert$1.apple.rgb = function (apple) { return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; }; convert$1.rgb.apple = function (rgb) { return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; }; convert$1.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert$1.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert$1.gray.hsv = convert$1.gray.hsl; convert$1.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert$1.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert$1.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert$1.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph$1() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions$1); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS$1(fromModel) { const graph = buildGraph$1(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions$1[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link$1(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion$1(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions$1[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link$1(conversions$1[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$1 = function route(fromModel) { const graph = deriveBFS$1(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion$1(toModel, graph); } return conversion; }; const convert$2 = {}; const models$1 = Object.keys(conversions$1); function wrapRaw$1(fn) { const wrappedFn = function wrappedFn(...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded$1(fn) { const wrappedFn = function wrappedFn(...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models$1.forEach(fromModel => { convert$2[fromModel] = {}; Object.defineProperty(convert$2[fromModel], 'channels', { value: conversions$1[fromModel].channels }); Object.defineProperty(convert$2[fromModel], 'labels', { value: conversions$1[fromModel].labels }); const routes = route$1(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert$2[fromModel][toModel] = wrapRounded$1(fn); convert$2[fromModel][toModel].raw = wrapRaw$1(fn); }); }); var colorConvert$1 = convert$2; var ansiStyles$1 = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return "\x1B[".concat(code + offset, "m"); }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); }; const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; const setLazyProperty = (object, property, _get) => { Object.defineProperty(object, property, { get: () => { const value = _get(); Object.defineProperty(object, property, { value, enumerable: true, configurable: true }); return value; }, enumerable: true, configurable: true }); }; /** @type {typeof import('color-convert')} */ let colorConvert; const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { if (colorConvert === undefined) { colorConvert = colorConvert$1; } const offset = isBackground ? 10 : 0; const styles = {}; for (const [sourceSpace, suite] of Object.entries(colorConvert)) { const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; if (sourceSpace === targetSpace) { styles[name] = wrap(identity, offset); } else if (typeof suite === 'object') { styles[name] = wrap(suite[targetSpace], offset); } } return styles; }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Alias bright black as gray (and grey) styles.color.gray = styles.color.blackBright; styles.bgColor.bgGray = styles.bgColor.bgBlackBright; styles.color.grey = styles.color.blackBright; styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles)) { for (const [styleName, style] of Object.entries(group)) { styles[styleName] = { open: "\x1B[".concat(style[0], "m"), close: "\x1B[".concat(style[1], "m") }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); var tty = { isatty() { return false; } }; var hasFlag$1 = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; const { env: env$2 } = process; let forceColor$1; if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) { forceColor$1 = 0; } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) { forceColor$1 = 1; } if ('FORCE_COLOR' in env$2) { if (env$2.FORCE_COLOR === 'true') { forceColor$1 = 1; } else if (env$2.FORCE_COLOR === 'false') { forceColor$1 = 0; } else { forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); } } function translateLevel$1(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$1(haveStream, streamIsTTY) { if (forceColor$1 === 0) { return 0; } if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) { return 3; } if (hasFlag$1('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor$1 === undefined) { return 0; } const min = forceColor$1 || 0; if (env$2.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = require$$0$1.release().split('.'); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$2) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$2) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; } if ('GITHUB_ACTIONS' in env$2) { return 1; } if (env$2.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$2) { const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$2.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$2.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { return 1; } if ('COLORTERM' in env$2) { return 1; } return min; } function getSupportLevel$1(stream) { const level = supportsColor$1(stream, stream && stream.isTTY); return translateLevel$1(level); } var supportsColor_1$1 = { supportsColor: getSupportLevel$1, stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))), stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2))) }; const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; var util = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); function unescape$1(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES$1.get(c) || c; } function parseArguments$1(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if (matches = chunk.match(STRING_REGEX$1)) { results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character)); } else { throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); } } return results; } function parseStyle$1(style) { STYLE_REGEX$1.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX$1.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments$1(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle$1(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error("Unknown Chalk style: ".concat(styleName)); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } var templates$1 = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape$1(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); styles.push({ inverse, styles: parseStyle$1(style) }); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMessage = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); throw new Error(errMessage); } return chunks.join(''); }; const { stdout: stdoutColor, stderr: stderrColor } = supportsColor_1$1; const { stringReplaceAll: stringReplaceAll$1, stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles$1)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, { value: builder }); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', { value: builder }); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const { level } = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const { level } = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto = Object.defineProperties(() => {}, Object.assign({}, styles, { level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } })); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' ')); }; // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const { openAll, closeAll } = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll$1(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!Array.isArray(firstString)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i])); } if (template === undefined) { template = templates$1; } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk$1 = Chalk(); // eslint-disable-line new-cap chalk$1.supportsColor = stdoutColor; chalk$1.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 }); // eslint-disable-line new-cap chalk$1.stderr.supportsColor = stderrColor; var source = chalk$1; const cliDescriptor = { key: _key => _key.length === 1 ? "-".concat(_key) : "--".concat(_key), value: _value => lib.apiDescriptor.value(_value), pair: ({ key, value }) => value === false ? "--no-".concat(key) : value === true ? cliDescriptor.key(key) : value === "" ? "".concat(cliDescriptor.key(key), " without an argument") : "".concat(cliDescriptor.key(key), "=").concat(value) }; class FlagSchema extends lib.ChoiceSchema { constructor({ name, flags }) { super({ name, choices: flags }); this._flags = flags.slice().sort(); } preprocess(value, utils) { if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) { const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3); if (suggestion) { utils.logger.warn(["Unknown flag ".concat(source.yellow(utils.descriptor.value(value)), ","), "did you mean ".concat(source.blue(utils.descriptor.value(suggestion)), "?")].join(" ")); return suggestion; } } return value; } expected() { return "a flag"; } } let hasDeprecationWarned; function normalizeOptions(options, optionInfos, { logger, isCLI = false, passThrough = false } = {}) { const unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : { [key]: value } : (key, value) => ({ [key]: value }); const descriptor = isCLI ? cliDescriptor : lib.apiDescriptor; const schemas = optionInfosToSchemas(optionInfos, { isCLI }); const normalizer = new lib.Normalizer(schemas, { logger, unknown, descriptor }); const shouldSuppressDuplicateDeprecationWarnings = logger !== false; if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) { normalizer._hasDeprecationWarned = hasDeprecationWarned; } const normalized = normalizer.normalize(options); if (shouldSuppressDuplicateDeprecationWarnings) { hasDeprecationWarned = normalizer._hasDeprecationWarned; } return normalized; } function optionInfosToSchemas(optionInfos, { isCLI }) { const schemas = []; if (isCLI) { schemas.push(lib.AnySchema.create({ name: "_" })); } for (const optionInfo of optionInfos) { schemas.push(optionInfoToSchema(optionInfo, { isCLI, optionInfos })); if (optionInfo.alias && isCLI) { schemas.push(lib.AliasSchema.create({ name: optionInfo.alias, sourceName: optionInfo.name })); } } return schemas; } function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { let SchemaConstructor; const parameters = { name: optionInfo.name }; const handlers = {}; switch (optionInfo.type) { case "int": SchemaConstructor = lib.IntegerSchema; if (isCLI) { parameters.preprocess = value => Number(value); } break; case "string": SchemaConstructor = lib.StringSchema; break; case "choice": SchemaConstructor = lib.ChoiceSchema; parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, { redirect: { to: { key: optionInfo.name, value: choiceInfo.redirect } } }) : choiceInfo); break; case "boolean": SchemaConstructor = lib.BooleanSchema; break; case "flag": SchemaConstructor = FlagSchema; parameters.flags = optionInfos.map(optionInfo => [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? "no-".concat(optionInfo.name) : [])).reduce((a, b) => a.concat(b), []); break; case "path": SchemaConstructor = lib.StringSchema; break; default: throw new Error("Unexpected type ".concat(optionInfo.type)); } if (optionInfo.exception) { parameters.validate = (value, schema, utils) => { return optionInfo.exception(value) || schema.validate(value, utils); }; } else { parameters.validate = (value, schema, utils) => { return value === undefined || schema.validate(value, utils); }; } if (optionInfo.redirect) { handlers.redirect = value => !value ? undefined : { to: { key: optionInfo.redirect.option, value: optionInfo.redirect.value } }; } if (optionInfo.deprecated) { handlers.deprecated = true; } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2 if (isCLI && !optionInfo.array) { const originalPreprocess = parameters.preprocess || (x => x); parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils); } return optionInfo.array ? lib.ArraySchema.create(Object.assign({}, isCLI ? { preprocess: v => [].concat(v) } : {}, {}, handlers, { valueSchema: SchemaConstructor.create(parameters) })) : SchemaConstructor.create(Object.assign({}, parameters, {}, handlers)); } function normalizeApiOptions(options, optionInfos, opts) { return normalizeOptions(options, optionInfos, opts); } function normalizeCliOptions(options, optionInfos, opts) { return normalizeOptions(options, optionInfos, Object.assign({ isCLI: true }, opts)); } var optionsNormalizer = { normalizeApiOptions, normalizeCliOptions }; var getLast = arr => arr[arr.length - 1]; function locStart(node, opts) { opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) { return locStart(node.declaration.decorators[0]); } if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) { return locStart(node.decorators[0]); } if (node.__location) { return node.__location.startOffset; } if (node.range) { return node.range[0]; } if (typeof node.start === "number") { return node.start; } if (node.loc) { return node.loc.start; } return null; } function locEnd(node) { const endNode = node.nodes && getLast(node.nodes); if (endNode && node.source && !node.source.end) { node = endNode; } if (node.__location) { return node.__location.endOffset; } const loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null; if (node.typeAnnotation) { return Math.max(loc, locEnd(node.typeAnnotation)); } if (node.loc && !loc) { return node.loc.end; } return loc; } function composeLoc(startNode, endNodeOrLength = startNode) { const length = typeof endNodeOrLength === "number" ? endNodeOrLength : -1; const start = locStart(startNode); const end = length !== -1 ? start + length : locEnd(endNodeOrLength); const startLoc = startNode.loc.start; return { start, end, range: [start, end], loc: { start: startLoc, end: length !== -1 ? { line: startLoc.line, column: startLoc.column + length } : endNodeOrLength.loc.end } }; } var loc = { locStart, locEnd, composeLoc }; var jsTokens = createCommonjsModule(function (module, exports) { // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell // License: MIT. (See LICENSE.) Object.defineProperty(exports, "__esModule", { value: true }); // This regex comes from regex.coffee, and is inserted here by generate-index.js // (run `npm run build`). exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; exports.matchToToken = function (match) { var token = { type: "invalid", value: match[0], closed: undefined }; if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; return token; }; }); unwrapExports(jsTokens); var jsTokens_1 = jsTokens.matchToToken; var ast = createCommonjsModule(function (module) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { function isExpression(node) { if (node == null) { return false; } switch (node.type) { case 'ArrayExpression': case 'AssignmentExpression': case 'BinaryExpression': case 'CallExpression': case 'ConditionalExpression': case 'FunctionExpression': case 'Identifier': case 'Literal': case 'LogicalExpression': case 'MemberExpression': case 'NewExpression': case 'ObjectExpression': case 'SequenceExpression': case 'ThisExpression': case 'UnaryExpression': case 'UpdateExpression': return true; } return false; } function isIterationStatement(node) { if (node == null) { return false; } switch (node.type) { case 'DoWhileStatement': case 'ForInStatement': case 'ForStatement': case 'WhileStatement': return true; } return false; } function isStatement(node) { if (node == null) { return false; } switch (node.type) { case 'BlockStatement': case 'BreakStatement': case 'ContinueStatement': case 'DebuggerStatement': case 'DoWhileStatement': case 'EmptyStatement': case 'ExpressionStatement': case 'ForInStatement': case 'ForStatement': case 'IfStatement': case 'LabeledStatement': case 'ReturnStatement': case 'SwitchStatement': case 'ThrowStatement': case 'TryStatement': case 'VariableDeclaration': case 'WhileStatement': case 'WithStatement': return true; } return false; } function isSourceElement(node) { return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; } function trailingStatement(node) { switch (node.type) { case 'IfStatement': if (node.alternate != null) { return node.alternate; } return node.consequent; case 'LabeledStatement': case 'ForStatement': case 'ForInStatement': case 'WhileStatement': case 'WithStatement': return node.body; } return null; } function isProblematicIfStatement(node) { var current; if (node.type !== 'IfStatement') { return false; } if (node.alternate == null) { return false; } current = node.consequent; do { if (current.type === 'IfStatement') { if (current.alternate == null) { return true; } } current = trailingStatement(current); } while (current); return false; } module.exports = { isExpression: isExpression, isStatement: isStatement, isIterationStatement: isIterationStatement, isSourceElement: isSourceElement, isProblematicIfStatement: isProblematicIfStatement, trailingStatement: trailingStatement }; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var ast_1 = ast.isExpression; var ast_2 = ast.isStatement; var ast_3 = ast.isIterationStatement; var ast_4 = ast.isSourceElement; var ast_5 = ast.isProblematicIfStatement; var ast_6 = ast.trailingStatement; var code = createCommonjsModule(function (module) { /* Copyright (C) 2013-2014 Yusuke Suzuki Copyright (C) 2014 Ivan Nikulin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. ES5Regex = { // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ }; ES6Regex = { // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; function isDecimalDigit(ch) { return 0x30 <= ch && ch <= 0x39; // 0..9 } function isHexDigit(ch) { return 0x30 <= ch && ch <= 0x39 || // 0..9 0x61 <= ch && ch <= 0x66 || // a..f 0x41 <= ch && ch <= 0x46; // A..F } function isOctalDigit(ch) { return ch >= 0x30 && ch <= 0x37; // 0..7 } // 7.2 White Space NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; function isWhiteSpace(ch) { return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; } // 7.3 Line Terminators function isLineTerminator(ch) { return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; } // 7.6 Identifier Names and Identifiers function fromCodePoint(cp) { if (cp <= 0xFFFF) { return String.fromCharCode(cp); } var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); return cu1 + cu2; } IDENTIFIER_START = new Array(0x80); for (ch = 0; ch < 0x80; ++ch) { IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } IDENTIFIER_PART = new Array(0x80); for (ch = 0; ch < 0x80; ++ch) { IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch >= 0x30 && ch <= 0x39 || // 0..9 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } function isIdentifierStartES5(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES5(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } function isIdentifierStartES6(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES6(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } module.exports = { isDecimalDigit: isDecimalDigit, isHexDigit: isHexDigit, isOctalDigit: isOctalDigit, isWhiteSpace: isWhiteSpace, isLineTerminator: isLineTerminator, isIdentifierStartES5: isIdentifierStartES5, isIdentifierPartES5: isIdentifierPartES5, isIdentifierStartES6: isIdentifierStartES6, isIdentifierPartES6: isIdentifierPartES6 }; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var code_1 = code.isDecimalDigit; var code_2 = code.isHexDigit; var code_3 = code.isOctalDigit; var code_4 = code.isWhiteSpace; var code_5 = code.isLineTerminator; var code_6 = code.isIdentifierStartES5; var code_7 = code.isIdentifierPartES5; var code_8 = code.isIdentifierStartES6; var code_9 = code.isIdentifierPartES6; var keyword = createCommonjsModule(function (module) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { var code$1 = code; function isStrictModeReservedWordES6(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'let': return true; default: return false; } } function isKeywordES5(id, strict) { // yield should not be treated as keyword under non-strict mode. if (!strict && id === 'yield') { return false; } return isKeywordES6(id, strict); } function isKeywordES6(id, strict) { if (strict && isStrictModeReservedWordES6(id)) { return true; } switch (id.length) { case 2: return id === 'if' || id === 'in' || id === 'do'; case 3: return id === 'var' || id === 'for' || id === 'new' || id === 'try'; case 4: return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; case 5: return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; case 6: return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; case 7: return id === 'default' || id === 'finally' || id === 'extends'; case 8: return id === 'function' || id === 'continue' || id === 'debugger'; case 10: return id === 'instanceof'; default: return false; } } function isReservedWordES5(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); } function isReservedWordES6(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } function isIdentifierNameES5(id) { var i, iz, ch; if (id.length === 0) { return false; } ch = id.charCodeAt(0); if (!code$1.isIdentifierStartES5(ch)) { return false; } for (i = 1, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (!code$1.isIdentifierPartES5(ch)) { return false; } } return true; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } function isIdentifierNameES6(id) { var i, iz, ch, lowCh, check; if (id.length === 0) { return false; } check = code$1.isIdentifierStartES6; for (i = 0, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (0xD800 <= ch && ch <= 0xDBFF) { ++i; if (i >= iz) { return false; } lowCh = id.charCodeAt(i); if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { return false; } ch = decodeUtf16(ch, lowCh); } if (!check(ch)) { return false; } check = code$1.isIdentifierPartES6; } return true; } function isIdentifierES5(id, strict) { return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); } function isIdentifierES6(id, strict) { return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); } module.exports = { isKeywordES5: isKeywordES5, isKeywordES6: isKeywordES6, isReservedWordES5: isReservedWordES5, isReservedWordES6: isReservedWordES6, isRestrictedWord: isRestrictedWord, isIdentifierNameES5: isIdentifierNameES5, isIdentifierNameES6: isIdentifierNameES6, isIdentifierES5: isIdentifierES5, isIdentifierES6: isIdentifierES6 }; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var keyword_1 = keyword.isKeywordES5; var keyword_2 = keyword.isKeywordES6; var keyword_3 = keyword.isReservedWordES5; var keyword_4 = keyword.isReservedWordES6; var keyword_5 = keyword.isRestrictedWord; var keyword_6 = keyword.isIdentifierNameES5; var keyword_7 = keyword.isIdentifierNameES6; var keyword_8 = keyword.isIdentifierES5; var keyword_9 = keyword.isIdentifierES6; var utils$1 = createCommonjsModule(function (module, exports) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { exports.ast = ast; exports.code = code; exports.keyword = keyword; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var utils_1$1 = utils$1.ast; var utils_2$1 = utils$1.code; var utils_3$1 = utils$1.keyword; var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp$1 = function escapeStringRegexp(str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe$1, '\\$&'); }; var colorName$2 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions$2 = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName$2) { if (colorName$2.hasOwnProperty(key)) { reverseKeywords[colorName$2[key]] = key; } } var convert = module.exports = { rgb: { channels: 3, labels: 'rgb' }, hsl: { channels: 3, labels: 'hsl' }, hsv: { channels: 3, labels: 'hsv' }, hwb: { channels: 3, labels: 'hwb' }, cmyk: { channels: 4, labels: 'cmyk' }, xyz: { channels: 3, labels: 'xyz' }, lab: { channels: 3, labels: 'lab' }, lch: { channels: 3, labels: 'lch' }, hex: { channels: 1, labels: ['hex'] }, keyword: { channels: 1, labels: ['keyword'] }, ansi16: { channels: 1, labels: ['ansi16'] }, ansi256: { channels: 1, labels: ['ansi256'] }, hcg: { channels: 3, labels: ['h', 'c', 'g'] }, apple: { channels: 3, labels: ['r16', 'g16', 'b16'] }, gray: { channels: 1, labels: ['gray'] } }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', { value: channels }); Object.defineProperty(convert[model], 'labels', { value: labels }); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function diffc(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = 1 / 3 + rdif - bdif; } else if (b === v) { h = 2 / 3 + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [h * 360, s * 100, v * 100]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName$2) { if (colorName$2.hasOwnProperty(keyword)) { var value = colorName$2[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName$2[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; var x = r * 0.4124 + g * 0.3576 + b * 0.1805; var y = r * 0.2126 + g * 0.7152 + b * 0.0722; var z = r * 0.0193 + g * 0.1192 + b * 0.9505; return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= l <= 1 ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - s * f); var t = 255 * v * (1 - s * (1 - f)); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= lmin <= 1 ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = x * 3.2406 + y * -1.5372 + z * -0.4986; g = x * -0.9689 + y * 1.8758 + z * 0.0415; b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round((r - 8) / 247 * 24) + 232; } var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = (color & 1) * mult * 255; var g = (color >> 1 & 1) * mult * 255; var b = (color >> 2 & 1) * mult * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = rem % 6 / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = integer >> 16 & 0xFF; var g = integer >> 8 & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = max - min; var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = (g - b) / chroma % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = h % 1 * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; }; convert.rgb.apple = function (rgb) { return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; }); var conversions_1$1 = conversions$2.rgb; var conversions_2$1 = conversions$2.hsl; var conversions_3$1 = conversions$2.hsv; var conversions_4$1 = conversions$2.hwb; var conversions_5$1 = conversions$2.cmyk; var conversions_6$1 = conversions$2.xyz; var conversions_7$1 = conversions$2.lab; var conversions_8$1 = conversions$2.lch; var conversions_9$1 = conversions$2.hex; var conversions_10$1 = conversions$2.keyword; var conversions_11$1 = conversions$2.ansi16; var conversions_12$1 = conversions$2.ansi256; var conversions_13$1 = conversions$2.hcg; var conversions_14$1 = conversions$2.apple; var conversions_15$1 = conversions$2.gray; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph$2() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions$2); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS$2(fromModel) { var graph = buildGraph$2(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions$2[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link$2(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion$2(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions$2[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link$2(conversions$2[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$2 = function route(fromModel) { var graph = deriveBFS$2(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion$2(toModel, graph); } return conversion; }; var convert$3 = {}; var models$2 = Object.keys(conversions$2); function wrapRaw$2(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded$2(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models$2.forEach(function (fromModel) { convert$3[fromModel] = {}; Object.defineProperty(convert$3[fromModel], 'channels', { value: conversions$2[fromModel].channels }); Object.defineProperty(convert$3[fromModel], 'labels', { value: conversions$2[fromModel].labels }); var routes = route$2(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert$3[fromModel][toModel] = wrapRounded$2(fn); convert$3[fromModel][toModel].raw = wrapRaw$2(fn); }); }); var colorConvert$2 = convert$3; var ansiStyles$2 = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert$2, arguments); return "\x1B[".concat(code + offset, "m"); }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert$2, arguments); return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert$2, arguments); return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); }; function assembleStyles() { const codes = new Map(); const styles = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], gray: [90, 39], // Bright color redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: "\x1B[".concat(style[0], "m"), close: "\x1B[".concat(style[1], "m") }; group[styleName] = styles[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles, groupName, { value: group, enumerable: false }); Object.defineProperty(styles, 'codes', { value: codes, enumerable: false }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert$2)) { if (typeof colorConvert$2[key] !== 'object') { continue; } const suite = colorConvert$2[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); const env$3 = process.env; let forceColor$2; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor$2 = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor$2 = true; } if ('FORCE_COLOR' in env$3) { forceColor$2 = env$3.FORCE_COLOR.length === 0 || parseInt(env$3.FORCE_COLOR, 10) !== 0; } function translateLevel$2(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$2(stream) { if (forceColor$2 === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor$2 !== true) { return 0; } const min = forceColor$2 ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = require$$0$1.release().split('.'); if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$3) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$3) || env$3.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$3) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$3.TEAMCITY_VERSION) ? 1 : 0; } if (env$3.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$3) { const version = parseInt((env$3.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$3.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$3.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$3.TERM)) { return 1; } if ('COLORTERM' in env$3) { return 1; } if (env$3.TERM === 'dumb') { return min; } return min; } function getSupportLevel$2(stream) { const level = supportsColor$2(stream); return translateLevel$2(level); } var supportsColor_1$2 = { supportsColor: getSupportLevel$2, stdout: getSupportLevel$2(process.stdout), stderr: getSupportLevel$2(process.stderr) }; const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); function unescape$2(c) { if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES$2.get(c) || c; } function parseArguments$2(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if (matches = chunk.match(STRING_REGEX$2)) { results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr)); } else { throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); } } return results; } function parseStyle$2(style) { STYLE_REGEX$2.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX$2.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments$2(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle$2(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error("Unknown Chalk style: ".concat(styleName)); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } var templates$2 = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape$2(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str)); styles.push({ inverse, styles: parseStyle$2(style) }); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle$2(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); throw new Error(errMsg); } return chunks.join(''); }; var chalk$2 = createCommonjsModule(function (module) { const stdoutColor = supportsColor_1$2.stdout; const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles$2.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles$2)) { ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles$2[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.color.close), 'g'); for (const model of Object.keys(ansiStyles$2.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$2.color.close, closeRe: ansiStyles$2.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$2.bgColor.close, closeRe: ansiStyles$2.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function builder() { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles$2.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles$2.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles$2.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return templates$2(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }); var chalk_1$1 = chalk$2.supportsColor; var lib$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldHighlight = shouldHighlight; exports.getChalk = getChalk; exports.default = highlight; var _jsTokens = _interopRequireWildcard(jsTokens); var _esutils = _interopRequireDefault(utils$1); var _chalk = _interopRequireDefault(chalk$2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; const JSX_TAG = /^[a-z][\w-]*$/i; const BRACKET = /^[()[\]{}]$/; function getTokenType(match) { const [offset, text] = match.slice(-2); const token = (0, _jsTokens.matchToToken)(match); if (token.type === "name") { if (_esutils.default.keyword.isReservedWordES6(token.value)) { return "keyword"; } if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); } else { return args[0]; } }); } function shouldHighlight(options) { return _chalk.default.supportsColor || options.forceColor; } function getChalk(options) { let chalk = _chalk.default; if (options.forceColor) { chalk = new _chalk.default.constructor({ enabled: true, level: 1 }); } return chalk; } function highlight(code, options = {}) { if (shouldHighlight(options)) { const chalk = getChalk(options); const defs = getDefs(chalk); return highlightTokens(defs, code); } else { return code; } } }); unwrapExports(lib$1); var lib_1 = lib$1.shouldHighlight; var lib_2 = lib$1.getChalk; var lib$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.codeFrameColumns = codeFrameColumns; exports.default = _default; var _highlight = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } let deprecationWarningShown = false; function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; function getMarkerLines(loc, source, opts) { const startLoc = Object.assign({ column: 0, line: -1 }, loc.start); const endLoc = Object.assign({}, startLoc, {}, loc.end); const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) { start = 0; } if (endLine === -1) { end = source.length; } const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) { for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) { markerLines[lineNumber] = true; } else if (i === 0) { const sourceLength = source[lineNumber - 1].length; markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; } else if (i === lineDiff) { markerLines[lineNumber] = [0, endColumn]; } else { const sourceLength = source[lineNumber - i].length; markerLines[lineNumber] = [0, sourceLength]; } } } else { if (startColumn === endColumn) { if (startColumn) { markerLines[startLine] = [startColumn, 0]; } else { markerLines[startLine] = true; } } else { markerLines[startLine] = [startColumn, endColumn - startColumn]; } } return { start, end, markerLines }; } function codeFrameColumns(rawLines, loc, opts = {}) { const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); const chalk = (0, _highlight.getChalk)(opts); const defs = getDefs(chalk); const maybeHighlight = (chalkFn, string) => { return highlighted ? chalkFn(string) : string; }; const lines = rawLines.split(NEWLINE); const { start, end, markerLines } = getMarkerLines(loc, lines, opts); const hasColumns = loc.start && typeof loc.start.column === "number"; const numberMaxWidth = String(end).length; const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { const number = start + 1 + index; const paddedNumber = " ".concat(number).slice(-numberMaxWidth); const gutter = " ".concat(paddedNumber, " | "); const hasMarker = markerLines[number]; const lastMarkerLine = !markerLines[number + 1]; if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); if (lastMarkerLine && opts.message) { markerLine += " " + maybeHighlight(defs.message, opts.message); } } return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); } else { return " ".concat(maybeHighlight(defs.gutter, gutter)).concat(line); } }).join("\n"); if (opts.message && !hasColumns) { frame = "".concat(" ".repeat(numberMaxWidth + 1)).concat(opts.message, "\n").concat(frame); } if (highlighted) { return chalk.reset(frame); } else { return frame; } } function _default(rawLines, lineNumber, colNumber, opts = {}) { if (!deprecationWarningShown) { deprecationWarningShown = true; const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; if (process.emitWarning) { process.emitWarning(message, "DeprecationWarning"); } else { const deprecationError = new Error(message); deprecationError.name = "DeprecationWarning"; console.warn(new Error(message)); } } colNumber = Math.max(colNumber, 0); const location = { start: { column: colNumber, line: lineNumber } }; return codeFrameColumns(rawLines, location, opts); } }); unwrapExports(lib$2); var lib_1$1 = lib$2.codeFrameColumns; const { ConfigError: ConfigError$1 } = errors; const { locStart: locStart$1, locEnd: locEnd$1 } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent // triggering the parsers getters. const ownNames = Object.getOwnPropertyNames; const ownDescriptor = Object.getOwnPropertyDescriptor; function getParsers(options) { const parsers = {}; for (const plugin of options.plugins) { if (!plugin.parsers) { continue; } for (const name of ownNames(plugin.parsers)) { Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name)); } } return parsers; } function resolveParser(opts, parsers) { parsers = parsers || getParsers(opts); if (typeof opts.parser === "function") { // Custom parser API always works with JavaScript. return { parse: opts.parser, astFormat: "estree", locStart: locStart$1, locEnd: locEnd$1 }; } if (typeof opts.parser === "string") { if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) { return parsers[opts.parser]; } /* istanbul ignore next */ { throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\". Parsers must be explicitly added to the standalone bundle.")); } } } function parse(text, opts) { const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call // the parsers getters when actually calling the parser `parse` function. const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, { enumerable: true, get() { return parsers[parserName].parse; } }), {}); const parser = resolveParser(opts, parsers); try { if (parser.preprocess) { text = parser.preprocess(text, opts); } return { text, ast: parser.parse(text, parsersForCustomParserApi, opts) }; } catch (error) { const { loc } = error; if (loc) { const codeFrame = lib$2; error.codeFrame = codeFrame.codeFrameColumns(text, loc, { highlightCode: true }); error.message += "\n" + error.codeFrame; throw error; } /* istanbul ignore next */ throw error.stack; } } var parser = { parse, resolveParser }; const { UndefinedParserError: UndefinedParserError$1 } = errors; const { getSupportInfo: getSupportInfo$1 } = support; const { resolveParser: resolveParser$1 } = parser; const hiddenDefaults = { astFormat: "estree", printer: {}, originalText: undefined, locStart: null, locEnd: null }; // Copy options and fill in default values. function normalize$1(options, opts) { opts = opts || {}; const rawOptions = Object.assign({}, options); const supportOptions = getSupportInfo$1({ plugins: options.plugins, showUnreleased: true, showDeprecated: true }).options; const defaults = Object.assign({}, hiddenDefaults, {}, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default]))); if (!rawOptions.parser) { if (!rawOptions.filepath) { const logger = opts.logger || console; logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred."); rawOptions.parser = "babel"; } else { rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins); if (!rawOptions.parser) { throw new UndefinedParserError$1("No parser could be inferred for file: ".concat(rawOptions.filepath)); } } } const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], { passThrough: true, logger: false })); rawOptions.astFormat = parser.astFormat; rawOptions.locEnd = parser.locEnd; rawOptions.locStart = parser.locStart; const plugin = getPlugin(rawOptions); rawOptions.printer = plugin.printers[rawOptions.astFormat]; const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, { [optionInfo.name]: optionInfo.pluginDefaults[plugin.name] }), {}); const mixedDefaults = Object.assign({}, defaults, {}, pluginDefaults); Object.keys(mixedDefaults).forEach(k => { if (rawOptions[k] == null) { rawOptions[k] = mixedDefaults[k]; } }); if (rawOptions.parser === "json") { rawOptions.trailingComma = "none"; } return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({ passThrough: Object.keys(hiddenDefaults) }, opts)); } function getPlugin(options) { const { astFormat } = options; if (!astFormat) { throw new Error("getPlugin() requires astFormat to be set"); } const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]); if (!printerPlugin) { throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\"")); } return printerPlugin; } function getInterpreter(filepath) { if (typeof filepath !== "string") { return ""; } let fd; try { fd = fs.openSync(filepath, "r"); } catch (err) { // istanbul ignore next return ""; } try { const liner = new readlines(fd); const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/); if (m1) { return m1[1]; } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/); if (m2) { return m2[1]; } return ""; } catch (err) { // There are some weird cases where paths are missing, causing Jest // failures. It's unclear what these correspond to in the real world. return ""; } finally { try { // There are some weird cases where paths are missing, causing Jest // failures. It's unclear what these correspond to in the real world. fs.closeSync(fd); } catch (err) {// nop } } } function inferParser(filepath, plugins) { const filename = path.basename(filepath).toLowerCase(); const languages = getSupportInfo$1({ plugins }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the // interpreter in the shebang line, if any; but since this requires FS access, // do it last. let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.find(name => name.toLowerCase() === filename)); if (!language && !filename.includes(".")) { const interpreter = getInterpreter(filepath); language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter)); } return language && language.parsers[0]; } var options$1 = { normalize: normalize$1, hiddenDefaults, inferParser }; function massageAST(ast, options, parent) { if (Array.isArray(ast)) { return ast.map(e => massageAST(e, options, parent)).filter(Boolean); } if (!ast || typeof ast !== "object") { return ast; } const newObj = {}; for (const key of Object.keys(ast)) { if (typeof ast[key] !== "function") { newObj[key] = massageAST(ast[key], options, ast); } } if (options.printer.massageAstNode) { const result = options.printer.massageAstNode(ast, newObj, parent); if (result === null) { return undefined; } if (result) { return result; } } return newObj; } var massageAst = massageAST; function assert() {} assert.ok = function () {}; assert.strictEqual = function () {}; /** * @param {Doc[]} parts * @returns Doc */ function concat(parts) { // access the internals of a document directly. // if(parts.length === 1) { // // If it's a single document, no need to concat it. // return parts[0]; // } return { type: "concat", parts }; } /** * @param {Doc} contents * @returns Doc */ function indent(contents) { return { type: "indent", contents }; } /** * @param {number} n * @param {Doc} contents * @returns Doc */ function align(n, contents) { return { type: "align", contents, n }; } /** * @param {Doc} contents * @param {object} [opts] - TBD ??? * @returns Doc */ function group(contents, opts) { opts = opts || {}; return { type: "group", id: opts.id, contents, break: !!opts.shouldBreak, expandedStates: opts.expandedStates }; } /** * @param {Doc} contents * @returns Doc */ function dedentToRoot(contents) { return align(-Infinity, contents); } /** * @param {Doc} contents * @returns Doc */ function markAsRoot(contents) { // @ts-ignore - TBD ???: return align({ type: "root" }, contents); } /** * @param {Doc} contents * @returns Doc */ function dedent(contents) { return align(-1, contents); } /** * @param {Doc[]} states * @param {object} [opts] - TBD ??? * @returns Doc */ function conditionalGroup(states, opts) { return group(states[0], Object.assign({}, opts, { expandedStates: states })); } /** * @param {Doc[]} parts * @returns Doc */ function fill(parts) { return { type: "fill", parts }; } /** * @param {Doc} [breakContents] * @param {Doc} [flatContents] * @param {object} [opts] - TBD ??? * @returns Doc */ function ifBreak(breakContents, flatContents, opts) { opts = opts || {}; return { type: "if-break", breakContents, flatContents, groupId: opts.groupId }; } /** * @param {Doc} contents * @returns Doc */ function lineSuffix(contents) { return { type: "line-suffix", contents }; } const lineSuffixBoundary = { type: "line-suffix-boundary" }; const breakParent = { type: "break-parent" }; const trim = { type: "trim" }; const line = { type: "line" }; const softline = { type: "line", soft: true }; const hardline = concat([{ type: "line", hard: true }, breakParent]); const literalline = concat([{ type: "line", hard: true, literal: true }, breakParent]); const cursor = { type: "cursor", placeholder: Symbol("cursor") }; /** * @param {Doc} sep * @param {Doc[]} arr * @returns Doc */ function join(sep, arr) { const res = []; for (let i = 0; i < arr.length; i++) { if (i !== 0) { res.push(sep); } res.push(arr[i]); } return concat(res); } /** * @param {Doc} doc * @param {number} size * @param {number} tabWidth */ function addAlignmentToDoc(doc, size, tabWidth) { let aligned = doc; if (size > 0) { // Use indent to add tabs for all the levels of tabs we need for (let i = 0; i < Math.floor(size / tabWidth); ++i) { aligned = indent(aligned); } // Use align for all the spaces that are needed aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current // indentation, so we use -Infinity to reset the indentation to 0 aligned = align(-Infinity, aligned); } return aligned; } var docBuilders = { concat, join, line, softline, hardline, literalline, group, conditionalGroup, fill, lineSuffix, lineSuffixBoundary, cursor, breakParent, ifBreak, trim, indent, align, addAlignmentToDoc, markAsRoot, dedentToRoot, dedent }; var ansiRegex = ({ onlyFirst = false } = {}) => { const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; /* eslint-disable yoda */ const isFullwidthCodePoint = codePoint => { if (Number.isNaN(codePoint)) { return false; } // Code points are derived from: // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane 0x20000 <= codePoint && codePoint <= 0x3FFFD)) { return true; } return false; }; var isFullwidthCodePoint_1 = isFullwidthCodePoint; var default_1$1 = isFullwidthCodePoint; isFullwidthCodePoint_1.default = default_1$1; var emojiRegex = function emojiRegex() { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; const stringWidth = string => { string = string.replace(emojiRegex(), ' '); if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || code >= 0x7F && code <= 0x9F) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint_1(code) ? 2 : 1; } return width; }; var stringWidth_1 = stringWidth; // TODO: remove this in the next major version var default_1$2 = stringWidth; stringWidth_1.default = default_1$2; const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g; var escapeStringRegexp$2 = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } return string.replace(matchOperatorsRegex, '\\$&'); }; const notAsciiRegex = /[^\x20-\x7F]/; function getPenultimate(arr) { if (arr.length > 1) { return arr[arr.length - 2]; } return null; } /** * @typedef {{backwards?: boolean}} SkipOptions */ /** * @param {string | RegExp} chars * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ function skip(chars) { return (text, index, opts) => { const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having // to check for failures (did someone say monads?). if (index === false) { return false; } const { length } = text; let cursor = index; while (cursor >= 0 && cursor < length) { const c = text.charAt(cursor); if (chars instanceof RegExp) { if (!chars.test(c)) { return cursor; } } else if (!chars.includes(c)) { return cursor; } backwards ? cursor-- : cursor++; } if (cursor === -1 || cursor === length) { // If we reached the beginning or end of the file, return the // out-of-bounds cursor. It's up to the caller to handle this // correctly. We don't want to indicate `false` though if it // actually skipped valid characters. return cursor; } return false; }; } /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipWhitespace = skip(/\s/); /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipSpaces = skip(" \t"); /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipToLineEnd = skip(",; \t"); /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipEverythingButNewLine = skip(/[^\r\n]/); /** * @param {string} text * @param {number | false} index * @returns {number | false} */ function skipInlineComment(text, index) { if (index === false) { return false; } if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { for (let i = index + 2; i < text.length; ++i) { if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { return i + 2; } } } return index; } /** * @param {string} text * @param {number | false} index * @returns {number | false} */ function skipTrailingComment(text, index) { if (index === false) { return false; } if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { return skipEverythingButNewLine(text, index); } return index; } // This one doesn't use the above helper function because it wants to // test \r\n in order and `skip` doesn't support ordering and we only // want to skip one newline. It's simple to implement. /** * @param {string} text * @param {number | false} index * @param {SkipOptions=} opts * @returns {number | false} */ function skipNewline(text, index, opts) { const backwards = opts && opts.backwards; if (index === false) { return false; } const atIndex = text.charAt(index); if (backwards) { if (text.charAt(index - 1) === "\r" && atIndex === "\n") { return index - 2; } if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { return index - 1; } } else { if (atIndex === "\r" && text.charAt(index + 1) === "\n") { return index + 2; } if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { return index + 1; } } return index; } /** * @param {string} text * @param {number} index * @param {SkipOptions=} opts * @returns {boolean} */ function hasNewline(text, index, opts) { opts = opts || {}; const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); const idx2 = skipNewline(text, idx, opts); return idx !== idx2; } /** * @param {string} text * @param {number} start * @param {number} end * @returns {boolean} */ function hasNewlineInRange(text, start, end) { for (let i = start; i < end; ++i) { if (text.charAt(i) === "\n") { return true; } } return false; } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locStart */ function isPreviousLineEmpty(text, node, locStart) { /** @type {number | false} */ let idx = locStart(node) - 1; idx = skipSpaces(text, idx, { backwards: true }); idx = skipNewline(text, idx, { backwards: true }); idx = skipSpaces(text, idx, { backwards: true }); const idx2 = skipNewline(text, idx, { backwards: true }); return idx !== idx2; } /** * @param {string} text * @param {number} index * @returns {boolean} */ function isNextLineEmptyAfterIndex(text, index) { /** @type {number | false} */ let oldIdx = null; /** @type {number | false} */ let idx = index; while (idx !== oldIdx) { // We need to skip all the potential trailing inline comments oldIdx = idx; idx = skipToLineEnd(text, idx); idx = skipInlineComment(text, idx); idx = skipSpaces(text, idx); } idx = skipTrailingComment(text, idx); idx = skipNewline(text, idx); return idx !== false && hasNewline(text, idx); } /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locEnd * @returns {boolean} */ function isNextLineEmpty(text, node, locEnd) { return isNextLineEmptyAfterIndex(text, locEnd(node)); } /** * @param {string} text * @param {number} idx * @returns {number | false} */ function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) { /** @type {number | false} */ let oldIdx = null; /** @type {number | false} */ let nextIdx = idx; while (nextIdx !== oldIdx) { oldIdx = nextIdx; nextIdx = skipSpaces(text, nextIdx); nextIdx = skipInlineComment(text, nextIdx); nextIdx = skipTrailingComment(text, nextIdx); nextIdx = skipNewline(text, nextIdx); } return nextIdx; } /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locEnd * @returns {number | false} */ function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node)); } /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locEnd * @returns {string} */ function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback? getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); } /** * @param {string} text * @param {number} index * @param {SkipOptions=} opts * @returns {boolean} */ function hasSpaces(text, index, opts) { opts = opts || {}; const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); return idx !== index; } /** * @param {{range?: [number, number], start?: number}} node * @param {number} index */ function setLocStart(node, index) { if (node.range) { node.range[0] = index; } else { node.start = index; } } /** * @param {{range?: [number, number], end?: number}} node * @param {number} index */ function setLocEnd(node, index) { if (node.range) { node.range[1] = index; } else { node.end = index; } } const PRECEDENCE = {}; [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => { tier.forEach(op => { PRECEDENCE[op] = i; }); }); function getPrecedence(op) { return PRECEDENCE[op]; } const equalityOperators = { "==": true, "!=": true, "===": true, "!==": true }; const multiplicativeOperators = { "*": true, "/": true, "%": true }; const bitshiftOperators = { ">>": true, ">>>": true, "<<": true }; function shouldFlatten(parentOp, nodeOp) { if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { return false; } // ** is right-associative // x ** y ** z --> x ** (y ** z) if (parentOp === "**") { return false; } // x == y == z --> (x == y) == z if (equalityOperators[parentOp] && equalityOperators[nodeOp]) { return false; } // x * y % z --> (x * y) % z if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) { return false; } // x * y / z --> (x * y) / z // x / y * z --> (x / y) * z if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) { return false; } // x << y << z --> (x << y) << z if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) { return false; } return true; } function isBitwiseOperator(operator) { return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&"; } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr // holds) `function`, `class`, or `do {}`. Will be overzealous if there's // already necessary grouping parentheses. function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) { node = getLeftMost(node); switch (node.type) { case "FunctionExpression": case "ClassExpression": case "DoExpression": return forbidFunctionClassAndDoExpr; case "ObjectExpression": return true; case "MemberExpression": case "OptionalMemberExpression": return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); case "TaggedTemplateExpression": if (node.tag.type === "FunctionExpression") { // IIFEs are always already parenthesized return false; } return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr); case "CallExpression": case "OptionalCallExpression": if (node.callee.type === "FunctionExpression") { // IIFEs are always already parenthesized return false; } return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr); case "ConditionalExpression": return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr); case "UpdateExpression": return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr); case "BindExpression": return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); case "SequenceExpression": return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr); case "TSAsExpression": return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr); default: return false; } } function getLeftMost(node) { if (node.left) { return getLeftMost(node.left); } return node; } /** * @param {string} value * @param {number} tabWidth * @param {number=} startIndex * @returns {number} */ function getAlignmentSize(value, tabWidth, startIndex) { startIndex = startIndex || 0; let size = 0; for (let i = startIndex; i < value.length; ++i) { if (value[i] === "\t") { // Tabs behave in a way that they are aligned to the nearest // multiple of tabWidth: // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... size = size + tabWidth - size % tabWidth; } else { size++; } } return size; } /** * @param {string} value * @param {number} tabWidth * @returns {number} */ function getIndentSize(value, tabWidth) { const lastNewlineIndex = value.lastIndexOf("\n"); if (lastNewlineIndex === -1) { return 0; } return getAlignmentSize( // All the leading whitespaces value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth); } /** * @typedef {'"' | "'"} Quote */ /** * * @param {string} raw * @param {Quote} preferredQuote * @returns {Quote} */ function getPreferredQuote(raw, preferredQuote) { // `rawContent` is the string exactly like it appeared in the input source // code, without its enclosing quotes. const rawContent = raw.slice(1, -1); /** @type {{ quote: '"', regex: RegExp }} */ const double = { quote: '"', regex: /"/g }; /** @type {{ quote: "'", regex: RegExp }} */ const single = { quote: "'", regex: /'/g }; const preferred = preferredQuote === "'" ? single : double; const alternate = preferred === single ? double : single; let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing // the string, we might want to enclose with the alternate quote instead, to // minimize the number of escaped quotes. if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote; } return result; } function printString(raw, options, isDirectiveLiteral) { // `rawContent` is the string exactly like it appeared in the input source // code, without its enclosing quotes. const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap // the quotes on a DirectiveLiteral. const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'"); /** @type {Quote} */ const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't // change the escape sequences they use. // See https://github.com/prettier/prettier/issues/1555 // and https://tc39.github.io/ecma262/#directive-prologue if (isDirectiveLiteral) { if (canChangeDirectiveQuotes) { return enclosingQuote + rawContent + enclosingQuote; } return raw; } // It might sound unnecessary to use `makeString` even if the string already // is enclosed with `enclosingQuote`, but it isn't. The string could contain // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes // sure that we consistently output the minimum amount of escaped quotes. return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml)); } /** * @param {string} rawContent * @param {Quote} enclosingQuote * @param {boolean=} unescapeUnnecessaryEscapes * @returns {string} */ function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to // enclose `rawContent` with `enclosingQuote`. const newContent = rawContent.replace(regex, (match, escaped, quote) => { // If we matched an escape, and the escaped character is a quote of the // other type than we intend to enclose the string with, there's no need for // it to be escaped, so return it _without_ the backslash. if (escaped === otherQuote) { return escaped; } // If we matched an unescaped quote and it is of the _same_ type as we // intend to enclose the string with, it must be escaped, so return it with // a backslash. if (quote === enclosingQuote) { return "\\" + quote; } if (quote) { return quote; } // Unescape any unnecessarily escaped character. // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped; }); return enclosingQuote + newContent + enclosingQuote; } function printNumber(rawNumber) { return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. .replace(/\.(?=e|$)/, ""); } /** * @param {string} str * @param {string} target * @returns {number} */ function getMaxContinuousCount(str, target) { const results = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g")); if (results === null) { return 0; } return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0); } function getMinNotPresentContinuousCount(str, target) { const matches = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g")); if (matches === null) { return 0; } const countPresent = new Map(); let max = 0; for (const match of matches) { const count = match.length / target.length; countPresent.set(count, true); if (count > max) { max = count; } } for (let i = 1; i < max; i++) { if (!countPresent.get(i)) { return i; } } return max + 1; } /** * @param {string} text * @returns {number} */ function getStringWidth(text) { if (!text) { return 0; } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` if (!notAsciiRegex.test(text)) { return text.length; } return stringWidth_1(text); } function hasIgnoreComment(path) { const node = path.getValue(); return hasNodeIgnoreComment(node); } function hasNodeIgnoreComment(node) { return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore); } function isNodeIgnoreComment(comment) { return comment.value.trim() === "prettier-ignore"; } function addCommentHelper(node, comment) { const comments = node.comments || (node.comments = []); comments.push(comment); comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment // We already "print" it via the raw text, we don't need to re-print it as a // comment if (node.type === "JSXText") { comment.printed = true; } } function addLeadingComment(node, comment) { comment.leading = true; comment.trailing = false; addCommentHelper(node, comment); } function addDanglingComment(node, comment) { comment.leading = false; comment.trailing = false; addCommentHelper(node, comment); } function addTrailingComment(node, comment) { comment.leading = false; comment.trailing = true; addCommentHelper(node, comment); } function isWithinParentArrayProperty(path, propertyName) { const node = path.getValue(); const parent = path.getParentNode(); if (parent == null) { return false; } if (!Array.isArray(parent[propertyName])) { return false; } const key = path.getName(); return parent[propertyName][key] === node; } function replaceEndOfLineWith(text, replacement) { const parts = []; for (const part of text.split("\n")) { if (parts.length !== 0) { parts.push(replacement); } parts.push(part); } return parts; } var util$1 = { replaceEndOfLineWith, getStringWidth, getMaxContinuousCount, getMinNotPresentContinuousCount, getPrecedence, shouldFlatten, isBitwiseOperator, getPenultimate, getLast, getNextNonSpaceNonCommentCharacterIndexWithStartIndex, getNextNonSpaceNonCommentCharacterIndex, getNextNonSpaceNonCommentCharacter, skip, skipWhitespace, skipSpaces, skipToLineEnd, skipEverythingButNewLine, skipInlineComment, skipTrailingComment, skipNewline, isNextLineEmptyAfterIndex, isNextLineEmpty, isPreviousLineEmpty, hasNewline, hasNewlineInRange, hasSpaces, setLocStart, setLocEnd, startsWithNoLookaheadToken, getAlignmentSize, getIndentSize, getPreferredQuote, printString, printNumber, hasIgnoreComment, hasNodeIgnoreComment, isNodeIgnoreComment, makeString, addLeadingComment, addDanglingComment, addTrailingComment, isWithinParentArrayProperty }; function guessEndOfLine(text) { const index = text.indexOf("\r"); if (index >= 0) { return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; } return "lf"; } function convertEndOfLineToChars(value) { switch (value) { case "cr": return "\r"; case "crlf": return "\r\n"; default: return "\n"; } } var endOfLine = { guessEndOfLine, convertEndOfLineToChars }; const { getStringWidth: getStringWidth$1 } = util$1; const { convertEndOfLineToChars: convertEndOfLineToChars$1 } = endOfLine; const { concat: concat$1, fill: fill$1, cursor: cursor$1 } = docBuilders; /** @type {Record} */ let groupModeMap; const MODE_BREAK = 1; const MODE_FLAT = 2; function rootIndent() { return { value: "", length: 0, queue: [] }; } function makeIndent(ind, options) { return generateInd(ind, { type: "indent" }, options); } function makeAlign(ind, n, options) { return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, { type: "dedent" }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, { root: ind }) : typeof n === "string" ? generateInd(ind, { type: "stringAlign", n }, options) : generateInd(ind, { type: "numberAlign", n }, options); } function generateInd(ind, newPart, options) { const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); let value = ""; let length = 0; let lastTabs = 0; let lastSpaces = 0; for (const part of queue) { switch (part.type) { case "indent": flush(); if (options.useTabs) { addTabs(1); } else { addSpaces(options.tabWidth); } break; case "stringAlign": flush(); value += part.n; length += part.n.length; break; case "numberAlign": lastTabs += 1; lastSpaces += part.n; break; /* istanbul ignore next */ default: throw new Error("Unexpected type '".concat(part.type, "'")); } } flushSpaces(); return Object.assign({}, ind, { value, length, queue }); function addTabs(count) { value += "\t".repeat(count); length += options.tabWidth * count; } function addSpaces(count) { value += " ".repeat(count); length += count; } function flush() { if (options.useTabs) { flushTabs(); } else { flushSpaces(); } } function flushTabs() { if (lastTabs > 0) { addTabs(lastTabs); } resetLast(); } function flushSpaces() { if (lastSpaces > 0) { addSpaces(lastSpaces); } resetLast(); } function resetLast() { lastTabs = 0; lastSpaces = 0; } } function trim$1(out) { if (out.length === 0) { return 0; } let trimCount = 0; // Trim whitespace at the end of line while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) { trimCount += out.pop().length; } if (out.length && typeof out[out.length - 1] === "string") { const trimmed = out[out.length - 1].replace(/[ \t]*$/, ""); trimCount += out[out.length - 1].length - trimmed.length; out[out.length - 1] = trimmed; } return trimCount; } function fits(next, restCommands, width, options, mustBeFlat) { let restIdx = restCommands.length; const cmds = [next]; // `out` is only used for width counting because `trim` requires to look // backwards for space characters. const out = []; while (width >= 0) { if (cmds.length === 0) { if (restIdx === 0) { return true; } cmds.push(restCommands[restIdx - 1]); restIdx--; continue; } const [ind, mode, doc] = cmds.pop(); if (typeof doc === "string") { out.push(doc); width -= getStringWidth$1(doc); } else { switch (doc.type) { case "concat": for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "indent": cmds.push([makeIndent(ind, options), mode, doc.contents]); break; case "align": cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); break; case "trim": width += trim$1(out); break; case "group": if (mustBeFlat && doc.break) { return false; } cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); if (doc.id) { groupModeMap[doc.id] = cmds[cmds.length - 1][1]; } break; case "fill": for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "if-break": { const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; if (groupMode === MODE_BREAK) { if (doc.breakContents) { cmds.push([ind, mode, doc.breakContents]); } } if (groupMode === MODE_FLAT) { if (doc.flatContents) { cmds.push([ind, mode, doc.flatContents]); } } break; } case "line": switch (mode) { // fallthrough case MODE_FLAT: if (!doc.hard) { if (!doc.soft) { out.push(" "); width -= 1; } break; } return true; case MODE_BREAK: return true; } break; } } } return false; } function printDocToString(doc, options) { groupModeMap = {}; const width = options.printWidth; const newLine = convertEndOfLineToChars$1(options.endOfLine); let pos = 0; // cmds is basically a stack. We've turned a recursive call into a // while loop which is much faster. The while loop below adds new // cmds to the array instead of recursively calling `print`. const cmds = [[rootIndent(), MODE_BREAK, doc]]; const out = []; let shouldRemeasure = false; let lineSuffix = []; while (cmds.length !== 0) { const [ind, mode, doc] = cmds.pop(); if (typeof doc === "string") { const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc; out.push(formatted); pos += getStringWidth$1(formatted); } else { switch (doc.type) { case "cursor": out.push(cursor$1.placeholder); break; case "concat": for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "indent": cmds.push([makeIndent(ind, options), mode, doc.contents]); break; case "align": cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); break; case "trim": pos -= trim$1(out); break; case "group": switch (mode) { case MODE_FLAT: if (!shouldRemeasure) { cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]); break; } // fallthrough case MODE_BREAK: { shouldRemeasure = false; const next = [ind, MODE_FLAT, doc.contents]; const rem = width - pos; if (!doc.break && fits(next, cmds, rem, options)) { cmds.push(next); } else { // Expanded states are a rare case where a document // can manually provide multiple representations of // itself. It provides an array of documents // going from the least expanded (most flattened) // representation first to the most expanded. If a // group has these, we need to manually go through // these states and find the first one that fits. if (doc.expandedStates) { const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1]; if (doc.break) { cmds.push([ind, MODE_BREAK, mostExpanded]); break; } else { for (let i = 1; i < doc.expandedStates.length + 1; i++) { if (i >= doc.expandedStates.length) { cmds.push([ind, MODE_BREAK, mostExpanded]); break; } else { const state = doc.expandedStates[i]; const cmd = [ind, MODE_FLAT, state]; if (fits(cmd, cmds, rem, options)) { cmds.push(cmd); break; } } } } } else { cmds.push([ind, MODE_BREAK, doc.contents]); } } break; } } if (doc.id) { groupModeMap[doc.id] = cmds[cmds.length - 1][1]; } break; // Fills each line with as much code as possible before moving to a new // line with the same indentation. // // Expects doc.parts to be an array of alternating content and // whitespace. The whitespace contains the linebreaks. // // For example: // ["I", line, "love", line, "monkeys"] // or // [{ type: group, ... }, softline, { type: group, ... }] // // It uses this parts structure to handle three main layout cases: // * The first two content items fit on the same line without // breaking // -> output the first content item and the whitespace "flat". // * Only the first content item fits on the line without breaking // -> output the first content item "flat" and the whitespace with // "break". // * Neither content item fits on the line without breaking // -> output the first content item and the whitespace with "break". case "fill": { const rem = width - pos; const { parts } = doc; if (parts.length === 0) { break; } const [content, whitespace] = parts; const contentFlatCmd = [ind, MODE_FLAT, content]; const contentBreakCmd = [ind, MODE_BREAK, content]; const contentFits = fits(contentFlatCmd, [], rem, options, true); if (parts.length === 1) { if (contentFits) { cmds.push(contentFlatCmd); } else { cmds.push(contentBreakCmd); } break; } const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; if (parts.length === 2) { if (contentFits) { cmds.push(whitespaceFlatCmd); cmds.push(contentFlatCmd); } else { cmds.push(whitespaceBreakCmd); cmds.push(contentBreakCmd); } break; } // At this point we've handled the first pair (context, separator) // and will create a new fill doc for the rest of the content. // Ideally we wouldn't mutate the array here but copying all the // elements to a new array would make this algorithm quadratic, // which is unusable for large arrays (e.g. large texts in JSX). parts.splice(0, 2); const remainingCmd = [ind, mode, fill$1(parts)]; const secondContent = parts[0]; const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])]; const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true); if (firstAndSecondContentFits) { cmds.push(remainingCmd); cmds.push(whitespaceFlatCmd); cmds.push(contentFlatCmd); } else if (contentFits) { cmds.push(remainingCmd); cmds.push(whitespaceBreakCmd); cmds.push(contentFlatCmd); } else { cmds.push(remainingCmd); cmds.push(whitespaceBreakCmd); cmds.push(contentBreakCmd); } break; } case "if-break": { const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; if (groupMode === MODE_BREAK) { if (doc.breakContents) { cmds.push([ind, mode, doc.breakContents]); } } if (groupMode === MODE_FLAT) { if (doc.flatContents) { cmds.push([ind, mode, doc.flatContents]); } } break; } case "line-suffix": lineSuffix.push([ind, mode, doc.contents]); break; case "line-suffix-boundary": if (lineSuffix.length > 0) { cmds.push([ind, mode, { type: "line", hard: true }]); } break; case "line": switch (mode) { case MODE_FLAT: if (!doc.hard) { if (!doc.soft) { out.push(" "); pos += 1; } break; } else { // This line was forced into the output even if we // were in flattened mode, so we need to tell the next // group that no matter what, it needs to remeasure // because the previous measurement didn't accurately // capture the entire expression (this is necessary // for nested groups) shouldRemeasure = true; } // fallthrough case MODE_BREAK: if (lineSuffix.length) { cmds.push([ind, mode, doc]); cmds.push(...lineSuffix.reverse()); lineSuffix = []; break; } if (doc.literal) { if (ind.root) { out.push(newLine, ind.root.value); pos = ind.root.length; } else { out.push(newLine); pos = 0; } } else { pos -= trim$1(out); out.push(newLine + ind.value); pos = ind.length; } break; } break; } } } const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder); if (cursorPlaceholderIndex !== -1) { const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1); const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); return { formatted: beforeCursor + aroundCursor + afterCursor, cursorNodeStart: beforeCursor.length, cursorNodeText: aroundCursor }; } return { formatted: out.join("") }; } var docPrinter = { printDocToString }; const traverseDocOnExitStackMarker = {}; function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { const docsStack = [doc]; while (docsStack.length !== 0) { const doc = docsStack.pop(); if (doc === traverseDocOnExitStackMarker) { onExit(docsStack.pop()); continue; } let shouldRecurse = true; if (onEnter) { if (onEnter(doc) === false) { shouldRecurse = false; } } if (onExit) { docsStack.push(doc); docsStack.push(traverseDocOnExitStackMarker); } if (shouldRecurse) { // When there are multiple parts to process, // the parts need to be pushed onto the stack in reverse order, // so that they are processed in the original order // when the stack is popped. if (doc.type === "concat" || doc.type === "fill") { for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) { docsStack.push(doc.parts[i]); } } else if (doc.type === "if-break") { if (doc.flatContents) { docsStack.push(doc.flatContents); } if (doc.breakContents) { docsStack.push(doc.breakContents); } } else if (doc.type === "group" && doc.expandedStates) { if (shouldTraverseConditionalGroups) { for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) { docsStack.push(doc.expandedStates[i]); } } else { docsStack.push(doc.contents); } } else if (doc.contents) { docsStack.push(doc.contents); } } } } function mapDoc(doc, cb) { if (doc.type === "concat" || doc.type === "fill") { const parts = doc.parts.map(part => mapDoc(part, cb)); return cb(Object.assign({}, doc, { parts })); } else if (doc.type === "if-break") { const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb); return cb(Object.assign({}, doc, { breakContents, flatContents })); } else if (doc.contents) { const contents = mapDoc(doc.contents, cb); return cb(Object.assign({}, doc, { contents })); } return cb(doc); } function findInDoc(doc, fn, defaultValue) { let result = defaultValue; let hasStopped = false; function findInDocOnEnterFn(doc) { const maybeResult = fn(doc); if (maybeResult !== undefined) { hasStopped = true; result = maybeResult; } if (hasStopped) { return false; } } traverseDoc(doc, findInDocOnEnterFn); return result; } function isEmpty(n) { return typeof n === "string" && n.length === 0; } function isLineNextFn(doc) { if (typeof doc === "string") { return false; } if (doc.type === "line") { return true; } } function isLineNext(doc) { return findInDoc(doc, isLineNextFn, false); } function willBreakFn(doc) { if (doc.type === "group" && doc.break) { return true; } if (doc.type === "line" && doc.hard) { return true; } if (doc.type === "break-parent") { return true; } } function willBreak(doc) { return findInDoc(doc, willBreakFn, false); } function breakParentGroup(groupStack) { if (groupStack.length > 0) { const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because // the user is expected to manually handle what breaks. if (!parentGroup.expandedStates) { parentGroup.break = true; } } return null; } function propagateBreaks(doc) { const alreadyVisitedSet = new Set(); const groupStack = []; function propagateBreaksOnEnterFn(doc) { if (doc.type === "break-parent") { breakParentGroup(groupStack); } if (doc.type === "group") { groupStack.push(doc); if (alreadyVisitedSet.has(doc)) { return false; } alreadyVisitedSet.add(doc); } } function propagateBreaksOnExitFn(doc) { if (doc.type === "group") { const group = groupStack.pop(); if (group.break) { breakParentGroup(groupStack); } } } traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, /* shouldTraverseConditionalGroups */ true); } function removeLinesFn(doc) { // Force this doc into flat mode by statically converting all // lines into spaces (or soft lines into nothing). Hard lines // should still output because there's too great of a chance // of breaking existing assumptions otherwise. if (doc.type === "line" && !doc.hard) { return doc.soft ? "" : " "; } else if (doc.type === "if-break") { return doc.flatContents || ""; } return doc; } function removeLines(doc) { return mapDoc(doc, removeLinesFn); } function stripTrailingHardline(doc) { // HACK remove ending hardline, original PR: #1984 if (doc.type === "concat" && doc.parts.length !== 0) { const lastPart = doc.parts[doc.parts.length - 1]; if (lastPart.type === "concat") { if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") { return { type: "concat", parts: doc.parts.slice(0, -1) }; } return { type: "concat", parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) }; } } return doc; } var docUtils = { isEmpty, willBreak, isLineNext, traverseDoc, findInDoc, mapDoc, propagateBreaks, removeLines, stripTrailingHardline }; function flattenDoc(doc) { if (doc.type === "concat") { const res = []; for (let i = 0; i < doc.parts.length; ++i) { const doc2 = doc.parts[i]; if (typeof doc2 !== "string" && doc2.type === "concat") { res.push(...flattenDoc(doc2).parts); } else { const flattened = flattenDoc(doc2); if (flattened !== "") { res.push(flattened); } } } return Object.assign({}, doc, { parts: res }); } else if (doc.type === "if-break") { return Object.assign({}, doc, { breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null }); } else if (doc.type === "group") { return Object.assign({}, doc, { contents: flattenDoc(doc.contents), expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates }); } else if (doc.contents) { return Object.assign({}, doc, { contents: flattenDoc(doc.contents) }); } return doc; } function printDoc(doc) { if (typeof doc === "string") { return JSON.stringify(doc); } if (doc.type === "line") { if (doc.literal) { return "literalline"; } if (doc.hard) { return "hardline"; } if (doc.soft) { return "softline"; } return "line"; } if (doc.type === "break-parent") { return "breakParent"; } if (doc.type === "trim") { return "trim"; } if (doc.type === "concat") { return "[" + doc.parts.map(printDoc).join(", ") + "]"; } if (doc.type === "indent") { return "indent(" + printDoc(doc.contents) + ")"; } if (doc.type === "align") { return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")"; } if (doc.type === "if-break") { return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; } if (doc.type === "group") { if (doc.expandedStates) { return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; } return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; } if (doc.type === "fill") { return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; } if (doc.type === "line-suffix") { return "lineSuffix(" + printDoc(doc.contents) + ")"; } if (doc.type === "line-suffix-boundary") { return "lineSuffixBoundary"; } throw new Error("Unknown doc type " + doc.type); } var docDebug = { printDocToDebug(doc) { return printDoc(flattenDoc(doc)); } }; var document = { builders: docBuilders, printer: docPrinter, utils: docUtils, debug: docDebug }; const { getMaxContinuousCount: getMaxContinuousCount$1, getStringWidth: getStringWidth$2, getAlignmentSize: getAlignmentSize$1, getIndentSize: getIndentSize$1, skip: skip$1, skipWhitespace: skipWhitespace$1, skipSpaces: skipSpaces$1, skipNewline: skipNewline$1, skipToLineEnd: skipToLineEnd$1, skipEverythingButNewLine: skipEverythingButNewLine$1, skipInlineComment: skipInlineComment$1, skipTrailingComment: skipTrailingComment$1, hasNewline: hasNewline$1, hasNewlineInRange: hasNewlineInRange$1, hasSpaces: hasSpaces$1, isNextLineEmpty: isNextLineEmpty$1, isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, isPreviousLineEmpty: isPreviousLineEmpty$1, getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, makeString: makeString$1, addLeadingComment: addLeadingComment$1, addDanglingComment: addDanglingComment$1, addTrailingComment: addTrailingComment$1 } = util$1; var utilShared = { getMaxContinuousCount: getMaxContinuousCount$1, getStringWidth: getStringWidth$2, getAlignmentSize: getAlignmentSize$1, getIndentSize: getIndentSize$1, skip: skip$1, skipWhitespace: skipWhitespace$1, skipSpaces: skipSpaces$1, skipNewline: skipNewline$1, skipToLineEnd: skipToLineEnd$1, skipEverythingButNewLine: skipEverythingButNewLine$1, skipInlineComment: skipInlineComment$1, skipTrailingComment: skipTrailingComment$1, hasNewline: hasNewline$1, hasNewlineInRange: hasNewlineInRange$1, hasSpaces: hasSpaces$1, isNextLineEmpty: isNextLineEmpty$1, isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, isPreviousLineEmpty: isPreviousLineEmpty$1, getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, makeString: makeString$1, addLeadingComment: addLeadingComment$1, addDanglingComment: addDanglingComment$1, addTrailingComment: addTrailingComment$1 }; const { concat: concat$2, line: line$1, hardline: hardline$1, breakParent: breakParent$1, indent: indent$1, lineSuffix: lineSuffix$1, join: join$1, cursor: cursor$2 } = document.builders; const { hasNewline: hasNewline$2, skipNewline: skipNewline$2, isPreviousLineEmpty: isPreviousLineEmpty$2 } = util$1; const { addLeadingComment: addLeadingComment$2, addDanglingComment: addDanglingComment$2, addTrailingComment: addTrailingComment$2 } = utilShared; const childNodesCacheKey = Symbol("child-nodes"); function getSortedChildNodes(node, options, resultArray) { if (!node) { return; } const { printer, locStart, locEnd } = options; if (resultArray) { if (printer.canAttachComment && printer.canAttachComment(node)) { // This reverse insertion sort almost always takes constant // time because we almost always (maybe always?) append the // nodes in order anyway. let i; for (i = resultArray.length - 1; i >= 0; --i) { if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) { break; } } resultArray.splice(i + 1, 0, node); return; } } else if (node[childNodesCacheKey]) { return node[childNodesCacheKey]; } const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode").map(n => node[n]); if (!childNodes) { return; } if (!resultArray) { Object.defineProperty(node, childNodesCacheKey, { value: resultArray = [], enumerable: false }); } childNodes.forEach(childNode => { getSortedChildNodes(childNode, options, resultArray); }); return resultArray; } // As efficiently as possible, decorate the comment object with // .precedingNode, .enclosingNode, and/or .followingNode properties, at // least one of which is guaranteed to be defined. function decorateComment(node, comment, options) { const { locStart, locEnd } = options; const childNodes = getSortedChildNodes(node, options); let precedingNode; let followingNode; // Time to dust off the old binary search robes and wizard hat. let left = 0; let right = childNodes.length; while (left < right) { const middle = left + right >> 1; const child = childNodes[middle]; if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) { // The comment is completely contained by this child node. comment.enclosingNode = child; decorateComment(child, comment, options); return; // Abandon the binary search at this level. } if (locEnd(child) - locStart(comment) <= 0) { // This child node falls completely before the comment. // Because we will never consider this node or any nodes // before it again, this node must be the closest preceding // node we have encountered so far. precedingNode = child; left = middle + 1; continue; } if (locEnd(comment) - locStart(child) <= 0) { // This child node falls completely after the comment. // Because we will never consider this node or any nodes after // it again, this node must be the closest following node we // have encountered so far. followingNode = child; right = middle; continue; } /* istanbul ignore next */ throw new Error("Comment location overlaps with node location"); } // We don't want comments inside of different expressions inside of the same // template literal to move to another expression. if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") { const { quasis } = comment.enclosingNode; const commentIndex = findExpressionIndexForComment(quasis, comment, options); if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) { precedingNode = null; } if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) { followingNode = null; } } if (precedingNode) { comment.precedingNode = precedingNode; } if (followingNode) { comment.followingNode = followingNode; } } function attach(comments, ast, text, options) { if (!Array.isArray(comments)) { return; } const tiesToBreak = []; const { locStart, locEnd } = options; comments.forEach((comment, i) => { if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") { if (locStart(comment) - locStart(ast) <= 0) { addLeadingComment$2(ast, comment); return; } if (locEnd(comment) - locEnd(ast) >= 0) { addTrailingComment$2(ast, comment); return; } } decorateComment(ast, comment, options); const { precedingNode, enclosingNode, followingNode } = comment; const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false; const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false; const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false; const isLastComment = comments.length - 1 === i; if (hasNewline$2(text, locStart(comment), { backwards: true })) { // If a comment exists on its own line, prefer a leading comment. // We also need to check if it's the first line of the file. if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) { // Always a leading comment. addLeadingComment$2(followingNode, comment); } else if (precedingNode) { addTrailingComment$2(precedingNode, comment); } else if (enclosingNode) { addDanglingComment$2(enclosingNode, comment); } else { // There are no nodes, let's attach it to the root of the ast /* istanbul ignore next */ addDanglingComment$2(ast, comment); } } else if (hasNewline$2(text, locEnd(comment))) { if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) { // There is content before this comment on the same line, but // none after it, so prefer a trailing comment of the previous node. addTrailingComment$2(precedingNode, comment); } else if (followingNode) { addLeadingComment$2(followingNode, comment); } else if (enclosingNode) { addDanglingComment$2(enclosingNode, comment); } else { // There are no nodes, let's attach it to the root of the ast /* istanbul ignore next */ addDanglingComment$2(ast, comment); } } else { if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) { // Otherwise, text exists both before and after the comment on // the same line. If there is both a preceding and following // node, use a tie-breaking algorithm to determine if it should // be attached to the next or previous node. In the last case, // simply attach the right node; const tieCount = tiesToBreak.length; if (tieCount > 0) { const lastTie = tiesToBreak[tieCount - 1]; if (lastTie.followingNode !== comment.followingNode) { breakTies(tiesToBreak, text, options); } } tiesToBreak.push(comment); } else if (precedingNode) { addTrailingComment$2(precedingNode, comment); } else if (followingNode) { addLeadingComment$2(followingNode, comment); } else if (enclosingNode) { addDanglingComment$2(enclosingNode, comment); } else { // There are no nodes, let's attach it to the root of the ast /* istanbul ignore next */ addDanglingComment$2(ast, comment); } } }); breakTies(tiesToBreak, text, options); comments.forEach(comment => { // These node references were useful for breaking ties, but we // don't need them anymore, and they create cycles in the AST that // may lead to infinite recursion if we don't delete them here. delete comment.precedingNode; delete comment.enclosingNode; delete comment.followingNode; }); } function breakTies(tiesToBreak, text, options) { const tieCount = tiesToBreak.length; if (tieCount === 0) { return; } const { precedingNode, followingNode, enclosingNode } = tiesToBreak[0]; const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/; let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps // between the tied comments. In order to qualify as leading, a // comment must be separated from followingNode by an unbroken series of // gaps (or other comments). Gaps should only contain whitespace or open // parentheses. let indexOfFirstLeadingComment; for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { const comment = tiesToBreak[indexOfFirstLeadingComment - 1]; assert.strictEqual(comment.precedingNode, precedingNode); assert.strictEqual(comment.followingNode, followingNode); const gap = text.slice(options.locEnd(comment), gapEndPos); if (gapRegExp.test(gap)) { gapEndPos = options.locStart(comment); } else { // The gap string contained something other than whitespace or open // parentheses. break; } } tiesToBreak.forEach((comment, i) => { if (i < indexOfFirstLeadingComment) { addTrailingComment$2(precedingNode, comment); } else { addLeadingComment$2(followingNode, comment); } }); tiesToBreak.length = 0; } function printComment(commentPath, options) { const comment = commentPath.getValue(); comment.printed = true; return options.printer.printComment(commentPath, options); } function findExpressionIndexForComment(quasis, comment, options) { const startPos = options.locStart(comment) - 1; for (let i = 1; i < quasis.length; ++i) { if (startPos < getQuasiRange(quasis[i]).start) { return i - 1; } } // We haven't found it, it probably means that some of the locations are off. // Let's just return the first one. /* istanbul ignore next */ return 0; } function getQuasiRange(expr) { if (expr.start !== undefined) { // Babel return { start: expr.start, end: expr.end }; } // Flow return { start: expr.range[0], end: expr.range[1] }; } function printLeadingComment(commentPath, print, options) { const comment = commentPath.getValue(); const contents = printComment(commentPath, options); if (!contents) { return ""; } const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the // same line or not. if (isBlock) { const lineBreak = hasNewline$2(options.originalText, options.locEnd(comment)) ? hasNewline$2(options.originalText, options.locStart(comment), { backwards: true }) ? hardline$1 : line$1 : " "; return concat$2([contents, lineBreak]); } return concat$2([contents, hardline$1]); } function printTrailingComment(commentPath, print, options) { const comment = commentPath.getValue(); const contents = printComment(commentPath, options); if (!contents) { return ""; } const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break // when the parentParentNode is a ClassDeclaration/-Expression // And the parentNode is in the superClass property const parentNode = commentPath.getNode(1); const parentParentNode = commentPath.getNode(2); const isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode; if (hasNewline$2(options.originalText, options.locStart(comment), { backwards: true })) { // This allows comments at the end of nested structures: // { // x: 1, // y: 2 // // A comment // } // Those kinds of comments are almost always leading comments, but // here it doesn't go "outside" the block and turns it into a // trailing comment for `2`. We can simulate the above by checking // if this a comment on its own line; normal trailing comments are // always at the end of another expression. const isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart); return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents])); } else if (isBlock || isParentSuperClass) { // Trailing block comments never need a newline return concat$2([" ", contents]); } return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]); } function printDanglingComments(path, options, sameIndent, filter) { const parts = []; const node = path.getValue(); if (!node || !node.comments) { return ""; } path.each(commentPath => { const comment = commentPath.getValue(); if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) { parts.push(printComment(commentPath, options)); } }, "comments"); if (parts.length === 0) { return ""; } if (sameIndent) { return join$1(hardline$1, parts); } return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)])); } function prependCursorPlaceholder(path, options, printed) { if (path.getNode() === options.cursorNode && path.getValue()) { return concat$2([cursor$2, printed, cursor$2]); } return printed; } function printComments(path, print, options, needsSemi) { const value = path.getValue(); const printed = print(path); const comments = value && value.comments; if (!comments || comments.length === 0) { return prependCursorPlaceholder(path, options, printed); } const leadingParts = []; const trailingParts = [needsSemi ? ";" : "", printed]; path.each(commentPath => { const comment = commentPath.getValue(); const { leading, trailing } = comment; if (leading) { const contents = printLeadingComment(commentPath, print, options); if (!contents) { return; } leadingParts.push(contents); const text = options.originalText; const index = skipNewline$2(text, options.locEnd(comment)); if (index !== false && hasNewline$2(text, index)) { leadingParts.push(hardline$1); } } else if (trailing) { trailingParts.push(printTrailingComment(commentPath, print, options)); } }, "comments"); return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts))); } var comments = { attach, printComments, printDanglingComments, getSortedChildNodes }; function getNodeHelper(path, count) { const stackIndex = getNodeStackIndexHelper(path.stack, count); return stackIndex === -1 ? null : path.stack[stackIndex]; } function getNodeStackIndexHelper(stack, count) { for (let i = stack.length - 1; i >= 0; i -= 2) { const value = stack[i]; if (value && !Array.isArray(value) && --count < 0) { return i; } } return -1; } class FastPath { constructor(value) { this.stack = [value]; } // The name of the current property is always the penultimate element of // this.stack, and always a String. getName() { const { stack } = this; const { length } = stack; if (length > 1) { return stack[length - 2]; } // Since the name is always a string, null is a safe sentinel value to // return if we do not know the name of the (root) value. /* istanbul ignore next */ return null; } // The value of the current property is always the final element of // this.stack. getValue() { return getLast(this.stack); } getNode(count = 0) { return getNodeHelper(this, count); } getParentNode(count = 0) { return getNodeHelper(this, count + 1); } // Temporarily push properties named by string arguments given after the // callback function onto this.stack, then call the callback with a // reference to this (modified) FastPath object. Note that the stack will // be restored to its original state after the callback is finished, so it // is probably a mistake to retain a reference to the path. call(callback, ...names) { const { stack } = this; const { length } = stack; let value = getLast(stack); for (const name of names) { value = value[name]; stack.push(name, value); } const result = callback(this); stack.length = length; return result; } callParent(callback, count = 0) { const stackIndex = getNodeStackIndexHelper(this.stack, count + 1); const parentValues = this.stack.splice(stackIndex + 1); const result = callback(this); this.stack.push(...parentValues); return result; } // Similar to FastPath.prototype.call, except that the value obtained by // accessing this.getValue()[name1][name2]... should be array-like. The // callback will be called with a reference to this path object for each // element of the array. each(callback, ...names) { const { stack } = this; const { length } = stack; let value = getLast(stack); for (const name of names) { value = value[name]; stack.push(name, value); } for (let i = 0; i < value.length; ++i) { if (i in value) { stack.push(i, value[i]); // If the callback needs to know the value of i, call // path.getName(), assuming path is the parameter name. callback(this); stack.length -= 2; } } stack.length = length; } // Similar to FastPath.prototype.each, except that the results of the // callback function invocations are stored in an array and returned at // the end of the iteration. map(callback, ...names) { const { stack } = this; const { length } = stack; let value = getLast(stack); for (const name of names) { value = value[name]; stack.push(name, value); } const result = new Array(value.length); for (let i = 0; i < value.length; ++i) { if (i in value) { stack.push(i, value[i]); result[i] = callback(this, i); stack.length -= 2; } } stack.length = length; return result; } /** * @param {...( * | ((node: any, name: string | null, number: number | null) => boolean) * | undefined * )} predicates */ match(...predicates) { let stackPointer = this.stack.length - 1; let name = null; let node = this.stack[stackPointer--]; for (const predicate of predicates) { if (node === undefined) { return false; } // skip index/array let number = null; if (typeof name === "number") { number = name; name = this.stack[stackPointer--]; node = this.stack[stackPointer--]; } if (predicate && !predicate(node, name, number)) { return false; } name = this.stack[stackPointer--]; node = this.stack[stackPointer--]; } return true; } } var fastPath = FastPath; const { normalize: normalize$2 } = options$1; function printSubtree(path, print, options, printAstToDoc) { if (options.printer.embed) { return options.printer.embed(path, print, (text, partialNextOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc), options); } } function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { const nextOptions = normalize$2(Object.assign({}, parentOptions, {}, partialNextOptions, { parentParser: parentOptions.parser, embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"), originalText: text }), { passThrough: true }); const result = parser.parse(text, nextOptions); const { ast } = result; text = result.text; const astComments = ast.comments; delete ast.comments; comments.attach(astComments, ast, text, nextOptions); return printAstToDoc(ast, nextOptions); } var multiparser = { printSubtree }; const doc = document; const docBuilders$1 = doc.builders; const { concat: concat$3, hardline: hardline$2, addAlignmentToDoc: addAlignmentToDoc$1 } = docBuilders$1; const docUtils$1 = doc.utils; /** * Takes an abstract syntax tree (AST) and recursively converts it to a * document (series of printing primitives). * * This is done by descending down the AST recursively. The recursion * involves two functions that call each other: * * 1. printGenerically(), which is defined as an inner function here. * It basically takes care of node caching. * 2. callPluginPrintFunction(), which checks for some options, and * ultimately calls the print() function provided by the plugin. * * The plugin function will call printGenerically() again for child nodes * of the current node, which will do its housekeeping, then call the * plugin function again, and so on. * * All the while, these functions pass a "path" variable around, which * is a stack-like data structure (FastPath) that maintains the current * state of the recursion. It is called "path", because it represents * the path to the current node through the Abstract Syntax Tree. */ function printAstToDoc(ast, options, alignmentSize = 0) { const { printer } = options; if (printer.preprocess) { ast = printer.preprocess(ast, options); } const cache = new Map(); function printGenerically(path, args) { const node = path.getValue(); const shouldCache = node && typeof node === "object" && args === undefined; if (shouldCache && cache.has(node)) { return cache.get(node); } // We let JSXElement print its comments itself because it adds () around // UnionTypeAnnotation has to align the child without the comments let res; if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) { res = callPluginPrintFunction(path, options, printGenerically, args); } else { // printComments will call the plugin print function and check for // comments to print res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi); } if (shouldCache) { cache.set(node, res); } return res; } let doc = printGenerically(new fastPath(ast)); if (alignmentSize > 0) { // Add a hardline to make the indents take effect // It should be removed in index.js format() doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth); } docUtils$1.propagateBreaks(doc); return doc; } function callPluginPrintFunction(path, options, printPath, args) { assert.ok(path instanceof fastPath); const node = path.getValue(); const { printer } = options; // Escape hatch if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) { return options.originalText.slice(options.locStart(node), options.locEnd(node)); } if (node) { try { // Potentially switch to a different parser const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc); if (sub) { return sub; } } catch (error) { /* istanbul ignore if */ if (commonjsGlobal.PRETTIER_DEBUG) { throw error; } // Continue with current parser } } return printer.print(path, options, printPath, args); } var astToDoc = printAstToDoc; function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, endNode: resultEndNode }; } for (const endParent of endNodeAndParents.parentNodes) { if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) { resultEndNode = endParent; } else { break; } } for (const startParent of startNodeAndParents.parentNodes) { if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) { resultStartNode = startParent; } else { break; } } return { startNode: resultStartNode, endNode: resultEndNode }; } function findNodeAtOffset(node, offset, options, predicate, parentNodes) { predicate = predicate || (() => true); parentNodes = parentNodes || []; const start = options.locStart(node, options.locStart); const end = options.locEnd(node, options.locEnd); if (start <= offset && offset <= end) { for (const childNode of comments.getSortedChildNodes(node, options)) { const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes)); if (childResult) { return childResult; } } if (predicate(node)) { return { node, parentNodes }; } } } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 function isSourceElement(opts, node) { if (node == null) { return false; } // JS and JS like to avoid repetitions const jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 "ImportDeclaration", // Module "ExportDefaultDeclaration", // Module "ExportNamedDeclaration", // Module "ExportAllDeclaration", // Module "TypeAlias", // Flow "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript "ExportDeclaration" // TypeScript ]; const jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]; const graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]; switch (opts.parser) { case "flow": case "babel": case "babel-flow": case "babel-ts": case "typescript": return jsSourceElements.includes(node.type); case "json": return jsonSourceElements.includes(node.type); case "graphql": return graphqlSourceElements.includes(node.kind); case "vue": return node.tag !== "root"; } return false; } function calculateRange(text, opts, ast) { // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart); let endNonWhitespace; for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) { if (text[endNonWhitespace - 1].match(/\S/)) { break; } } const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node)); const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node)); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, rangeEnd: 0 }; } const siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts); const { startNode, endNode } = siblingAncestors; const rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart)); const rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd)); return { rangeStart, rangeEnd }; } var rangeUtil = { calculateRange, findNodeAtOffset }; var diff = getCjsExportFromNamespace(index_es6); const normalizeOptions$1 = options$1.normalize; const { guessEndOfLine: guessEndOfLine$1, convertEndOfLineToChars: convertEndOfLineToChars$2 } = endOfLine; const { printer: { printDocToString: printDocToString$1 }, debug: { printDocToDebug } } = document; const BOM = "\uFEFF"; const CURSOR = Symbol("cursor"); const PLACEHOLDERS = { cursorOffset: "<<>>", rangeStart: "<<>>", rangeEnd: "<<>>" }; function ensureAllCommentsPrinted(astComments) { if (!astComments) { return; } for (let i = 0; i < astComments.length; ++i) { if (util$1.isNodeIgnoreComment(astComments[i])) { // If there's a prettier-ignore, we're not printing that sub-tree so we // don't know if the comments was printed or not. return; } } astComments.forEach(comment => { if (!comment.printed) { throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!'); } delete comment.printed; }); } function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; comments.attach(astComments, ast, text, opts); } ast.tokens = []; opts.originalText = opts.parser === "yaml" ? text : text.trimEnd(); return astComments; } function coreFormat(text, opts, addAlignmentSize) { if (!text || !text.trim().length) { return { formatted: "", cursorOffset: 0 }; } addAlignmentSize = addAlignmentSize || 0; const parsed = parser.parse(text, opts); const { ast } = parsed; text = parsed.text; if (opts.cursorOffset >= 0) { const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); if (nodeResult && nodeResult.node) { opts.cursorNode = nodeResult.node; } } const astComments = attachComments(text, ast, opts); const doc = astToDoc(ast, opts, addAlignmentSize); const result = printDocToString$1(doc, opts); ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { const trimmed = result.formatted.trim(); if (result.cursorNodeStart !== undefined) { result.cursorNodeStart -= result.formatted.indexOf(trimmed); } result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine); } if (opts.cursorOffset >= 0) { let oldCursorNodeStart; let oldCursorNodeText; let cursorOffsetRelativeToOldCursorNode; let newCursorNodeStart; let newCursorNodeText; if (opts.cursorNode && result.cursorNodeText) { oldCursorNodeStart = opts.locStart(opts.cursorNode); oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode)); cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart; newCursorNodeStart = result.cursorNodeStart; newCursorNodeText = result.cursorNodeText; } else { oldCursorNodeStart = 0; oldCursorNodeText = text; cursorOffsetRelativeToOldCursorNode = opts.cursorOffset; newCursorNodeStart = 0; newCursorNodeText = result.formatted; } if (oldCursorNodeText === newCursorNodeText) { return { formatted: result.formatted, cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode }; } // diff old and new cursor node texts, with a special cursor // symbol inserted to find out where it moves to const oldCursorNodeCharArray = oldCursorNodeText.split(""); oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR); const newCursorNodeCharArray = newCursorNodeText.split(""); const cursorNodeDiff = diff.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray); let cursorOffset = newCursorNodeStart; for (const entry of cursorNodeDiff) { if (entry.removed) { if (entry.value.includes(CURSOR)) { break; } } else { cursorOffset += entry.count; } } return { formatted: result.formatted, cursorOffset }; } return { formatted: result.formatted }; } function formatRange(text, opts) { const parsed = parser.parse(text, opts); const { ast } = parsed; text = parsed.text; const range = rangeUtil.calculateRange(text, opts, ast); const { rangeStart, rangeEnd } = range; const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. // This is so we can detect indentation correctly and restore it. // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1); const indentString = text.slice(rangeStart2, rangeStart); const alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth); const rangeResult = coreFormat(rangeString, Object.assign({}, opts, { rangeStart: 0, rangeEnd: Infinity, // track the cursor offset only if it's within our range cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1 }), alignmentSize); // Since the range contracts to avoid trailing whitespace, // we need to remove the newline that was inserted by the `format` call. const rangeTrimmed = rangeResult.formatted.trimEnd(); const rangeLeft = text.slice(0, rangeStart); const rangeRight = text.slice(rangeEnd); let { cursorOffset } = opts; if (opts.cursorOffset >= rangeEnd) { // handle the case where the cursor was past the end of the range cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length); } else if (rangeResult.cursorOffset !== undefined) { // handle the case where the cursor was in the range cursorOffset = rangeResult.cursorOffset + rangeStart; } // keep the cursor as it was if it was before the start of the range let formatted; if (opts.endOfLine === "lf") { formatted = rangeLeft + rangeTrimmed + rangeRight; } else { const eol = convertEndOfLineToChars$2(opts.endOfLine); if (cursorOffset >= 0) { const parts = [rangeLeft, rangeTrimmed, rangeRight]; let partIndex = 0; let partOffset = cursorOffset; while (partIndex < parts.length) { const part = parts[partIndex]; if (partOffset < part.length) { parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset); break; } partIndex++; partOffset -= part.length; } const [newRangeLeft, newRangeTrimmed, newRangeRight] = parts; formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, (_, index) => { cursorOffset = index; return ""; }); } else { formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol); } } return { formatted, cursorOffset }; } function format(text, opts) { const selectedParser = parser.resolveParser(opts); const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text); if (opts.requirePragma && !hasPragma) { return { formatted: text }; } if (opts.endOfLine === "auto") { opts.endOfLine = guessEndOfLine$1(text); } const hasCursor = opts.cursorOffset >= 0; const hasRangeStart = opts.rangeStart > 0; const hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing if (text.includes("\r")) { const offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort((aKey, bKey) => opts[aKey] - opts[bKey]); for (let i = offsetKeys.length - 1; i >= 0; i--) { const key = offsetKeys[i]; text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]); } text = text.replace(/\r\n?/g, "\n"); for (let i = 0; i < offsetKeys.length; i++) { const key = offsetKeys[i]; text = text.replace(PLACEHOLDERS[key], (_, index) => { opts[key] = index; return ""; }); } } const hasUnicodeBOM = text.charAt(0) === BOM; if (hasUnicodeBOM) { text = text.slice(1); if (hasCursor) { opts.cursorOffset++; } if (hasRangeStart) { opts.rangeStart++; } if (hasRangeEnd) { opts.rangeEnd++; } } if (!hasCursor) { opts.cursorOffset = -1; } if (opts.rangeStart < 0) { opts.rangeStart = 0; } if (opts.rangeEnd > text.length) { opts.rangeEnd = text.length; } const result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts); if (hasUnicodeBOM) { result.formatted = BOM + result.formatted; if (hasCursor) { result.cursorOffset++; } } return result; } var core = { formatWithCursor(text, opts) { opts = normalizeOptions$1(opts); return format(text, opts); }, parse(text, opts, massage) { opts = normalizeOptions$1(opts); if (text.includes("\r")) { text = text.replace(/\r\n?/g, "\n"); } const parsed = parser.parse(text, opts); if (massage) { parsed.ast = massageAst(parsed.ast, opts); } return parsed; }, formatAST(ast, opts) { opts = normalizeOptions$1(opts); const doc = astToDoc(ast, opts); return printDocToString$1(doc, opts); }, // Doesn't handle shebang for now formatDoc(doc, opts) { const debug = printDocToDebug(doc); opts = normalizeOptions$1(Object.assign({}, opts, { parser: "babel" })); return format(debug, opts).formatted; }, printToDoc(text, opts) { opts = normalizeOptions$1(opts); const parsed = parser.parse(text, opts); const { ast } = parsed; text = parsed.text; attachComments(text, ast, opts); return astToDoc(ast, opts); }, printDocToString(doc, opts) { return printDocToString$1(doc, normalizeOptions$1(opts)); } }; function clean(ast, newObj, parent) { ["raw", // front-matter "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => { delete newObj[name]; }); if (ast.type === "yaml") { delete newObj.value; } // --insert-pragma if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) { /** * something * * @format */ delete newObj.text; // standalone pragma if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { return null; } } if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { delete newObj.value; } if (ast.type === "css-rule") { delete newObj.params; } if (ast.type === "selector-combinator") { newObj.value = newObj.value.replace(/\s+/g, " "); } if (ast.type === "media-feature") { newObj.value = newObj.value.replace(/ /g, ""); } if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { newObj.value = newObj.value.toLowerCase(); } if (ast.type === "css-decl") { newObj.prop = newObj.prop.toLowerCase(); } if (ast.type === "css-atrule" || ast.type === "css-import") { newObj.name = newObj.name.toLowerCase(); } if (ast.type === "value-number") { newObj.unit = newObj.unit.toLowerCase(); } if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { newObj.value = cleanCSSStrings(newObj.value); } if (ast.type === "selector-attribute") { newObj.attribute = newObj.attribute.trim(); if (newObj.namespace) { if (typeof newObj.namespace === "string") { newObj.namespace = newObj.namespace.trim(); if (newObj.namespace.length === 0) { newObj.namespace = true; } } } if (newObj.value) { newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, ""); delete newObj.quoted; } } if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, (match, numStr, unit) => { const num = Number(numStr); return isNaN(num) ? match : num + unit.toLowerCase(); }); } if (ast.type === "selector-tag") { const lowercasedValue = ast.value.toLowerCase(); if (["from", "to"].includes(lowercasedValue)) { newObj.value = lowercasedValue; } } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { delete newObj.value; } // Workaround for SCSS nested properties if (ast.type === "selector-unknown") { delete newObj.value; } } function cleanCSSStrings(value) { return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1"); } var clean_1 = clean; const { builders: { hardline: hardline$3, literalline: literalline$1, concat: concat$4, markAsRoot: markAsRoot$1 }, utils: { mapDoc: mapDoc$1 } } = document; function embed(path, print, textToDoc /*, options */ ) { const node = path.getValue(); if (node.type === "yaml") { return markAsRoot$1(concat$4(["---", hardline$3, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { parser: "yaml" })) : "", "---", hardline$3])); } return null; function replaceNewlinesWithLiterallines(doc) { return mapDoc$1(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$4(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc); } } var embed_1 = embed; const detectNewline = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } const newlines = string.match(/(?:\r?\n)/g) || []; if (newlines.length === 0) { return; } const crlf = newlines.filter(newline => newline === '\r\n').length; const lf = newlines.length - crlf; return crlf > lf ? '\r\n' : '\n'; }; var detectNewline_1 = detectNewline; var graceful = string => typeof string === 'string' && detectNewline(string) || '\n'; detectNewline_1.graceful = graceful; var build = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); exports.extract = extract; exports.strip = strip; exports.parse = parse; exports.parseWithComments = parseWithComments; exports.print = print; function _os() { const data = require$$0$1; _os = function _os() { return data; }; return data; } function _detectNewline() { const data = _interopRequireDefault(detectNewline_1); _detectNewline = function _detectNewline() { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const commentEndRe = /\*\/$/; const commentStartRe = /^\/\*\*/; const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; const ltrimNewlineRe = /^(\r?\n)+/; const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; const stringStartRe = /(\r?\n|^) *\* ?/g; function extract(contents) { const match = contents.match(docblockRe); return match ? match[0].trimLeft() : ''; } function strip(contents) { const match = contents.match(docblockRe); return match && match[0] ? contents.substring(match[0].length) : contents; } function parse(docblock) { return parseWithComments(docblock).pragmas; } function parseWithComments(docblock) { const line = (0, _detectNewline().default)(docblock) || _os().EOL; docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives let prev = ''; while (prev !== docblock) { prev = docblock; docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line)); } docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); const result = Object.create(null); const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight(); let match; while (match = propertyRe.exec(docblock)) { // strip linecomments from pragmas const nextPragma = match[2].replace(lineCommentRe, ''); if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) { result[match[1]] = [].concat(result[match[1]], nextPragma); } else { result[match[1]] = nextPragma; } } return { comments, pragmas: result }; } function print({ comments = '', pragmas = {} }) { const line = (0, _detectNewline().default)(comments) || _os().EOL; const head = '/**'; const start = ' *'; const tail = ' */'; const keys = Object.keys(pragmas); const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join(''); if (!comments) { if (keys.length === 0) { return ''; } if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { const value = pragmas[keys[0]]; return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail); } } const printedComments = comments.split(line).map(textLine => "".concat(start, " ").concat(textLine)).join(line) + line; return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail; } function printKeyValues(key, valueOrArray) { return [].concat(valueOrArray).map(value => "@".concat(key, " ").concat(value).trim()); } }); unwrapExports(build); var build_1 = build.extract; var build_2 = build.strip; var build_3 = build.parse; var build_4 = build.parseWithComments; var build_5 = build.print; function hasPragma(text) { const pragmas = Object.keys(build.parse(build.extract(text))); return pragmas.includes("prettier") || pragmas.includes("format"); } function insertPragma(text) { const parsedDocblock = build.parseWithComments(build.extract(text)); const pragmas = Object.assign({ format: "" }, parsedDocblock.pragmas); const newDocblock = build.print({ pragmas, comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock) const strippedText = build.strip(text); const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; return newDocblock + separatingNewlines + strippedText; } var pragma = { hasPragma, insertPragma }; const DELIMITER_MAP = { "---": "yaml", "+++": "toml" }; function parse$1(text) { const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp$2).join("|"); const match = text.match( // trailing spaces after delimiters are allowed new RegExp("^(".concat(delimiterRegex, ")[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)"))); if (match === null) { return { frontMatter: null, content: text }; } const [raw, delimiter, value] = match; return { frontMatter: { type: DELIMITER_MAP[delimiter], value, raw: raw.replace(/\n$/, "") }, content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length) }; } var frontMatter = parse$1; function hasPragma$1(text) { return pragma.hasPragma(frontMatter(text).content); } function insertPragma$1(text) { const { frontMatter: frontMatter$1, content } = frontMatter(text); return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content); } var pragma$1 = { hasPragma: hasPragma$1, insertPragma: insertPragma$1 }; var lineColumnToIndex = function lineColumnToIndex(lineColumn, text) { let index = 0; for (let i = 0; i < lineColumn.line - 1; ++i) { index = text.indexOf("\n", index) + 1; if (index === -1) { return -1; } } return index + lineColumn.column; }; const { getLast: getLast$1, skipEverythingButNewLine: skipEverythingButNewLine$2 } = util$1; function calculateLocStart(node, text) { if (node.source) { return lineColumnToIndex(node.source.start, text) - 1; } return null; } function calculateLocEnd(node, text) { if (node.type === "css-comment" && node.inline) { return skipEverythingButNewLine$2(text, node.source.startOffset); } const endNode = node.nodes && getLast$1(node.nodes); if (endNode && node.source && !node.source.end) { node = endNode; } if (node.source && node.source.end) { return lineColumnToIndex(node.source.end, text); } return null; } function calculateLoc(node, text) { if (node && typeof node === "object") { if (node.source) { node.source.startOffset = calculateLocStart(node, text); node.source.endOffset = calculateLocEnd(node, text); } for (const key in node) { calculateLoc(node[key], text); } } } /** * Workaround for a bug: quotes in inline comments corrupt loc data of subsequent nodes. * This function replaces the quotes with U+FFFE and U+FFFF. Later, when the comments are printed, * their content is extracted from the original text or restored by replacing the placeholder * characters back with quotes. * - https://github.com/prettier/prettier/issues/7780 * - https://github.com/shellscape/postcss-less/issues/145 * - About noncharacters (U+FFFE and U+FFFF): http://www.unicode.org/faq/private_use.html#nonchar1 * @param text {string} */ function replaceQuotesInInlineComments(text) { /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */ /** @type {State} */ let state = "initial"; /** @type {State} */ let stateToReturnFromQuotes = "initial"; let inlineCommentStartIndex; let inlineCommentContainsQuotes = false; const inlineCommentsToReplace = []; for (let i = 0; i < text.length; i++) { const c = text[i]; switch (state) { case "initial": if (c === "'") { state = "single-quotes"; continue; } if (c === '"') { state = "double-quotes"; continue; } if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") { state = "url"; i += 3; continue; } if (c === "*" && text[i - 1] === "/") { state = "comment-block"; continue; } if (c === "/" && text[i - 1] === "/") { state = "comment-inline"; inlineCommentStartIndex = i - 1; continue; } continue; case "single-quotes": if (c === "'" && text[i - 1] !== "\\") { state = stateToReturnFromQuotes; stateToReturnFromQuotes = "initial"; } if (c === "\n" || c === "\r") { return text; // invalid input } continue; case "double-quotes": if (c === '"' && text[i - 1] !== "\\") { state = stateToReturnFromQuotes; stateToReturnFromQuotes = "initial"; } if (c === "\n" || c === "\r") { return text; // invalid input } continue; case "url": if (c === ")") { state = "initial"; } if (c === "\n" || c === "\r") { return text; // invalid input } if (c === "'") { state = "single-quotes"; stateToReturnFromQuotes = "url"; continue; } if (c === '"') { state = "double-quotes"; stateToReturnFromQuotes = "url"; continue; } continue; case "comment-block": if (c === "/" && text[i - 1] === "*") { state = "initial"; } continue; case "comment-inline": if (c === '"' || c === "'") { inlineCommentContainsQuotes = true; } if (c === "\n" || c === "\r") { if (inlineCommentContainsQuotes) { inlineCommentsToReplace.push([inlineCommentStartIndex, i]); } state = "initial"; inlineCommentContainsQuotes = false; } continue; } } for (const [start, end] of inlineCommentsToReplace) { text = text.slice(0, start) + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end); } return text; } function restoreQuotesInInlineComments(text) { return text.replace(/\ufffe/g, "'").replace(/\uffff/g, '"'); } var loc$1 = { calculateLoc, replaceQuotesInInlineComments, restoreQuotesInInlineComments }; const colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]; function getAncestorCounter(path, typeOrTypes) { const types = [].concat(typeOrTypes); let counter = -1; let ancestorNode; while (ancestorNode = path.getParentNode(++counter)) { if (types.includes(ancestorNode.type)) { return counter; } } return -1; } function getAncestorNode(path, typeOrTypes) { const counter = getAncestorCounter(path, typeOrTypes); return counter === -1 ? null : path.getParentNode(counter); } function getPropOfDeclNode(path) { const declAncestorNode = getAncestorNode(path, "css-decl"); return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); } function isSCSS(parser, text) { const hasExplicitParserChoice = parser === "less" || parser === "scss"; const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^}:]+|#){|@import[^\n]+(?:url|,)/; return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); } function isWideKeywords(value) { return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase()); } function isKeyframeAtRuleKeywords(path, value) { const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase()); } function maybeToLowerCase(value) { return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); } function insideValueFunctionNode(path, functionName) { const funcAncestorNode = getAncestorNode(path, "value-func"); return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; } function insideICSSRuleNode(path) { const ruleAncestorNode = getAncestorNode(path, "css-rule"); return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); } function insideAtRuleNode(path, atRuleNameOrAtRuleNames) { const atRuleNames = [].concat(atRuleNameOrAtRuleNames); const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase()); } function insideURLFunctionInImportAtRuleNode(path) { const node = path.getValue(); const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; } function isURLFunctionNode(node) { return node.type === "value-func" && node.value.toLowerCase() === "url"; } function isLastNode(path, node) { const parentNode = path.getParentNode(); if (!parentNode) { return false; } const { nodes } = parentNode; return nodes && nodes.indexOf(node) === nodes.length - 1; } function isDetachedRulesetDeclarationNode(node) { // If a Less file ends up being parsed with the SCSS parser, Less // variable declarations will be parsed as atrules with names ending // with a colon, so keep the original case then. if (!node.selector) { return false; } return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); } function isForKeywordNode(node) { return node.type === "value-word" && ["from", "through", "end"].includes(node.value); } function isIfElseKeywordNode(node) { return node.type === "value-word" && ["and", "or", "not"].includes(node.value); } function isEachKeywordNode(node) { return node.type === "value-word" && node.value === "in"; } function isMultiplicationNode(node) { return node.type === "value-operator" && node.value === "*"; } function isDivisionNode(node) { return node.type === "value-operator" && node.value === "/"; } function isAdditionNode(node) { return node.type === "value-operator" && node.value === "+"; } function isSubtractionNode(node) { return node.type === "value-operator" && node.value === "-"; } function isModuloNode(node) { return node.type === "value-operator" && node.value === "%"; } function isMathOperatorNode(node) { return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node); } function isEqualityOperatorNode(node) { return node.type === "value-word" && ["==", "!="].includes(node.value); } function isRelationalOperatorNode(node) { return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value); } function isSCSSControlDirectiveNode(node) { return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name); } function isSCSSNestedPropertyNode(node) { if (!node.selector) { return false; } return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); } function isDetachedRulesetCallNode(node) { return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); } function isTemplatePlaceholderNode(node) { return node.name.startsWith("prettier-placeholder"); } function isTemplatePropNode(node) { return node.prop.startsWith("@prettier-placeholder"); } function isPostcssSimpleVarNode(currentNode, nextNode) { return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; } function hasComposesNode(node) { return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; } function hasParensAroundNode(node) { return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; } function hasEmptyRawBefore(node) { return node.raws && node.raws.before === ""; } function isKeyValuePairNode(node) { return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; } function isKeyValuePairInParenGroupNode(node) { return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]); } function isSCSSMapItemNode(path) { const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) if (node.groups.length === 0) { return false; } const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { return false; } const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) if (declNode && declNode.prop && declNode.prop.startsWith("$")) { return true; } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) if (isKeyValuePairInParenGroupNode(parentParentNode)) { return true; } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) if (parentParentNode.type === "value-func") { return true; } return false; } function isInlineValueCommentNode(node) { return node.type === "value-comment" && node.inline; } function isHashNode(node) { return node.type === "value-word" && node.value === "#"; } function isLeftCurlyBraceNode(node) { return node.type === "value-word" && node.value === "{"; } function isRightCurlyBraceNode(node) { return node.type === "value-word" && node.value === "}"; } function isWordNode(node) { return ["value-word", "value-atword"].includes(node.type); } function isColonNode(node) { return node.type === "value-colon"; } function isMediaAndSupportsKeywords(node) { return node.value && ["not", "and", "or"].includes(node.value.toLowerCase()); } function isColorAdjusterFuncNode(node) { if (node.type !== "value-func") { return false; } return colorAdjusterFunctions.includes(node.value.toLowerCase()); } // TODO: only check `less` when we don't use `less` to parse `css` function isLessParser(options) { return options.parser === "css" || options.parser === "less"; } function lastLineHasInlineComment(text) { return /\/\//.test(text.split(/[\r\n]/).pop()); } var utils$2 = { getAncestorCounter, getAncestorNode, getPropOfDeclNode, maybeToLowerCase, insideValueFunctionNode, insideICSSRuleNode, insideAtRuleNode, insideURLFunctionInImportAtRuleNode, isKeyframeAtRuleKeywords, isWideKeywords, isSCSS, isLastNode, isLessParser, isSCSSControlDirectiveNode, isDetachedRulesetDeclarationNode, isRelationalOperatorNode, isEqualityOperatorNode, isMultiplicationNode, isDivisionNode, isAdditionNode, isSubtractionNode, isModuloNode, isMathOperatorNode, isEachKeywordNode, isForKeywordNode, isURLFunctionNode, isIfElseKeywordNode, hasComposesNode, hasParensAroundNode, hasEmptyRawBefore, isSCSSNestedPropertyNode, isDetachedRulesetCallNode, isTemplatePlaceholderNode, isTemplatePropNode, isPostcssSimpleVarNode, isKeyValuePairNode, isKeyValuePairInParenGroupNode, isSCSSMapItemNode, isInlineValueCommentNode, isHashNode, isLeftCurlyBraceNode, isRightCurlyBraceNode, isWordNode, isColonNode, isMediaAndSupportsKeywords, isColorAdjusterFuncNode, lastLineHasInlineComment }; const { insertPragma: insertPragma$2 } = pragma$1; const { printNumber: printNumber$1, printString: printString$1, hasIgnoreComment: hasIgnoreComment$1, hasNewline: hasNewline$3 } = util$1; const { isNextLineEmpty: isNextLineEmpty$2 } = utilShared; const { restoreQuotesInInlineComments: restoreQuotesInInlineComments$1 } = loc$1; const { builders: { concat: concat$5, join: join$2, line: line$2, hardline: hardline$4, softline: softline$1, group: group$1, fill: fill$2, indent: indent$2, dedent: dedent$1, ifBreak: ifBreak$1 }, utils: { removeLines: removeLines$1 } } = document; const { getAncestorNode: getAncestorNode$1, getPropOfDeclNode: getPropOfDeclNode$1, maybeToLowerCase: maybeToLowerCase$1, insideValueFunctionNode: insideValueFunctionNode$1, insideICSSRuleNode: insideICSSRuleNode$1, insideAtRuleNode: insideAtRuleNode$1, insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, isWideKeywords: isWideKeywords$1, isSCSS: isSCSS$1, isLastNode: isLastNode$1, isLessParser: isLessParser$1, isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, isRelationalOperatorNode: isRelationalOperatorNode$1, isEqualityOperatorNode: isEqualityOperatorNode$1, isMultiplicationNode: isMultiplicationNode$1, isDivisionNode: isDivisionNode$1, isAdditionNode: isAdditionNode$1, isSubtractionNode: isSubtractionNode$1, isMathOperatorNode: isMathOperatorNode$1, isEachKeywordNode: isEachKeywordNode$1, isForKeywordNode: isForKeywordNode$1, isURLFunctionNode: isURLFunctionNode$1, isIfElseKeywordNode: isIfElseKeywordNode$1, hasComposesNode: hasComposesNode$1, hasParensAroundNode: hasParensAroundNode$1, hasEmptyRawBefore: hasEmptyRawBefore$1, isKeyValuePairNode: isKeyValuePairNode$1, isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, isTemplatePlaceholderNode: isTemplatePlaceholderNode$1, isTemplatePropNode: isTemplatePropNode$1, isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, isSCSSMapItemNode: isSCSSMapItemNode$1, isInlineValueCommentNode: isInlineValueCommentNode$1, isHashNode: isHashNode$1, isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, isRightCurlyBraceNode: isRightCurlyBraceNode$1, isWordNode: isWordNode$1, isColonNode: isColonNode$1, isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, isColorAdjusterFuncNode: isColorAdjusterFuncNode$1, lastLineHasInlineComment: lastLineHasInlineComment$1 } = utils$2; function shouldPrintComma(options) { switch (options.trailingComma) { case "all": case "es5": return true; case "none": default: return false; } } function genericPrint(path, options, print) { const node = path.getValue(); /* istanbul ignore if */ if (!node) { return ""; } if (typeof node === "string") { return node; } switch (node.type) { case "yaml": case "toml": return concat$5([node.raw, hardline$4]); case "css-root": { const nodes = printNodeSequence(path, options, print); if (nodes.parts.length) { return concat$5([nodes, options.__isHTMLStyleAttribute ? "" : hardline$4]); } return nodes; } case "css-comment": { const isInlineComment = node.inline || node.raws.inline; const text = options.originalText.slice(options.locStart(node), options.locEnd(node)); return isInlineComment ? text.trimEnd() : text; } case "css-rule": { return concat$5([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$5([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$2 : " ", "{", node.nodes.length > 0 ? indent$2(concat$5([hardline$4, printNodeSequence(path, options, print)])) : "", hardline$4, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]); } case "css-decl": { const parentNode = path.getParentNode(); return concat$5([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode$1(node) ? removeLines$1(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$5([" {", indent$2(concat$5([softline$1, printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]); } case "css-atrule": { const parentNode = path.getParentNode(); const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";"; if (isLessParser$1(options)) { if (node.mixin) { return concat$5([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } if (node.function) { return concat$5([node.name, concat$5([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } if (node.variable) { return concat$5(["@", node.name, ": ", node.value ? concat$5([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$5(["{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } } return concat$5(["@", // If a Less file ends up being parsed with the SCSS parser, Less // variable declarations will be parsed as at-rules with names ending // with a colon, so keep the original case then. isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$5([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$5([hardline$4, hardline$4]) : /^\s*\n/.test(node.raws.afterName) ? hardline$4 : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$2(concat$5([" ", path.call(print, "selector")])) : "", node.value ? group$1(concat$5([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$2 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$5([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } // postcss-media-query-parser case "media-query-list": { const parts = []; path.each(childPath => { const node = childPath.getValue(); if (node.type === "media-query" && node.value === "") { return; } parts.push(childPath.call(print)); }, "nodes"); return group$1(indent$2(join$2(line$2, parts))); } case "media-query": { return concat$5([join$2(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]); } case "media-type": { return adjustNumbers(adjustStrings(node.value, options)); } case "media-feature-expression": { if (!node.nodes) { return node.value; } return concat$5(["(", concat$5(path.map(print, "nodes")), ")"]); } case "media-feature": { return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options)); } case "media-colon": { return concat$5([node.value, " "]); } case "media-value": { return adjustNumbers(adjustStrings(node.value, options)); } case "media-keyword": { return adjustStrings(node.value, options); } case "media-url": { return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options); } case "media-unknown": { return node.value; } // postcss-selector-parser case "selector-root": { return group$1(concat$5([insideAtRuleNode$1(path, "custom-selector") ? concat$5([getAncestorNode$1(path, "css-atrule").customSelector, line$2]) : "", join$2(concat$5([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$2 : hardline$4]), path.map(print, "nodes"))])); } case "selector-selector": { return group$1(indent$2(concat$5(path.map(print, "nodes")))); } case "selector-comment": { return node.value; } case "selector-string": { return adjustStrings(node.value, options); } case "selector-tag": { const parentNode = path.getParentNode(); const index = parentNode && parentNode.nodes.indexOf(node); const prevNode = index && parentNode.nodes[index - 1]; return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]); } case "selector-id": { return concat$5(["#", node.value]); } case "selector-class": { return concat$5([".", adjustNumbers(adjustStrings(node.value, options))]); } case "selector-attribute": { return concat$5(["[", node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]); } case "selector-combinator": { if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { const parentNode = path.getParentNode(); const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$2; return concat$5([leading, node.value, isLastNode$1(path, node) ? "" : " "]); } const leading = node.value.trim().startsWith("(") ? line$2 : ""; const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$2; return concat$5([leading, value]); } case "selector-universal": { return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]); } case "selector-pseudo": { return concat$5([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$5(["(", join$2(", ", path.map(print, "nodes")), ")"]) : ""]); } case "selector-nesting": { return node.value; } case "selector-unknown": { const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options)); } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js const parentNode = path.getParentNode(); if (parentNode.raws && parentNode.raws.selector) { const start = options.locStart(parentNode); const end = start + parentNode.raws.selector.length; return options.originalText.slice(start, end).trim(); } return node.value; } // postcss-values-parser case "value-value": case "value-root": { return path.call(print, "group"); } case "value-comment": { return concat$5([node.inline ? "//" : "/*", // see replaceQuotesInInlineComments in loc.js // value-* nodes don't have correct location data, so we have to rely on placeholder characters. restoreQuotesInInlineComments$1(node.value), node.inline ? "" : "*/"]); } case "value-comma_group": { const parentNode = path.getParentNode(); const parentParentNode = path.getParentNode(1); const declAncestorProp = getPropOfDeclNode$1(path); const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode); const printed = path.map(print, "groups"); const parts = []; const insideURLFunction = insideValueFunctionNode$1(path, "url"); let insideSCSSInterpolationInString = false; let didBreak = false; for (let i = 0; i < node.groups.length; ++i) { parts.push(printed[i]); const iPrevNode = node.groups[i - 1]; const iNode = node.groups[i]; const iNextNode = node.groups[i + 1]; const iNextNextNode = node.groups[i + 2]; if (insideURLFunction) { if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) { parts.push(" "); } continue; } // Ignore after latest node (i.e. before semicolon) if (!iNextNode) { continue; } // styled.div` background: var(--${one}); ` if (!iPrevNode && iNode.value === "--" && iNextNode.type === "value-atword") { continue; } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) { insideSCSSInterpolationInString = !insideSCSSInterpolationInString; continue; } if (insideSCSSInterpolationInString) { continue; } // Ignore colon (i.e. `:`) if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) { continue; } // Ignore `@` in Less (i.e. `@@var;`) if (iNode.type === "value-atword" && iNode.value === "") { continue; } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) if (iNode.value === "~") { continue; } // Ignore escape `\` if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") { continue; } // Ignore escaped `/` if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") { continue; } // Ignore `\` (i.e. `$variable: \@small;`) if (iNode.value === "\\") { continue; } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) if (isPostcssSimpleVarNode$1(iNode, iNextNode)) { continue; } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) { continue; } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) if (iNode.value === "--" && isHashNode$1(iNextNode)) { continue; } // Formatting math operations const isMathOperator = isMathOperatorNode$1(iNode); const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) { continue; } // Print spaces before and after addition and subtraction math operators as is in `calc` function // due to the fact that it is not valid syntax // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) { continue; } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode); const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode); const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) { continue; } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) if (isInlineValueCommentNode$1(iNode)) { parts.push(hardline$4); continue; } // Handle keywords in SCSS control directive if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) { parts.push(" "); continue; } // At-rule `namespace` should be in one line if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { parts.push(" "); continue; } // Formatting `grid` property if (isGridValue) { if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) { parts.push(hardline$4); didBreak = true; } else { parts.push(" "); } continue; } // Add `space` before next math operation // Note: `grip` property have `/` delimiter and it is not math operation, so // `grid` property handles above if (isNextMathOperator) { parts.push(" "); continue; } // Be default all values go through `line` parts.push(line$2); } if (didBreak) { parts.unshift(hardline$4); } if (isControlDirective) { return group$1(indent$2(concat$5(parts))); } // Indent is not needed for import url when url is very long // and node has two groups // when type is value-comma_group // example @import url("verylongurl") projection,tv if (insideURLFunctionInImportAtRuleNode$1(path)) { return group$1(fill$2(parts)); } return group$1(indent$2(fill$2(parts))); } case "value-paren_group": { const parentNode = path.getParentNode(); if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { return concat$5([node.open ? path.call(print, "open") : "", join$2(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]); } if (!node.open) { const printed = path.map(print, "groups"); const res = []; for (let i = 0; i < printed.length; i++) { if (i !== 0) { res.push(concat$5([",", line$2])); } res.push(printed[i]); } return group$1(indent$2(fill$2(res))); } const isSCSSMapItem = isSCSSMapItemNode$1(path); const lastItem = node.groups[node.groups.length - 1]; const isLastItemComment = lastItem && lastItem.type === "value-comment"; return group$1(concat$5([node.open ? path.call(print, "open") : "", indent$2(concat$5([softline$1, join$2(concat$5([",", line$2]), path.map(childPath => { const node = childPath.getValue(); const printed = print(childPath); // Key/Value pair in open paren already indented if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") { printed.contents.contents.parts[1] = group$1(printed.contents.contents.parts[1]); return group$1(dedent$1(printed)); } return printed; }, "groups"))])), ifBreak$1(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$1, node.close ? path.call(print, "close") : ""]), { shouldBreak: isSCSSMapItem }); } case "value-func": { return concat$5([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]); } case "value-paren": { return node.value; } case "value-number": { return concat$5([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]); } case "value-operator": { return node.value; } case "value-word": { if (node.isColor && node.isHex || isWideKeywords$1(node.value)) { return node.value.toLowerCase(); } return node.value; } case "value-colon": { return concat$5([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) insideValueFunctionNode$1(path, "url") ? "" : line$2]); } case "value-comma": { return concat$5([node.value, " "]); } case "value-string": { return printString$1(node.raws.quote + node.value + node.raws.quote, options); } case "value-atword": { return concat$5(["@", node.value]); } case "value-unicode-range": { return node.value; } case "value-unknown": { return node.value; } default: /* istanbul ignore next */ throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type))); } } function printNodeSequence(path, options, print) { const node = path.getValue(); const parts = []; let i = 0; path.map(pathChild => { const prevNode = node.nodes[i - 1]; if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { const childNode = pathChild.getValue(); parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode))); } else { parts.push(pathChild.call(print)); } if (i !== node.nodes.length - 1) { if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), { backwards: true }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") { parts.push(" "); } else { parts.push(options.__isHTMLStyleAttribute ? line$2 : hardline$4); if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), options.locEnd) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") { parts.push(hardline$4); } } } i++; }, "nodes"); return concat$5(parts); } const STRING_REGEX$3 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g; const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g; const STANDARD_UNIT_REGEX = /[a-zA-Z]+/g; const WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g; const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g"); function adjustStrings(value, options) { return value.replace(STRING_REGEX$3, match => printString$1(match, options)); } function quoteAttributeValue(value, options) { const quote = options.singleQuote ? "'" : '"'; return value.includes('"') || value.includes("'") ? value : quote + value + quote; } function adjustNumbers(value) { return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match); } function printCssNumber(rawNumber) { return printNumber$1(rawNumber) // Remove trailing `.0`. .replace(/\.0(?=$|e)/, ""); } var printerPostcss = { print: genericPrint, embed: embed_1, insertPragma: insertPragma$2, hasPrettierIgnore: hasIgnoreComment$1, massageAstNode: clean_1 }; const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js var commonOptions = { bracketSpacing: { since: "0.0.0", category: CATEGORY_COMMON, type: "boolean", default: true, description: "Print spaces between brackets.", oppositeDescription: "Do not print spaces between brackets." }, singleQuote: { since: "0.0.0", category: CATEGORY_COMMON, type: "boolean", default: false, description: "Use single quotes instead of double quotes." }, proseWrap: { since: "1.8.2", category: CATEGORY_COMMON, type: "choice", default: [{ since: "1.8.2", value: true }, { since: "1.9.0", value: "preserve" }], description: "How to wrap prose.", choices: [{ since: "1.9.0", value: "always", description: "Wrap prose if it exceeds the print width." }, { since: "1.9.0", value: "never", description: "Do not wrap prose." }, { since: "1.9.0", value: "preserve", description: "Wrap prose as-is." }] } }; var options$2 = { singleQuote: commonOptions.singleQuote }; var createLanguage = function createLanguage(linguistData, override) { const { languageId } = linguistData, rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]); return Object.assign({ linguistLanguageId: languageId }, rest, {}, override(linguistData)); }; var name$1 = "CSS"; var type = "markup"; var tmScope = "source.css"; var aceMode = "css"; var codemirrorMode = "css"; var codemirrorMimeType = "text/css"; var color = "#563d7c"; var extensions = [ ".css" ]; var languageId = 50; var CSS = { name: name$1, type: type, tmScope: tmScope, aceMode: aceMode, codemirrorMode: codemirrorMode, codemirrorMimeType: codemirrorMimeType, color: color, extensions: extensions, languageId: languageId }; var CSS$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$1, type: type, tmScope: tmScope, aceMode: aceMode, codemirrorMode: codemirrorMode, codemirrorMimeType: codemirrorMimeType, color: color, extensions: extensions, languageId: languageId, 'default': CSS }); var name$2 = "PostCSS"; var type$1 = "markup"; var tmScope$1 = "source.postcss"; var group$2 = "CSS"; var extensions$1 = [ ".pcss", ".postcss" ]; var aceMode$1 = "text"; var languageId$1 = 262764437; var PostCSS = { name: name$2, type: type$1, tmScope: tmScope$1, group: group$2, extensions: extensions$1, aceMode: aceMode$1, languageId: languageId$1 }; var PostCSS$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$2, type: type$1, tmScope: tmScope$1, group: group$2, extensions: extensions$1, aceMode: aceMode$1, languageId: languageId$1, 'default': PostCSS }); var name$3 = "Less"; var type$2 = "markup"; var group$3 = "CSS"; var extensions$2 = [ ".less" ]; var tmScope$2 = "source.css.less"; var aceMode$2 = "less"; var codemirrorMode$1 = "css"; var codemirrorMimeType$1 = "text/css"; var languageId$2 = 198; var Less = { name: name$3, type: type$2, group: group$3, extensions: extensions$2, tmScope: tmScope$2, aceMode: aceMode$2, codemirrorMode: codemirrorMode$1, codemirrorMimeType: codemirrorMimeType$1, languageId: languageId$2 }; var Less$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$3, type: type$2, group: group$3, extensions: extensions$2, tmScope: tmScope$2, aceMode: aceMode$2, codemirrorMode: codemirrorMode$1, codemirrorMimeType: codemirrorMimeType$1, languageId: languageId$2, 'default': Less }); var name$4 = "SCSS"; var type$3 = "markup"; var tmScope$3 = "source.css.scss"; var group$4 = "CSS"; var aceMode$3 = "scss"; var codemirrorMode$2 = "css"; var codemirrorMimeType$2 = "text/x-scss"; var extensions$3 = [ ".scss" ]; var languageId$3 = 329; var SCSS = { name: name$4, type: type$3, tmScope: tmScope$3, group: group$4, aceMode: aceMode$3, codemirrorMode: codemirrorMode$2, codemirrorMimeType: codemirrorMimeType$2, extensions: extensions$3, languageId: languageId$3 }; var SCSS$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$4, type: type$3, tmScope: tmScope$3, group: group$4, aceMode: aceMode$3, codemirrorMode: codemirrorMode$2, codemirrorMimeType: codemirrorMimeType$2, extensions: extensions$3, languageId: languageId$3, 'default': SCSS }); var require$$0$2 = getCjsExportFromNamespace(CSS$1); var require$$1 = getCjsExportFromNamespace(PostCSS$1); var require$$2 = getCjsExportFromNamespace(Less$1); var require$$3 = getCjsExportFromNamespace(SCSS$1); const languages = [createLanguage(require$$0$2, () => ({ since: "1.4.0", parsers: ["css"], vscodeLanguageIds: ["css"] })), createLanguage(require$$1, () => ({ since: "1.4.0", parsers: ["css"], vscodeLanguageIds: ["postcss"] })), createLanguage(require$$2, () => ({ since: "1.4.0", parsers: ["less"], vscodeLanguageIds: ["less"] })), createLanguage(require$$3, () => ({ since: "1.4.0", parsers: ["scss"], vscodeLanguageIds: ["scss"] }))]; const printers = { postcss: printerPostcss }; var languageCss = { languages, options: options$2, printers }; function hasPragma$2(text) { return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text); } function insertPragma$3(text) { return "# @format\n\n" + text; } var pragma$2 = { hasPragma: hasPragma$2, insertPragma: insertPragma$3 }; const { concat: concat$6, join: join$3, hardline: hardline$5, line: line$3, softline: softline$2, group: group$5, indent: indent$3, ifBreak: ifBreak$2 } = document.builders; const { hasIgnoreComment: hasIgnoreComment$2 } = util$1; const { isNextLineEmpty: isNextLineEmpty$3 } = utilShared; const { insertPragma: insertPragma$4 } = pragma$2; function genericPrint$1(path, options, print) { const n = path.getValue(); if (!n) { return ""; } if (typeof n === "string") { return n; } switch (n.kind) { case "Document": { const parts = []; path.map((pathChild, index) => { parts.push(concat$6([pathChild.call(print)])); if (index !== n.definitions.length - 1) { parts.push(hardline$5); if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options.locEnd)) { parts.push(hardline$5); } } }, "definitions"); return concat$6([concat$6(parts), hardline$5]); } case "OperationDefinition": { const hasOperation = options.originalText[options.locStart(n)] !== "{"; const hasName = !!n.name; return concat$6([hasOperation ? n.operation : "", hasOperation && hasName ? concat$6([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]); } case "FragmentDefinition": { return concat$6(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); } case "SelectionSet": { return concat$6(["{", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$5, "}"]); } case "Field": { return group$5(concat$6([n.alias ? concat$6([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); } case "Name": { return n.value; } case "StringValue": { if (n.block) { return concat$6(['"""', hardline$5, join$3(hardline$5, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$5, '"""']); } return concat$6(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']); } case "IntValue": case "FloatValue": case "EnumValue": { return n.value; } case "BooleanValue": { return n.value ? "true" : "false"; } case "NullValue": { return "null"; } case "Variable": { return concat$6(["$", path.call(print, "name")]); } case "ListValue": { return group$5(concat$6(["[", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "values"))])), softline$2, "]"])); } case "ObjectValue": { return group$5(concat$6(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"])); } case "ObjectField": case "Argument": { return concat$6([path.call(print, "name"), ": ", path.call(print, "value")]); } case "Directive": { return concat$6(["@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : ""]); } case "NamedType": { return path.call(print, "name"); } case "VariableDefinition": { return concat$6([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); } case "TypeExtensionDefinition": { return concat$6(["extend ", path.call(print, "definition")]); } case "ObjectTypeExtension": case "ObjectTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$6([" implements ", concat$6(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); } case "FieldDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]); } case "DirectiveDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", n.repeatable ? " repeatable" : "", concat$6([" on ", join$3(" | ", path.map(print, "locations"))])]); } case "EnumTypeExtension": case "EnumTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$5, "}"]) : ""]); } case "EnumValueDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), printDirectives(path, print, n)]); } case "InputValueDefinition": { return concat$6([path.call(print, "description"), n.description ? n.description.block ? hardline$5 : line$3 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); } case "InputObjectTypeExtension": case "InputObjectTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); } case "SchemaDefinition": { return concat$6(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$5, "}"]); } case "OperationTypeDefinition": { return concat$6([path.call(print, "operation"), ": ", path.call(print, "type")]); } case "InterfaceTypeExtension": case "InterfaceTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); } case "FragmentSpread": { return concat$6(["...", path.call(print, "name"), printDirectives(path, print, n)]); } case "InlineFragment": { return concat$6(["...", n.typeCondition ? concat$6([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); } case "UnionTypeExtension": case "UnionTypeDefinition": { return group$5(concat$6([path.call(print, "description"), n.description ? hardline$5 : "", group$5(concat$6([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$6([" =", ifBreak$2("", " "), indent$3(concat$6([ifBreak$2(concat$6([line$3, " "])), join$3(concat$6([line$3, "| "]), path.map(print, "types"))]))]) : ""]))])); } case "ScalarTypeExtension": case "ScalarTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]); } case "NonNullType": { return concat$6([path.call(print, "type"), "!"]); } case "ListType": { return concat$6(["[", path.call(print, "type"), "]"]); } default: /* istanbul ignore next */ throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); } } function printDirectives(path, print, n) { if (n.directives.length === 0) { return ""; } return concat$6([" ", group$5(indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]); } function printSequence(sequencePath, options, print) { const count = sequencePath.getValue().length; return sequencePath.map((path, i) => { const printed = print(path); if (isNextLineEmpty$3(options.originalText, path.getValue(), options.locEnd) && i < count - 1) { return concat$6([printed, hardline$5]); } return printed; }); } function canAttachComment(node) { return node.kind && node.kind !== "Comment"; } function printComment$1(commentPath) { const comment = commentPath.getValue(); if (comment.kind === "Comment") { return "#" + comment.value.trimEnd(); } throw new Error("Not a comment: " + JSON.stringify(comment)); } function determineInterfaceSeparatorBetween(first, second, options) { const textBetween = options.originalText.slice(first.loc.end, second.loc.start).replace(/#.*/g, "").trim(); return textBetween === "," ? ", " : " & "; } function printInterfaces(path, options, print) { const node = path.getNode(); const parts = []; const { interfaces } = node; const printed = path.map(node => print(node), "interfaces"); for (let index = 0; index < interfaces.length; index++) { const interfaceNode = interfaces[index]; if (index > 0) { parts.push(determineInterfaceSeparatorBetween(interfaces[index - 1], interfaceNode, options)); } parts.push(printed[index]); } return parts; } function clean$1(node, newNode /*, parent*/ ) { delete newNode.loc; delete newNode.comments; } var printerGraphql = { print: genericPrint$1, massageAstNode: clean$1, hasPrettierIgnore: hasIgnoreComment$2, insertPragma: insertPragma$4, printComment: printComment$1, canAttachComment }; var options$3 = { bracketSpacing: commonOptions.bracketSpacing }; var name$5 = "GraphQL"; var type$4 = "data"; var extensions$4 = [ ".graphql", ".gql", ".graphqls" ]; var tmScope$4 = "source.graphql"; var aceMode$4 = "text"; var languageId$4 = 139; var GraphQL = { name: name$5, type: type$4, extensions: extensions$4, tmScope: tmScope$4, aceMode: aceMode$4, languageId: languageId$4 }; var GraphQL$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$5, type: type$4, extensions: extensions$4, tmScope: tmScope$4, aceMode: aceMode$4, languageId: languageId$4, 'default': GraphQL }); var require$$0$3 = getCjsExportFromNamespace(GraphQL$1); const languages$1 = [createLanguage(require$$0$3, () => ({ since: "1.5.0", parsers: ["graphql"], vscodeLanguageIds: ["graphql"] }))]; const printers$1 = { graphql: printerGraphql }; var languageGraphql = { languages: languages$1, options: options$3, printers: printers$1 }; var clean$2 = function clean(ast, newNode) { delete newNode.loc; delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace if (ast.type === "TextNode") { const trimmed = ast.chars.trim(); if (!trimmed) { return null; } newNode.chars = trimmed; } }; function isUppercase(string) { return string.toUpperCase() === string; } function isGlimmerComponent(node) { return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes(".")); } function isWhitespaceNode(node) { return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars); } function isNodeOfSomeType(node, types) { return node && types.some(type => node.type === type); } function isParentOfSomeType(path, types) { const parentNode = path.getParentNode(0); return isNodeOfSomeType(parentNode, types); } function isPreviousNodeOfSomeType(path, types) { const previousNode = getPreviousNode(path); return isNodeOfSomeType(previousNode, types); } function isNextNodeOfSomeType(path, types) { const nextNode = getNextNode(path); return isNodeOfSomeType(nextNode, types); } function getSiblingNode(path, offset) { const node = path.getValue(); const parentNode = path.getParentNode(0) || {}; const children = parentNode.children || parentNode.body || []; const index = children.indexOf(node); return index !== -1 && children[index + offset]; } function getPreviousNode(path, lookBack = 1) { return getSiblingNode(path, -lookBack); } function getNextNode(path) { return getSiblingNode(path, 1); } function isPrettierIgnoreNode(node) { return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore"; } function hasPrettierIgnore(path) { const node = path.getValue(); const previousPreviousNode = getPreviousNode(path, 2); return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode); } var utils$3 = { getNextNode, getPreviousNode, hasPrettierIgnore, isGlimmerComponent, isNextNodeOfSomeType, isNodeOfSomeType, isParentOfSomeType, isPreviousNodeOfSomeType, isWhitespaceNode }; const { concat: concat$7, join: join$4, softline: softline$3, hardline: hardline$6, line: line$4, group: group$6, indent: indent$4, ifBreak: ifBreak$3 } = document.builders; const { getNextNode: getNextNode$1, getPreviousNode: getPreviousNode$1, hasPrettierIgnore: hasPrettierIgnore$1, isGlimmerComponent: isGlimmerComponent$1, isNextNodeOfSomeType: isNextNodeOfSomeType$1, isParentOfSomeType: isParentOfSomeType$1, isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1, isWhitespaceNode: isWhitespaceNode$1 } = utils$3; // http://w3c.github.io/html/single-page.html#void-elements const voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter: // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts function print(path, options, print) { const n = path.getValue(); /* istanbul ignore if*/ if (!n) { return ""; } if (hasPrettierIgnore$1(path)) { const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column); const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column); const ignoredText = options.originalText.slice(startOffset, endOffset); return ignoredText; } switch (n.type) { case "Block": case "Program": case "Template": { return group$6(concat$7(path.map(print, "body"))); } case "ElementNode": { const hasChildren = n.children.length > 0; const hasNonWhitespaceChildren = n.children.some(n => !isWhitespaceNode$1(n)); const isVoid = isGlimmerComponent$1(n) && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.includes(n.tag); const closeTagForNoBreak = isVoid ? concat$7([" />", softline$3]) : ">"; const closeTagForBreak = isVoid ? "/>" : ">"; const printParams = (path, print) => indent$4(concat$7([n.attributes.length ? line$4 : "", join$4(line$4, path.map(print, "attributes")), n.modifiers.length ? line$4 : "", join$4(line$4, path.map(print, "modifiers")), n.comments.length ? line$4 : "", join$4(line$4, path.map(print, "comments"))])); const nextNode = getNextNode$1(path); return concat$7([group$6(concat$7(["<", n.tag, printParams(path, print), n.blockParams.length ? " as |".concat(n.blockParams.join(" "), "|") : "", ifBreak$3(softline$3, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$6(concat$7([hasNonWhitespaceChildren ? indent$4(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$6 : "", ""), concat$7([""])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$6 : ""]); } case "BlockStatement": { const pp = path.getParentNode(1); const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if"; const hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if"; const indentElse = hasElseIf ? a => a : indent$4; const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + (n.inverseStrip.close ? "~}}" : "}}"); if (n.inverse) { return concat$7([isElseIf ? concat$7([n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]) : printOpenBlock(path, print, n.openStrip), indent$4(concat$7([hardline$6, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$7([hardline$6, inverseElseStatement]) : "", n.inverse ? indentElse(concat$7([hardline$6, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$7([hardline$6, printCloseBlock(path, print, n.closeStrip)])]); } else if (isElseIf) { return concat$7([concat$7([n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]), indent$4(concat$7([hardline$6, path.call(print, "program")]))]); } const hasNonWhitespaceChildren = n.program.body.some(n => !isWhitespaceNode$1(n)); return concat$7([printOpenBlock(path, print, n.openStrip), group$6(concat$7([indent$4(concat$7([softline$3, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline$6 : softline$3, printCloseBlock(path, print, n.closeStrip)]))]); } case "ElementModifierStatement": { return group$6(concat$7(["{{", printPathParams(path, print), softline$3, "}}"])); } case "MustacheStatement": { const isEscaped = n.escaped === false; const { open: openStrip, close: closeStrip } = n.strip; const opening = (isEscaped ? "{{{" : "{{") + (openStrip ? "~" : ""); const closing = (closeStrip ? "~" : "") + (isEscaped ? "}}}" : "}}"); const leading = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement", "ElementNode"]) ? [opening, indent$4(softline$3)] : [opening]; return group$6(concat$7([...leading, printPathParams(path, print), softline$3, closing])); } case "SubExpression": { const params = printParams(path, print); const printedParams = params.length > 0 ? indent$4(concat$7([line$4, group$6(join$4(line$4, params))])) : ""; return group$6(concat$7(["(", printPath(path, print), printedParams, softline$3, ")"])); } case "AttrNode": { const isText = n.value.type === "TextNode"; const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the // same, there is no value for this AttrNode and it should be printed // without the `=""`. Example: `` -> `` const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column; if (isEmptyValue) { return concat$7([n.name]); } const value = path.call(print, "value"); const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value; return concat$7([n.name, "=", quotedValue]); } case "ConcatStatement": { return concat$7(['"', concat$7(path.map(partPath => print(partPath), "parts").filter(a => a !== "")), '"']); } case "Hash": { return concat$7([join$4(line$4, path.map(print, "pairs"))]); } case "HashPair": { return concat$7([n.key, "=", path.call(print, "value")]); } case "TextNode": { const maxLineBreaksToPreserve = 2; const isFirstElement = !getPreviousNode$1(path); const isLastElement = !getNextNode$1(path); const isWhitespaceOnly = !/\S/.test(n.chars); const lineBreaksCount = countNewLines(n.chars); const hasBlockParent = path.getParentNode(0).type === "Block"; const hasElementParent = path.getParentNode(0).type === "ElementNode"; const hasTemplateParent = path.getParentNode(0).type === "Template"; let leadingLineBreaksCount = countLeadingNewLines(n.chars); let trailingLineBreaksCount = countTrailingNewLines(n.chars); if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) { return ""; } if (isWhitespaceOnly && lineBreaksCount) { leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve); trailingLineBreaksCount = 0; } else { if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) { trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1); } if (isPreviousNodeOfSomeType$1(path, ["ElementNode"]) || isPreviousNodeOfSomeType$1(path, ["BlockStatement"])) { leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1); } } let leadingSpace = ""; let trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present, // when next to mustache statement. const inAttrNode = path.stack.includes("attributes"); if (inAttrNode) { const parentNode = path.getParentNode(0); const isConcat = parentNode.type === "ConcatStatement"; if (isConcat) { const { parts } = parentNode; const partIndex = parts.indexOf(n); if (partIndex > 0) { const partType = parts[partIndex - 1].type; const isMustache = partType === "MustacheStatement"; if (isMustache) { leadingSpace = " "; } } if (partIndex < parts.length - 1) { const partType = parts[partIndex + 1].type; const isMustache = partType === "MustacheStatement"; if (isMustache) { trailingSpace = " "; } } } } else { if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) { trailingSpace = " "; } if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) { leadingSpace = " "; } if (isFirstElement) { leadingLineBreaksCount = 0; leadingSpace = ""; } if (isLastElement) { trailingLineBreaksCount = 0; trailingSpace = ""; } } return concat$7([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)].filter(Boolean)); } case "MustacheCommentStatement": { const dashes = n.value.includes("}}") ? "--" : ""; return concat$7(["{{!", dashes, n.value, dashes, "}}"]); } case "PathExpression": { return n.original; } case "BooleanLiteral": { return String(n.value); } case "CommentStatement": { return concat$7([""]); } case "StringLiteral": { return printStringLiteral(n.value, options); } case "NumberLiteral": { return String(n.value); } case "UndefinedLiteral": { return "undefined"; } case "NullLiteral": { return "null"; } /* istanbul ignore next */ default: throw new Error("unknown glimmer type: " + JSON.stringify(n.type)); } } function printChildren(path, options, print) { return concat$7(path.map((childPath, childIndex) => { const childNode = path.getValue(); const isFirstNode = childIndex === 0; const isLastNode = childIndex === path.getParentNode(0).children.length - 1; const isLastNodeInMultiNodeList = isLastNode && !isFirstNode; const isWhitespace = isWhitespaceNode$1(childNode); if (isWhitespace && isLastNodeInMultiNodeList) { return print(childPath, options, print); } else if (isFirstNode) { return concat$7([softline$3, print(childPath, options, print)]); } return print(childPath, options, print); }, "children")); } /** * Prints a string literal with the correct surrounding quotes based on * `options.singleQuote` and the number of escaped quotes contained in * the string literal. This function is the glimmer equivalent of `printString` * in `common/util`, but has differences because of the way escaped characters * are treated in hbs string literals. * @param {string} stringLiteral - the string literal value * @param {object} options - the prettier options object */ function printStringLiteral(stringLiteral, options) { const double = { quote: '"', regex: /"/g }; const single = { quote: "'", regex: /'/g }; const preferred = options.singleQuote ? single : double; const alternate = preferred === single ? double : single; let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for // enclosing the string, we might want to enclose with the alternate quote // instead, to minimize the number of escaped quotes. if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) { const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length; const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length; shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; } const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred; const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, "\\".concat(enclosingQuote.quote)); return concat$7([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]); } function printPath(path, print) { return path.call(print, "path"); } function printParams(path, print) { const node = path.getValue(); let parts = []; if (node.params.length > 0) { parts = parts.concat(path.map(print, "params")); } if (node.hash && node.hash.pairs.length > 0) { parts.push(path.call(print, "hash")); } return parts; } function printPathParams(path, print) { const printedPath = printPath(path, print); const printedParams = printParams(path, print); const parts = [printedPath, ...printedParams]; return indent$4(group$6(join$4(line$4, parts))); } function printBlockParams(path) { const block = path.getValue(); if (!block.program || !block.program.blockParams.length) { return ""; } return concat$7([" as |", block.program.blockParams.join(" "), "|"]); } function printOpenBlock(path, print, { open: isOpenStrip = false, close: isCloseStrip = false } = {}) { return group$6(concat$7([isOpenStrip ? "{{~#" : "{{#", printPathParams(path, print), printBlockParams(path), softline$3, isCloseStrip ? "~}}" : "}}"])); } function printCloseBlock(path, print, { open: isOpenStrip = false, close: isCloseStrip = false } = {}) { return concat$7([isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), isCloseStrip ? "~}}" : "}}"]); } function countNewLines(string) { /* istanbul ignore next */ string = typeof string === "string" ? string : ""; return string.split("\n").length - 1; } function countLeadingNewLines(string) { /* istanbul ignore next */ string = typeof string === "string" ? string : ""; const newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || ""; return countNewLines(newLines); } function countTrailingNewLines(string) { /* istanbul ignore next */ string = typeof string === "string" ? string : ""; const newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || ""; return countNewLines(newLines); } function generateHardlines(number = 0, max = 0) { return new Array(Math.min(number, max)).fill(hardline$6); } /* istanbul ignore next https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29 */ function locationToOffset(source, line, column) { let seenLines = 0; let seenChars = 0; // eslint-disable-next-line no-constant-condition while (true) { if (seenChars === source.length) { return null; } let nextLine = source.indexOf("\n", seenChars); if (nextLine === -1) { nextLine = source.length; } if (seenLines === line) { if (seenChars + column > nextLine) { return null; } return seenChars + column; } else if (nextLine === -1) { return null; } seenLines += 1; seenChars = nextLine + 1; } } var printerGlimmer = { print, massageAstNode: clean$2 }; var name$6 = "Handlebars"; var type$5 = "markup"; var group$7 = "HTML"; var aliases = [ "hbs", "htmlbars" ]; var extensions$5 = [ ".handlebars", ".hbs" ]; var tmScope$5 = "text.html.handlebars"; var aceMode$5 = "handlebars"; var languageId$5 = 155; var Handlebars = { name: name$6, type: type$5, group: group$7, aliases: aliases, extensions: extensions$5, tmScope: tmScope$5, aceMode: aceMode$5, languageId: languageId$5 }; var Handlebars$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$6, type: type$5, group: group$7, aliases: aliases, extensions: extensions$5, tmScope: tmScope$5, aceMode: aceMode$5, languageId: languageId$5, 'default': Handlebars }); var require$$0$4 = getCjsExportFromNamespace(Handlebars$1); const languages$2 = [createLanguage(require$$0$4, () => ({ since: null, // unreleased parsers: ["glimmer"], vscodeLanguageIds: ["handlebars"] }))]; const printers$2 = { glimmer: printerGlimmer }; var languageHandlebars = { languages: languages$2, printers: printers$2 }; var clean$3 = function clean(ast, newNode) { delete newNode.sourceSpan; delete newNode.startSourceSpan; delete newNode.endSourceSpan; delete newNode.nameSpan; delete newNode.valueSpan; if (ast.type === "text" || ast.type === "comment") { return null; } // may be formatted by multiparser if (ast.type === "yaml" || ast.type === "toml") { return null; } if (ast.type === "attribute") { delete newNode.value; } if (ast.type === "docType") { delete newNode.value; } }; var json = { "CSS_DISPLAY_TAGS": { "area": "none", "base": "none", "basefont": "none", "datalist": "none", "head": "none", "link": "none", "meta": "none", "noembed": "none", "noframes": "none", "param": "none", "rp": "none", "script": "block", "source": "block", "style": "none", "template": "inline", "track": "block", "title": "none", "html": "block", "body": "block", "address": "block", "blockquote": "block", "center": "block", "div": "block", "figure": "block", "figcaption": "block", "footer": "block", "form": "block", "header": "block", "hr": "block", "legend": "block", "listing": "block", "main": "block", "p": "block", "plaintext": "block", "pre": "block", "xmp": "block", "slot": "contents", "ruby": "ruby", "rt": "ruby-text", "article": "block", "aside": "block", "h1": "block", "h2": "block", "h3": "block", "h4": "block", "h5": "block", "h6": "block", "hgroup": "block", "nav": "block", "section": "block", "dir": "block", "dd": "block", "dl": "block", "dt": "block", "ol": "block", "ul": "block", "li": "list-item", "table": "table", "caption": "table-caption", "colgroup": "table-column-group", "col": "table-column", "thead": "table-header-group", "tbody": "table-row-group", "tfoot": "table-footer-group", "tr": "table-row", "td": "table-cell", "th": "table-cell", "fieldset": "block", "button": "inline-block", "video": "inline-block", "audio": "inline-block" }, "CSS_DISPLAY_DEFAULT": "inline", "CSS_WHITE_SPACE_TAGS": { "listing": "pre", "plaintext": "pre", "pre": "pre", "xmp": "pre", "nobr": "nowrap", "table": "initial", "textarea": "pre-wrap" }, "CSS_WHITE_SPACE_DEFAULT": "normal" }; var index = [ "a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp" ]; var htmlTagNames = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': index }); var a = [ "accesskey", "charset", "coords", "download", "href", "hreflang", "name", "ping", "referrerpolicy", "rel", "rev", "shape", "tabindex", "target", "type" ]; var abbr = [ "title" ]; var applet = [ "align", "alt", "archive", "code", "codebase", "height", "hspace", "name", "object", "vspace", "width" ]; var area = [ "accesskey", "alt", "coords", "download", "href", "hreflang", "nohref", "ping", "referrerpolicy", "rel", "shape", "tabindex", "target", "type" ]; var audio = [ "autoplay", "controls", "crossorigin", "loop", "muted", "preload", "src" ]; var base = [ "href", "target" ]; var basefont = [ "color", "face", "size" ]; var bdo = [ "dir" ]; var blockquote = [ "cite" ]; var body = [ "alink", "background", "bgcolor", "link", "text", "vlink" ]; var br = [ "clear" ]; var button = [ "accesskey", "autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "tabindex", "type", "value" ]; var canvas = [ "height", "width" ]; var caption = [ "align" ]; var col = [ "align", "char", "charoff", "span", "valign", "width" ]; var colgroup = [ "align", "char", "charoff", "span", "valign", "width" ]; var data = [ "value" ]; var del = [ "cite", "datetime" ]; var details = [ "open" ]; var dfn = [ "title" ]; var dialog = [ "open" ]; var dir = [ "compact" ]; var div = [ "align" ]; var dl = [ "compact" ]; var embed$1 = [ "height", "src", "type", "width" ]; var fieldset = [ "disabled", "form", "name" ]; var font = [ "color", "face", "size" ]; var form = [ "accept", "accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target" ]; var frame = [ "frameborder", "longdesc", "marginheight", "marginwidth", "name", "noresize", "scrolling", "src" ]; var frameset = [ "cols", "rows" ]; var h1 = [ "align" ]; var h2 = [ "align" ]; var h3 = [ "align" ]; var h4 = [ "align" ]; var h5 = [ "align" ]; var h6 = [ "align" ]; var head = [ "profile" ]; var hr = [ "align", "noshade", "size", "width" ]; var html = [ "manifest", "version" ]; var iframe = [ "align", "allow", "allowfullscreen", "allowpaymentrequest", "allowusermedia", "frameborder", "height", "longdesc", "marginheight", "marginwidth", "name", "referrerpolicy", "sandbox", "scrolling", "src", "srcdoc", "width" ]; var img = [ "align", "alt", "border", "crossorigin", "decoding", "height", "hspace", "ismap", "longdesc", "name", "referrerpolicy", "sizes", "src", "srcset", "usemap", "vspace", "width" ]; var input = [ "accept", "accesskey", "align", "alt", "autocomplete", "autofocus", "checked", "dirname", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "ismap", "list", "max", "maxlength", "min", "minlength", "multiple", "name", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "tabindex", "title", "type", "usemap", "value", "width" ]; var ins = [ "cite", "datetime" ]; var isindex = [ "prompt" ]; var label = [ "accesskey", "for", "form" ]; var legend = [ "accesskey", "align" ]; var li = [ "type", "value" ]; var link$3 = [ "as", "charset", "color", "crossorigin", "href", "hreflang", "imagesizes", "imagesrcset", "integrity", "media", "nonce", "referrerpolicy", "rel", "rev", "sizes", "target", "title", "type" ]; var map = [ "name" ]; var menu = [ "compact" ]; var meta = [ "charset", "content", "http-equiv", "name", "scheme" ]; var meter = [ "high", "low", "max", "min", "optimum", "value" ]; var object = [ "align", "archive", "border", "classid", "codebase", "codetype", "data", "declare", "form", "height", "hspace", "name", "standby", "tabindex", "type", "typemustmatch", "usemap", "vspace", "width" ]; var ol = [ "compact", "reversed", "start", "type" ]; var optgroup = [ "disabled", "label" ]; var option = [ "disabled", "label", "selected", "value" ]; var output = [ "for", "form", "name" ]; var p = [ "align" ]; var param = [ "name", "type", "value", "valuetype" ]; var pre = [ "width" ]; var progress = [ "max", "value" ]; var q = [ "cite" ]; var script = [ "async", "charset", "crossorigin", "defer", "integrity", "language", "nomodule", "nonce", "referrerpolicy", "src", "type" ]; var select = [ "autocomplete", "autofocus", "disabled", "form", "multiple", "name", "required", "size", "tabindex" ]; var slot = [ "name" ]; var source$1 = [ "media", "sizes", "src", "srcset", "type" ]; var style = [ "media", "nonce", "title", "type" ]; var table = [ "align", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "rules", "summary", "width" ]; var tbody = [ "align", "char", "charoff", "valign" ]; var td = [ "abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width" ]; var textarea = [ "accesskey", "autocomplete", "autofocus", "cols", "dirname", "disabled", "form", "maxlength", "minlength", "name", "placeholder", "readonly", "required", "rows", "tabindex", "wrap" ]; var tfoot = [ "align", "char", "charoff", "valign" ]; var th = [ "abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width" ]; var thead = [ "align", "char", "charoff", "valign" ]; var time = [ "datetime" ]; var tr = [ "align", "bgcolor", "char", "charoff", "valign" ]; var track = [ "default", "kind", "label", "src", "srclang" ]; var ul = [ "compact", "type" ]; var video = [ "autoplay", "controls", "crossorigin", "height", "loop", "muted", "playsinline", "poster", "preload", "src", "width" ]; var index$1 = { "*": [ "accesskey", "autocapitalize", "autofocus", "class", "contenteditable", "dir", "draggable", "enterkeyhint", "hidden", "id", "inputmode", "is", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "nonce", "slot", "spellcheck", "style", "tabindex", "title", "translate" ], a: a, abbr: abbr, applet: applet, area: area, audio: audio, base: base, basefont: basefont, bdo: bdo, blockquote: blockquote, body: body, br: br, button: button, canvas: canvas, caption: caption, col: col, colgroup: colgroup, data: data, del: del, details: details, dfn: dfn, dialog: dialog, dir: dir, div: div, dl: dl, embed: embed$1, fieldset: fieldset, font: font, form: form, frame: frame, frameset: frameset, h1: h1, h2: h2, h3: h3, h4: h4, h5: h5, h6: h6, head: head, hr: hr, html: html, iframe: iframe, img: img, input: input, ins: ins, isindex: isindex, label: label, legend: legend, li: li, link: link$3, map: map, menu: menu, meta: meta, meter: meter, object: object, ol: ol, optgroup: optgroup, option: option, output: output, p: p, param: param, pre: pre, progress: progress, q: q, script: script, select: select, slot: slot, source: source$1, style: style, table: table, tbody: tbody, td: td, textarea: textarea, tfoot: tfoot, th: th, thead: thead, time: time, tr: tr, track: track, ul: ul, video: video }; var htmlElementAttributes = /*#__PURE__*/Object.freeze({ __proto__: null, a: a, abbr: abbr, applet: applet, area: area, audio: audio, base: base, basefont: basefont, bdo: bdo, blockquote: blockquote, body: body, br: br, button: button, canvas: canvas, caption: caption, col: col, colgroup: colgroup, data: data, del: del, details: details, dfn: dfn, dialog: dialog, dir: dir, div: div, dl: dl, embed: embed$1, fieldset: fieldset, font: font, form: form, frame: frame, frameset: frameset, h1: h1, h2: h2, h3: h3, h4: h4, h5: h5, h6: h6, head: head, hr: hr, html: html, iframe: iframe, img: img, input: input, ins: ins, isindex: isindex, label: label, legend: legend, li: li, link: link$3, map: map, menu: menu, meta: meta, meter: meter, object: object, ol: ol, optgroup: optgroup, option: option, output: output, p: p, param: param, pre: pre, progress: progress, q: q, script: script, select: select, slot: slot, source: source$1, style: style, table: table, tbody: tbody, td: td, textarea: textarea, tfoot: tfoot, th: th, thead: thead, time: time, tr: tr, track: track, ul: ul, video: video, 'default': index$1 }); var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames); var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes); const { CSS_DISPLAY_TAGS, CSS_DISPLAY_DEFAULT, CSS_WHITE_SPACE_TAGS, CSS_WHITE_SPACE_DEFAULT } = json; const HTML_TAGS = arrayToMap(htmlTagNames$1); const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); function arrayToMap(array) { const map = Object.create(null); for (const value of array) { map[value] = true; } return map; } function mapObject(object, fn) { const newObject = Object.create(null); for (const key of Object.keys(object)) { newObject[key] = fn(object[key], key); } return newObject; } function shouldPreserveContent(node, options) { if (!node.endSourceSpan) { return false; } if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") { return true; } // unterminated node in ie conditional comment // e.g. if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) { return true; } // incomplete html in ie conditional comment // e.g. if (node.type === "ieConditionalComment" && !node.complete) { return true; } // top-level elements (excluding