├── .cfignore ├── .gitignore ├── README.md ├── css └── mddoc.css ├── favicon.ico ├── img └── md.png ├── index.html └── js ├── markdown.js ├── mddoc.js ├── old.js ├── pouchdb-5.2.1.min.js └── uuid.js /.cfignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | start.sh 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | start.sh 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MD 2 | 3 | This project contains the code to create "MD", an in-browser, offline-first, Markdown word processor. 4 | 5 | ![logo](https://github.com/glynnbird/md/raw/master/public/img/md.png) 6 | 7 | To run it, simply clone this repository and run 8 | 9 | npm install 10 | node app.js 11 | 12 | and visit "http://localhost:3000/" in your browser. Alternatively, this app can be hosted on IBM Bluemix or another Node.js hosting platform. It can be tried out by visiting 13 | 14 | * click “New” to create a new document 15 | * add some Markdown into the grey box e.g. ## Hello World 16 | * give your document a name 17 | * press save 18 | * your document should now be visible in the "Load" popup 19 | * disconnect yourself from the internet (or kill the node app.js, if you’re self-hosting) 20 | * refresh the app in the browser - it should still work! 21 | 22 | ## How do I try it? 23 | 24 | The easiest way is to click the button below: 25 | 26 | Deploy to Bluemix 27 | 28 | This will deploy this App to your Bluemix account, or allow you to create one first if you don't have one. Bluemix is IBM's Platform-as-a-Service and allows you to deploy your code together with open-source and proprietary services with a few clicks, or using the CloudFoundry tools. 29 | 30 | ## How does it work? 31 | 32 | ### PouchDB 33 | 34 | [PouchDB](http://pouchdb.com/) is an in-browser database. In a few lines of code, Javascript objects can be saved an retrieved using the browser's internal storage. As no internet connection is required after the browser has loaded the page, PouchDB is a great tool to create offline-first applications. Here's some example code to create a database 'md' and add a simple document to it: 35 | 36 | var db = new PouchDB("md"); 37 | var doc = { name: "fred", body: "Document body" }; 38 | db.post(doc, function(err, data) { 39 | console.log("Saved", err, data); 40 | }); 41 | 42 | PouchDB is NoSQL data store; it does not force you to define a database schema up front, nor does it force you to follow the same document pattern for every document in the database. For this application, the documents look like this: 43 | 44 | { 45 | "_id": "23966717-5A6F-E581-AF79-BB55D6BBB613", 46 | "_rev": "1-96daf2e7c7c0c277d0a63c49b57919bc", 47 | "doc_id": "0d7c2bf2-d9d5-4db3-a412-5f85aa8d2f76", 48 | "doc_name": "Markdown Reference", 49 | "body": "Lorem Ipsum", 50 | "ts": 1422358827 51 | } 52 | 53 | The __\_id__ and __\_rev__ are auto-generated by PouchDB. The **doc_id** is generated programmatically by us and is used to uniquely identify a document. The same **doc\_id** may appear in several PouchDB documents, representing different iterations of the same document. Each document has a **doc\_name**, **body** and **ts**, representing the name, the Markdown of the document and the Unix timestamp when the document was saved. 54 | 55 | 56 | ### Manifest files 57 | 58 | In order for your app to be work offline, the app needs to instruct the browser to retain some files locally for offline use. A project's manifest file contains a list of urls that need to cached by the browser e.g. the site's home page and all of its Javascript and CSS assets. 59 | 60 | 61 | ### Markdown 62 | 63 | Markdown is a simple text-based syntax that allows basic document formatting to be defined and converted programmatically into HTML. The full Markdown syntax reference can be found here . 64 | 65 | ### Syncing with Cloudant 66 | 67 | This web app can function quite happily, saving its data to your local web browser. For a real-world application, however, we may wish to backup our store of documents to the Cloud. With PouchDB this is easy, as PouchDB is compatible with CouchDB's replication protocol. Cloudant, which is based on CouchDB, is also a compatible target for PouchDB replication. With a single line of code, your local PouchDB database is synced to the cloud: 68 | 69 | db.sync("https://myusername:mypassword@myhost.cloudant.com/mydb"); 70 | 71 | Simply: 72 | 73 | * [Sign-up for a Cloudant account](https://cloudant.com/sign-up/) 74 | * Create a new database in the Cloudant Dashboard 75 | * In the permissions tab, generate a new api key 76 | * Make the generated api have "reader" & writer access 77 | * Enable CORS access 78 | * Construct the url: https://APIKEY:PASSWORD@HOSTNAME.cloudant.com/DATABASE_NAME 79 | * Paste the url into the settings tab of the web app and press save. 80 | 81 | The app will save your Cloudant URL in a different PouchDB database. When the app loads again, it will retrieve the Cloudant URL from local storage and re-initialise synchronisation. 82 | -------------------------------------------------------------------------------- /css/mddoc.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | height: 100%; 3 | } 4 | 5 | body { 6 | } 7 | 8 | .myctrl { 9 | margin-left:20px; 10 | } 11 | 12 | .container { 13 | height:100%; 14 | } 15 | 16 | #togglepreviewlabel { 17 | color: #ccc; 18 | } 19 | 20 | #themarkdown { 21 | width: 100%; 22 | height: 100vh; 23 | background-color: #eee; 24 | overflow: scroll; 25 | outline: none; 26 | font-family: "Courier New", Courier, monospace; 27 | min-height:500px; 28 | } 29 | #rendered { 30 | width: 100%; 31 | height: 100vh; 32 | overflow: scroll; 33 | } 34 | #cloudanturl { 35 | width:90%; 36 | } 37 | 38 | #jumbo { 39 | background-color: white; 40 | border:2px solid #666; 41 | } 42 | 43 | @media print 44 | { 45 | 46 | #themarkdown { display:none} 47 | #rendered { overflow:visible;} 48 | #nav { display:none;} 49 | .alert {display: none;} 50 | } -------------------------------------------------------------------------------- /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glynnbird/md/153b208bc601ea368e3570c2517acf0542ce53f9/favicon.ico -------------------------------------------------------------------------------- /img/md.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glynnbird/md/153b208bc601ea368e3570c2517acf0542ce53f9/img/md.png -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MD - Markdown word processor 7 | 8 | 9 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 34 | 35 |
36 | 47 | 48 |
49 | 50 |

MD

51 |

An offline-first, Markdown wordprocessor

52 |
    53 |
  • write documents in Markdown, see it rendered as you type
  • 54 |
  • store your work locally using PouchDB
  • 55 |
  • continue working with or without an internet connection
  • 56 |
  • sync to the cloud - CouchDB or Cloudant
  • 57 |
58 |

59 |
60 | 61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 | 69 |
70 |
71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /js/markdown.js: -------------------------------------------------------------------------------- 1 | // Released under MIT license 2 | // Copyright (c) 2009-2010 Dominic Baggott 3 | // Copyright (c) 2009-2010 Ash Berlin 4 | // Copyright (c) 2011 Christoph Dorn (http://www.christophdorn.com) 5 | // Date: 2013-09-15T16:12Z 6 | 7 | (function(expose) { 8 | 9 | 10 | 11 | 12 | var MarkdownHelpers = {}; 13 | 14 | // For Spidermonkey based engines 15 | function mk_block_toSource() { 16 | return "Markdown.mk_block( " + 17 | uneval(this.toString()) + 18 | ", " + 19 | uneval(this.trailing) + 20 | ", " + 21 | uneval(this.lineNumber) + 22 | " )"; 23 | } 24 | 25 | // node 26 | function mk_block_inspect() { 27 | var util = require("util"); 28 | return "Markdown.mk_block( " + 29 | util.inspect(this.toString()) + 30 | ", " + 31 | util.inspect(this.trailing) + 32 | ", " + 33 | util.inspect(this.lineNumber) + 34 | " )"; 35 | 36 | } 37 | 38 | MarkdownHelpers.mk_block = function(block, trail, line) { 39 | // Be helpful for default case in tests. 40 | if ( arguments.length === 1 ) 41 | trail = "\n\n"; 42 | 43 | // We actually need a String object, not a string primitive 44 | /* jshint -W053 */ 45 | var s = new String(block); 46 | s.trailing = trail; 47 | // To make it clear its not just a string 48 | s.inspect = mk_block_inspect; 49 | s.toSource = mk_block_toSource; 50 | 51 | if ( line !== undefined ) 52 | s.lineNumber = line; 53 | 54 | return s; 55 | }; 56 | 57 | 58 | var isArray = MarkdownHelpers.isArray = Array.isArray || function(obj) { 59 | return Object.prototype.toString.call(obj) === "[object Array]"; 60 | }; 61 | 62 | // Don't mess with Array.prototype. Its not friendly 63 | if ( Array.prototype.forEach ) { 64 | MarkdownHelpers.forEach = function forEach( arr, cb, thisp ) { 65 | return arr.forEach( cb, thisp ); 66 | }; 67 | } 68 | else { 69 | MarkdownHelpers.forEach = function forEach(arr, cb, thisp) { 70 | for (var i = 0; i < arr.length; i++) 71 | cb.call(thisp || arr, arr[i], i, arr); 72 | }; 73 | } 74 | 75 | MarkdownHelpers.isEmpty = function isEmpty( obj ) { 76 | for ( var key in obj ) { 77 | if ( hasOwnProperty.call( obj, key ) ) 78 | return false; 79 | } 80 | return true; 81 | }; 82 | 83 | MarkdownHelpers.extract_attr = function extract_attr( jsonml ) { 84 | return isArray(jsonml) 85 | && jsonml.length > 1 86 | && typeof jsonml[ 1 ] === "object" 87 | && !( isArray(jsonml[ 1 ]) ) 88 | ? jsonml[ 1 ] 89 | : undefined; 90 | }; 91 | 92 | 93 | 94 | 95 | /** 96 | * class Markdown 97 | * 98 | * Markdown processing in Javascript done right. We have very particular views 99 | * on what constitutes 'right' which include: 100 | * 101 | * - produces well-formed HTML (this means that em and strong nesting is 102 | * important) 103 | * 104 | * - has an intermediate representation to allow processing of parsed data (We 105 | * in fact have two, both as [JsonML]: a markdown tree and an HTML tree). 106 | * 107 | * - is easily extensible to add new dialects without having to rewrite the 108 | * entire parsing mechanics 109 | * 110 | * - has a good test suite 111 | * 112 | * This implementation fulfills all of these (except that the test suite could 113 | * do with expanding to automatically run all the fixtures from other Markdown 114 | * implementations.) 115 | * 116 | * ##### Intermediate Representation 117 | * 118 | * *TODO* Talk about this :) Its JsonML, but document the node names we use. 119 | * 120 | * [JsonML]: http://jsonml.org/ "JSON Markup Language" 121 | **/ 122 | var Markdown = function(dialect) { 123 | switch (typeof dialect) { 124 | case "undefined": 125 | this.dialect = Markdown.dialects.Gruber; 126 | break; 127 | case "object": 128 | this.dialect = dialect; 129 | break; 130 | default: 131 | if ( dialect in Markdown.dialects ) 132 | this.dialect = Markdown.dialects[dialect]; 133 | else 134 | throw new Error("Unknown Markdown dialect '" + String(dialect) + "'"); 135 | break; 136 | } 137 | this.em_state = []; 138 | this.strong_state = []; 139 | this.debug_indent = ""; 140 | }; 141 | 142 | /** 143 | * Markdown.dialects 144 | * 145 | * Namespace of built-in dialects. 146 | **/ 147 | Markdown.dialects = {}; 148 | 149 | 150 | 151 | 152 | // Imported functions 153 | var mk_block = Markdown.mk_block = MarkdownHelpers.mk_block, 154 | isArray = MarkdownHelpers.isArray; 155 | 156 | /** 157 | * parse( markdown, [dialect] ) -> JsonML 158 | * - markdown (String): markdown string to parse 159 | * - dialect (String | Dialect): the dialect to use, defaults to gruber 160 | * 161 | * Parse `markdown` and return a markdown document as a Markdown.JsonML tree. 162 | **/ 163 | Markdown.parse = function( source, dialect ) { 164 | // dialect will default if undefined 165 | var md = new Markdown( dialect ); 166 | return md.toTree( source ); 167 | }; 168 | 169 | function count_lines( str ) { 170 | var n = 0, 171 | i = -1; 172 | while ( ( i = str.indexOf("\n", i + 1) ) !== -1 ) 173 | n++; 174 | return n; 175 | } 176 | 177 | // Internal - split source into rough blocks 178 | Markdown.prototype.split_blocks = function splitBlocks( input ) { 179 | input = input.replace(/(\r\n|\n|\r)/g, "\n"); 180 | // [\s\S] matches _anything_ (newline or space) 181 | // [^] is equivalent but doesn't work in IEs. 182 | var re = /([\s\S]+?)($|\n#|\n(?:\s*\n|$)+)/g, 183 | blocks = [], 184 | m; 185 | 186 | var line_no = 1; 187 | 188 | if ( ( m = /^(\s*\n)/.exec(input) ) !== null ) { 189 | // skip (but count) leading blank lines 190 | line_no += count_lines( m[0] ); 191 | re.lastIndex = m[0].length; 192 | } 193 | 194 | while ( ( m = re.exec(input) ) !== null ) { 195 | if (m[2] === "\n#") { 196 | m[2] = "\n"; 197 | re.lastIndex--; 198 | } 199 | blocks.push( mk_block( m[1], m[2], line_no ) ); 200 | line_no += count_lines( m[0] ); 201 | } 202 | 203 | return blocks; 204 | }; 205 | 206 | /** 207 | * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ] 208 | * - block (String): the block to process 209 | * - next (Array): the following blocks 210 | * 211 | * Process `block` and return an array of JsonML nodes representing `block`. 212 | * 213 | * It does this by asking each block level function in the dialect to process 214 | * the block until one can. Succesful handling is indicated by returning an 215 | * array (with zero or more JsonML nodes), failure by a false value. 216 | * 217 | * Blocks handlers are responsible for calling [[Markdown#processInline]] 218 | * themselves as appropriate. 219 | * 220 | * If the blocks were split incorrectly or adjacent blocks need collapsing you 221 | * can adjust `next` in place using shift/splice etc. 222 | * 223 | * If any of this default behaviour is not right for the dialect, you can 224 | * define a `__call__` method on the dialect that will get invoked to handle 225 | * the block processing. 226 | */ 227 | Markdown.prototype.processBlock = function processBlock( block, next ) { 228 | var cbs = this.dialect.block, 229 | ord = cbs.__order__; 230 | 231 | if ( "__call__" in cbs ) 232 | return cbs.__call__.call(this, block, next); 233 | 234 | for ( var i = 0; i < ord.length; i++ ) { 235 | //D:this.debug( "Testing", ord[i] ); 236 | var res = cbs[ ord[i] ].call( this, block, next ); 237 | if ( res ) { 238 | //D:this.debug(" matched"); 239 | if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) ) 240 | this.debug(ord[i], "didn't return a proper array"); 241 | //D:this.debug( "" ); 242 | return res; 243 | } 244 | } 245 | 246 | // Uhoh! no match! Should we throw an error? 247 | return []; 248 | }; 249 | 250 | Markdown.prototype.processInline = function processInline( block ) { 251 | return this.dialect.inline.__call__.call( this, String( block ) ); 252 | }; 253 | 254 | /** 255 | * Markdown#toTree( source ) -> JsonML 256 | * - source (String): markdown source to parse 257 | * 258 | * Parse `source` into a JsonML tree representing the markdown document. 259 | **/ 260 | // custom_tree means set this.tree to `custom_tree` and restore old value on return 261 | Markdown.prototype.toTree = function toTree( source, custom_root ) { 262 | var blocks = source instanceof Array ? source : this.split_blocks( source ); 263 | 264 | // Make tree a member variable so its easier to mess with in extensions 265 | var old_tree = this.tree; 266 | try { 267 | this.tree = custom_root || this.tree || [ "markdown" ]; 268 | 269 | blocks_loop: 270 | while ( blocks.length ) { 271 | var b = this.processBlock( blocks.shift(), blocks ); 272 | 273 | // Reference blocks and the like won't return any content 274 | if ( !b.length ) 275 | continue blocks_loop; 276 | 277 | this.tree.push.apply( this.tree, b ); 278 | } 279 | return this.tree; 280 | } 281 | finally { 282 | if ( custom_root ) 283 | this.tree = old_tree; 284 | } 285 | }; 286 | 287 | // Noop by default 288 | Markdown.prototype.debug = function () { 289 | var args = Array.prototype.slice.call( arguments); 290 | args.unshift(this.debug_indent); 291 | if ( typeof print !== "undefined" ) 292 | print.apply( print, args ); 293 | if ( typeof console !== "undefined" && typeof console.log !== "undefined" ) 294 | console.log.apply( null, args ); 295 | }; 296 | 297 | Markdown.prototype.loop_re_over_block = function( re, block, cb ) { 298 | // Dont use /g regexps with this 299 | var m, 300 | b = block.valueOf(); 301 | 302 | while ( b.length && (m = re.exec(b) ) !== null ) { 303 | b = b.substr( m[0].length ); 304 | cb.call(this, m); 305 | } 306 | return b; 307 | }; 308 | 309 | // Build default order from insertion order. 310 | Markdown.buildBlockOrder = function(d) { 311 | var ord = []; 312 | for ( var i in d ) { 313 | if ( i === "__order__" || i === "__call__" ) 314 | continue; 315 | ord.push( i ); 316 | } 317 | d.__order__ = ord; 318 | }; 319 | 320 | // Build patterns for inline matcher 321 | Markdown.buildInlinePatterns = function(d) { 322 | var patterns = []; 323 | 324 | for ( var i in d ) { 325 | // __foo__ is reserved and not a pattern 326 | if ( i.match( /^__.*__$/) ) 327 | continue; 328 | var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" ) 329 | .replace( /\n/, "\\n" ); 330 | patterns.push( i.length === 1 ? l : "(?:" + l + ")" ); 331 | } 332 | 333 | patterns = patterns.join("|"); 334 | d.__patterns__ = patterns; 335 | //print("patterns:", uneval( patterns ) ); 336 | 337 | var fn = d.__call__; 338 | d.__call__ = function(text, pattern) { 339 | if ( pattern !== undefined ) 340 | return fn.call(this, text, pattern); 341 | else 342 | return fn.call(this, text, patterns); 343 | }; 344 | }; 345 | 346 | 347 | 348 | 349 | var extract_attr = MarkdownHelpers.extract_attr; 350 | 351 | /** 352 | * renderJsonML( jsonml[, options] ) -> String 353 | * - jsonml (Array): JsonML array to render to XML 354 | * - options (Object): options 355 | * 356 | * Converts the given JsonML into well-formed XML. 357 | * 358 | * The options currently understood are: 359 | * 360 | * - root (Boolean): wether or not the root node should be included in the 361 | * output, or just its children. The default `false` is to not include the 362 | * root itself. 363 | */ 364 | Markdown.renderJsonML = function( jsonml, options ) { 365 | options = options || {}; 366 | // include the root element in the rendered output? 367 | options.root = options.root || false; 368 | 369 | var content = []; 370 | 371 | if ( options.root ) { 372 | content.push( render_tree( jsonml ) ); 373 | } 374 | else { 375 | jsonml.shift(); // get rid of the tag 376 | if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) 377 | jsonml.shift(); // get rid of the attributes 378 | 379 | while ( jsonml.length ) 380 | content.push( render_tree( jsonml.shift() ) ); 381 | } 382 | 383 | return content.join( "\n\n" ); 384 | }; 385 | 386 | 387 | /** 388 | * toHTMLTree( markdown, [dialect] ) -> JsonML 389 | * toHTMLTree( md_tree ) -> JsonML 390 | * - markdown (String): markdown string to parse 391 | * - dialect (String | Dialect): the dialect to use, defaults to gruber 392 | * - md_tree (Markdown.JsonML): parsed markdown tree 393 | * 394 | * Turn markdown into HTML, represented as a JsonML tree. If a string is given 395 | * to this function, it is first parsed into a markdown tree by calling 396 | * [[parse]]. 397 | **/ 398 | Markdown.toHTMLTree = function toHTMLTree( input, dialect , options ) { 399 | 400 | // convert string input to an MD tree 401 | if ( typeof input === "string" ) 402 | input = this.parse( input, dialect ); 403 | 404 | // Now convert the MD tree to an HTML tree 405 | 406 | // remove references from the tree 407 | var attrs = extract_attr( input ), 408 | refs = {}; 409 | 410 | if ( attrs && attrs.references ) 411 | refs = attrs.references; 412 | 413 | var html = convert_tree_to_html( input, refs , options ); 414 | merge_text_nodes( html ); 415 | return html; 416 | }; 417 | 418 | /** 419 | * toHTML( markdown, [dialect] ) -> String 420 | * toHTML( md_tree ) -> String 421 | * - markdown (String): markdown string to parse 422 | * - md_tree (Markdown.JsonML): parsed markdown tree 423 | * 424 | * Take markdown (either as a string or as a JsonML tree) and run it through 425 | * [[toHTMLTree]] then turn it into a well-formated HTML fragment. 426 | **/ 427 | Markdown.toHTML = function toHTML( source , dialect , options ) { 428 | var input = this.toHTMLTree( source , dialect , options ); 429 | 430 | return this.renderJsonML( input ); 431 | }; 432 | 433 | 434 | function escapeHTML( text ) { 435 | return text.replace( /&/g, "&" ) 436 | .replace( //g, ">" ) 438 | .replace( /"/g, """ ) 439 | .replace( /'/g, "'" ); 440 | } 441 | 442 | function render_tree( jsonml ) { 443 | // basic case 444 | if ( typeof jsonml === "string" ) 445 | return escapeHTML( jsonml ); 446 | 447 | var tag = jsonml.shift(), 448 | attributes = {}, 449 | content = []; 450 | 451 | if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) 452 | attributes = jsonml.shift(); 453 | 454 | while ( jsonml.length ) 455 | content.push( render_tree( jsonml.shift() ) ); 456 | 457 | var tag_attrs = ""; 458 | for ( var a in attributes ) 459 | tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"'; 460 | 461 | // be careful about adding whitespace here for inline elements 462 | if ( tag === "img" || tag === "br" || tag === "hr" ) 463 | return "<"+ tag + tag_attrs + "/>"; 464 | else 465 | return "<"+ tag + tag_attrs + ">" + content.join( "" ) + ""; 466 | } 467 | 468 | function convert_tree_to_html( tree, references, options ) { 469 | var i; 470 | options = options || {}; 471 | 472 | // shallow clone 473 | var jsonml = tree.slice( 0 ); 474 | 475 | if ( typeof options.preprocessTreeNode === "function" ) 476 | jsonml = options.preprocessTreeNode(jsonml, references); 477 | 478 | // Clone attributes if they exist 479 | var attrs = extract_attr( jsonml ); 480 | if ( attrs ) { 481 | jsonml[ 1 ] = {}; 482 | for ( i in attrs ) { 483 | jsonml[ 1 ][ i ] = attrs[ i ]; 484 | } 485 | attrs = jsonml[ 1 ]; 486 | } 487 | 488 | // basic case 489 | if ( typeof jsonml === "string" ) 490 | return jsonml; 491 | 492 | // convert this node 493 | switch ( jsonml[ 0 ] ) { 494 | case "header": 495 | jsonml[ 0 ] = "h" + jsonml[ 1 ].level; 496 | delete jsonml[ 1 ].level; 497 | break; 498 | case "bulletlist": 499 | jsonml[ 0 ] = "ul"; 500 | break; 501 | case "numberlist": 502 | jsonml[ 0 ] = "ol"; 503 | break; 504 | case "listitem": 505 | jsonml[ 0 ] = "li"; 506 | break; 507 | case "para": 508 | jsonml[ 0 ] = "p"; 509 | break; 510 | case "markdown": 511 | jsonml[ 0 ] = "html"; 512 | if ( attrs ) 513 | delete attrs.references; 514 | break; 515 | case "code_block": 516 | jsonml[ 0 ] = "pre"; 517 | i = attrs ? 2 : 1; 518 | var code = [ "code" ]; 519 | code.push.apply( code, jsonml.splice( i, jsonml.length - i ) ); 520 | jsonml[ i ] = code; 521 | break; 522 | case "inlinecode": 523 | jsonml[ 0 ] = "code"; 524 | break; 525 | case "img": 526 | jsonml[ 1 ].src = jsonml[ 1 ].href; 527 | delete jsonml[ 1 ].href; 528 | break; 529 | case "linebreak": 530 | jsonml[ 0 ] = "br"; 531 | break; 532 | case "link": 533 | jsonml[ 0 ] = "a"; 534 | break; 535 | case "link_ref": 536 | jsonml[ 0 ] = "a"; 537 | 538 | // grab this ref and clean up the attribute node 539 | var ref = references[ attrs.ref ]; 540 | 541 | // if the reference exists, make the link 542 | if ( ref ) { 543 | delete attrs.ref; 544 | 545 | // add in the href and title, if present 546 | attrs.href = ref.href; 547 | if ( ref.title ) 548 | attrs.title = ref.title; 549 | 550 | // get rid of the unneeded original text 551 | delete attrs.original; 552 | } 553 | // the reference doesn't exist, so revert to plain text 554 | else { 555 | return attrs.original; 556 | } 557 | break; 558 | case "img_ref": 559 | jsonml[ 0 ] = "img"; 560 | 561 | // grab this ref and clean up the attribute node 562 | var ref = references[ attrs.ref ]; 563 | 564 | // if the reference exists, make the link 565 | if ( ref ) { 566 | delete attrs.ref; 567 | 568 | // add in the href and title, if present 569 | attrs.src = ref.href; 570 | if ( ref.title ) 571 | attrs.title = ref.title; 572 | 573 | // get rid of the unneeded original text 574 | delete attrs.original; 575 | } 576 | // the reference doesn't exist, so revert to plain text 577 | else { 578 | return attrs.original; 579 | } 580 | break; 581 | } 582 | 583 | // convert all the children 584 | i = 1; 585 | 586 | // deal with the attribute node, if it exists 587 | if ( attrs ) { 588 | // if there are keys, skip over it 589 | for ( var key in jsonml[ 1 ] ) { 590 | i = 2; 591 | break; 592 | } 593 | // if there aren't, remove it 594 | if ( i === 1 ) 595 | jsonml.splice( i, 1 ); 596 | } 597 | 598 | for ( ; i < jsonml.length; ++i ) { 599 | jsonml[ i ] = convert_tree_to_html( jsonml[ i ], references, options ); 600 | } 601 | 602 | return jsonml; 603 | } 604 | 605 | 606 | // merges adjacent text nodes into a single node 607 | function merge_text_nodes( jsonml ) { 608 | // skip the tag name and attribute hash 609 | var i = extract_attr( jsonml ) ? 2 : 1; 610 | 611 | while ( i < jsonml.length ) { 612 | // if it's a string check the next item too 613 | if ( typeof jsonml[ i ] === "string" ) { 614 | if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { 615 | // merge the second string into the first and remove it 616 | jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; 617 | } 618 | else { 619 | ++i; 620 | } 621 | } 622 | // if it's not a string recurse 623 | else { 624 | merge_text_nodes( jsonml[ i ] ); 625 | ++i; 626 | } 627 | } 628 | }; 629 | 630 | 631 | 632 | var DialectHelpers = {}; 633 | DialectHelpers.inline_until_char = function( text, want ) { 634 | var consumed = 0, 635 | nodes = []; 636 | 637 | while ( true ) { 638 | if ( text.charAt( consumed ) === want ) { 639 | // Found the character we were looking for 640 | consumed++; 641 | return [ consumed, nodes ]; 642 | } 643 | 644 | if ( consumed >= text.length ) { 645 | // No closing char found. Abort. 646 | return null; 647 | } 648 | 649 | var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) ); 650 | consumed += res[ 0 ]; 651 | // Add any returned nodes. 652 | nodes.push.apply( nodes, res.slice( 1 ) ); 653 | } 654 | }; 655 | 656 | // Helper function to make sub-classing a dialect easier 657 | DialectHelpers.subclassDialect = function( d ) { 658 | function Block() {} 659 | Block.prototype = d.block; 660 | function Inline() {} 661 | Inline.prototype = d.inline; 662 | 663 | return { block: new Block(), inline: new Inline() }; 664 | }; 665 | 666 | 667 | 668 | 669 | var forEach = MarkdownHelpers.forEach, 670 | extract_attr = MarkdownHelpers.extract_attr, 671 | mk_block = MarkdownHelpers.mk_block, 672 | isEmpty = MarkdownHelpers.isEmpty, 673 | inline_until_char = DialectHelpers.inline_until_char; 674 | 675 | /** 676 | * Gruber dialect 677 | * 678 | * The default dialect that follows the rules set out by John Gruber's 679 | * markdown.pl as closely as possible. Well actually we follow the behaviour of 680 | * that script which in some places is not exactly what the syntax web page 681 | * says. 682 | **/ 683 | var Gruber = { 684 | block: { 685 | atxHeader: function atxHeader( block, next ) { 686 | var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ ); 687 | 688 | if ( !m ) 689 | return undefined; 690 | 691 | var header = [ "header", { level: m[ 1 ].length } ]; 692 | Array.prototype.push.apply(header, this.processInline(m[ 2 ])); 693 | 694 | if ( m[0].length < block.length ) 695 | next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); 696 | 697 | return [ header ]; 698 | }, 699 | 700 | setextHeader: function setextHeader( block, next ) { 701 | var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ ); 702 | 703 | if ( !m ) 704 | return undefined; 705 | 706 | var level = ( m[ 2 ] === "=" ) ? 1 : 2, 707 | header = [ "header", { level : level }, m[ 1 ] ]; 708 | 709 | if ( m[0].length < block.length ) 710 | next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); 711 | 712 | return [ header ]; 713 | }, 714 | 715 | code: function code( block, next ) { 716 | // | Foo 717 | // |bar 718 | // should be a code block followed by a paragraph. Fun 719 | // 720 | // There might also be adjacent code block to merge. 721 | 722 | var ret = [], 723 | re = /^(?: {0,3}\t| {4})(.*)\n?/; 724 | 725 | // 4 spaces + content 726 | if ( !block.match( re ) ) 727 | return undefined; 728 | 729 | block_search: 730 | do { 731 | // Now pull out the rest of the lines 732 | var b = this.loop_re_over_block( 733 | re, block.valueOf(), function( m ) { ret.push( m[1] ); } ); 734 | 735 | if ( b.length ) { 736 | // Case alluded to in first comment. push it back on as a new block 737 | next.unshift( mk_block(b, block.trailing) ); 738 | break block_search; 739 | } 740 | else if ( next.length ) { 741 | // Check the next block - it might be code too 742 | if ( !next[0].match( re ) ) 743 | break block_search; 744 | 745 | // Pull how how many blanks lines follow - minus two to account for .join 746 | ret.push ( block.trailing.replace(/[^\n]/g, "").substring(2) ); 747 | 748 | block = next.shift(); 749 | } 750 | else { 751 | break block_search; 752 | } 753 | } while ( true ); 754 | 755 | return [ [ "code_block", ret.join("\n") ] ]; 756 | }, 757 | 758 | horizRule: function horizRule( block, next ) { 759 | // this needs to find any hr in the block to handle abutting blocks 760 | var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ ); 761 | 762 | if ( !m ) 763 | return undefined; 764 | 765 | var jsonml = [ [ "hr" ] ]; 766 | 767 | // if there's a leading abutting block, process it 768 | if ( m[ 1 ] ) { 769 | var contained = mk_block( m[ 1 ], "", block.lineNumber ); 770 | jsonml.unshift.apply( jsonml, this.toTree( contained, [] ) ); 771 | } 772 | 773 | // if there's a trailing abutting block, stick it into next 774 | if ( m[ 3 ] ) 775 | next.unshift( mk_block( m[ 3 ], block.trailing, block.lineNumber + 1 ) ); 776 | 777 | return jsonml; 778 | }, 779 | 780 | // There are two types of lists. Tight and loose. Tight lists have no whitespace 781 | // between the items (and result in text just in the
  • ) and loose lists, 782 | // which have an empty line between list items, resulting in (one or more) 783 | // paragraphs inside the
  • . 784 | // 785 | // There are all sorts weird edge cases about the original markdown.pl's 786 | // handling of lists: 787 | // 788 | // * Nested lists are supposed to be indented by four chars per level. But 789 | // if they aren't, you can get a nested list by indenting by less than 790 | // four so long as the indent doesn't match an indent of an existing list 791 | // item in the 'nest stack'. 792 | // 793 | // * The type of the list (bullet or number) is controlled just by the 794 | // first item at the indent. Subsequent changes are ignored unless they 795 | // are for nested lists 796 | // 797 | lists: (function( ) { 798 | // Use a closure to hide a few variables. 799 | var any_list = "[*+-]|\\d+\\.", 800 | bullet_list = /[*+-]/, 801 | // Capture leading indent as it matters for determining nested lists. 802 | is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ), 803 | indent_re = "(?: {0,3}\\t| {4})"; 804 | 805 | // TODO: Cache this regexp for certain depths. 806 | // Create a regexp suitable for matching an li for a given stack depth 807 | function regex_for_depth( depth ) { 808 | 809 | return new RegExp( 810 | // m[1] = indent, m[2] = list_type 811 | "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" + 812 | // m[3] = cont 813 | "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})" 814 | ); 815 | } 816 | function expand_tab( input ) { 817 | return input.replace( / {0,3}\t/g, " " ); 818 | } 819 | 820 | // Add inline content `inline` to `li`. inline comes from processInline 821 | // so is an array of content 822 | function add(li, loose, inline, nl) { 823 | if ( loose ) { 824 | li.push( [ "para" ].concat(inline) ); 825 | return; 826 | } 827 | // Hmmm, should this be any block level element or just paras? 828 | var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] === "para" 829 | ? li[li.length -1] 830 | : li; 831 | 832 | // If there is already some content in this list, add the new line in 833 | if ( nl && li.length > 1 ) 834 | inline.unshift(nl); 835 | 836 | for ( var i = 0; i < inline.length; i++ ) { 837 | var what = inline[i], 838 | is_str = typeof what === "string"; 839 | if ( is_str && add_to.length > 1 && typeof add_to[add_to.length-1] === "string" ) 840 | add_to[ add_to.length-1 ] += what; 841 | else 842 | add_to.push( what ); 843 | } 844 | } 845 | 846 | // contained means have an indent greater than the current one. On 847 | // *every* line in the block 848 | function get_contained_blocks( depth, blocks ) { 849 | 850 | var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ), 851 | replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"), 852 | ret = []; 853 | 854 | while ( blocks.length > 0 ) { 855 | if ( re.exec( blocks[0] ) ) { 856 | var b = blocks.shift(), 857 | // Now remove that indent 858 | x = b.replace( replace, ""); 859 | 860 | ret.push( mk_block( x, b.trailing, b.lineNumber ) ); 861 | } 862 | else 863 | break; 864 | } 865 | return ret; 866 | } 867 | 868 | // passed to stack.forEach to turn list items up the stack into paras 869 | function paragraphify(s, i, stack) { 870 | var list = s.list; 871 | var last_li = list[list.length-1]; 872 | 873 | if ( last_li[1] instanceof Array && last_li[1][0] === "para" ) 874 | return; 875 | if ( i + 1 === stack.length ) { 876 | // Last stack frame 877 | // Keep the same array, but replace the contents 878 | last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ) ); 879 | } 880 | else { 881 | var sublist = last_li.pop(); 882 | last_li.push( ["para"].concat( last_li.splice(1, last_li.length - 1) ), sublist ); 883 | } 884 | } 885 | 886 | // The matcher function 887 | return function( block, next ) { 888 | var m = block.match( is_list_re ); 889 | if ( !m ) 890 | return undefined; 891 | 892 | function make_list( m ) { 893 | var list = bullet_list.exec( m[2] ) 894 | ? ["bulletlist"] 895 | : ["numberlist"]; 896 | 897 | stack.push( { list: list, indent: m[1] } ); 898 | return list; 899 | } 900 | 901 | 902 | var stack = [], // Stack of lists for nesting. 903 | list = make_list( m ), 904 | last_li, 905 | loose = false, 906 | ret = [ stack[0].list ], 907 | i; 908 | 909 | // Loop to search over block looking for inner block elements and loose lists 910 | loose_search: 911 | while ( true ) { 912 | // Split into lines preserving new lines at end of line 913 | var lines = block.split( /(?=\n)/ ); 914 | 915 | // We have to grab all lines for a li and call processInline on them 916 | // once as there are some inline things that can span lines. 917 | var li_accumulate = "", nl = ""; 918 | 919 | // Loop over the lines in this block looking for tight lists. 920 | tight_search: 921 | for ( var line_no = 0; line_no < lines.length; line_no++ ) { 922 | nl = ""; 923 | var l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; }); 924 | 925 | 926 | // TODO: really should cache this 927 | var line_re = regex_for_depth( stack.length ); 928 | 929 | m = l.match( line_re ); 930 | //print( "line:", uneval(l), "\nline match:", uneval(m) ); 931 | 932 | // We have a list item 933 | if ( m[1] !== undefined ) { 934 | // Process the previous list item, if any 935 | if ( li_accumulate.length ) { 936 | add( last_li, loose, this.processInline( li_accumulate ), nl ); 937 | // Loose mode will have been dealt with. Reset it 938 | loose = false; 939 | li_accumulate = ""; 940 | } 941 | 942 | m[1] = expand_tab( m[1] ); 943 | var wanted_depth = Math.floor(m[1].length/4)+1; 944 | //print( "want:", wanted_depth, "stack:", stack.length); 945 | if ( wanted_depth > stack.length ) { 946 | // Deep enough for a nested list outright 947 | //print ( "new nested list" ); 948 | list = make_list( m ); 949 | last_li.push( list ); 950 | last_li = list[1] = [ "listitem" ]; 951 | } 952 | else { 953 | // We aren't deep enough to be strictly a new level. This is 954 | // where Md.pl goes nuts. If the indent matches a level in the 955 | // stack, put it there, else put it one deeper then the 956 | // wanted_depth deserves. 957 | var found = false; 958 | for ( i = 0; i < stack.length; i++ ) { 959 | if ( stack[ i ].indent !== m[1] ) 960 | continue; 961 | 962 | list = stack[ i ].list; 963 | stack.splice( i+1, stack.length - (i+1) ); 964 | found = true; 965 | break; 966 | } 967 | 968 | if (!found) { 969 | //print("not found. l:", uneval(l)); 970 | wanted_depth++; 971 | if ( wanted_depth <= stack.length ) { 972 | stack.splice(wanted_depth, stack.length - wanted_depth); 973 | //print("Desired depth now", wanted_depth, "stack:", stack.length); 974 | list = stack[wanted_depth-1].list; 975 | //print("list:", uneval(list) ); 976 | } 977 | else { 978 | //print ("made new stack for messy indent"); 979 | list = make_list(m); 980 | last_li.push(list); 981 | } 982 | } 983 | 984 | //print( uneval(list), "last", list === stack[stack.length-1].list ); 985 | last_li = [ "listitem" ]; 986 | list.push(last_li); 987 | } // end depth of shenegains 988 | nl = ""; 989 | } 990 | 991 | // Add content 992 | if ( l.length > m[0].length ) 993 | li_accumulate += nl + l.substr( m[0].length ); 994 | } // tight_search 995 | 996 | if ( li_accumulate.length ) { 997 | add( last_li, loose, this.processInline( li_accumulate ), nl ); 998 | // Loose mode will have been dealt with. Reset it 999 | loose = false; 1000 | li_accumulate = ""; 1001 | } 1002 | 1003 | // Look at the next block - we might have a loose list. Or an extra 1004 | // paragraph for the current li 1005 | var contained = get_contained_blocks( stack.length, next ); 1006 | 1007 | // Deal with code blocks or properly nested lists 1008 | if ( contained.length > 0 ) { 1009 | // Make sure all listitems up the stack are paragraphs 1010 | forEach( stack, paragraphify, this); 1011 | 1012 | last_li.push.apply( last_li, this.toTree( contained, [] ) ); 1013 | } 1014 | 1015 | var next_block = next[0] && next[0].valueOf() || ""; 1016 | 1017 | if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) { 1018 | block = next.shift(); 1019 | 1020 | // Check for an HR following a list: features/lists/hr_abutting 1021 | var hr = this.dialect.block.horizRule( block, next ); 1022 | 1023 | if ( hr ) { 1024 | ret.push.apply(ret, hr); 1025 | break; 1026 | } 1027 | 1028 | // Make sure all listitems up the stack are paragraphs 1029 | forEach( stack, paragraphify, this); 1030 | 1031 | loose = true; 1032 | continue loose_search; 1033 | } 1034 | break; 1035 | } // loose_search 1036 | 1037 | return ret; 1038 | }; 1039 | })(), 1040 | 1041 | blockquote: function blockquote( block, next ) { 1042 | if ( !block.match( /^>/m ) ) 1043 | return undefined; 1044 | 1045 | var jsonml = []; 1046 | 1047 | // separate out the leading abutting block, if any. I.e. in this case: 1048 | // 1049 | // a 1050 | // > b 1051 | // 1052 | if ( block[ 0 ] !== ">" ) { 1053 | var lines = block.split( /\n/ ), 1054 | prev = [], 1055 | line_no = block.lineNumber; 1056 | 1057 | // keep shifting lines until you find a crotchet 1058 | while ( lines.length && lines[ 0 ][ 0 ] !== ">" ) { 1059 | prev.push( lines.shift() ); 1060 | line_no++; 1061 | } 1062 | 1063 | var abutting = mk_block( prev.join( "\n" ), "\n", block.lineNumber ); 1064 | jsonml.push.apply( jsonml, this.processBlock( abutting, [] ) ); 1065 | // reassemble new block of just block quotes! 1066 | block = mk_block( lines.join( "\n" ), block.trailing, line_no ); 1067 | } 1068 | 1069 | 1070 | // if the next block is also a blockquote merge it in 1071 | while ( next.length && next[ 0 ][ 0 ] === ">" ) { 1072 | var b = next.shift(); 1073 | block = mk_block( block + block.trailing + b, b.trailing, block.lineNumber ); 1074 | } 1075 | 1076 | // Strip off the leading "> " and re-process as a block. 1077 | var input = block.replace( /^> ?/gm, "" ), 1078 | old_tree = this.tree, 1079 | processedBlock = this.toTree( input, [ "blockquote" ] ), 1080 | attr = extract_attr( processedBlock ); 1081 | 1082 | // If any link references were found get rid of them 1083 | if ( attr && attr.references ) { 1084 | delete attr.references; 1085 | // And then remove the attribute object if it's empty 1086 | if ( isEmpty( attr ) ) 1087 | processedBlock.splice( 1, 1 ); 1088 | } 1089 | 1090 | jsonml.push( processedBlock ); 1091 | return jsonml; 1092 | }, 1093 | 1094 | referenceDefn: function referenceDefn( block, next) { 1095 | var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/; 1096 | // interesting matches are [ , ref_id, url, , title, title ] 1097 | 1098 | if ( !block.match(re) ) 1099 | return undefined; 1100 | 1101 | // make an attribute node if it doesn't exist 1102 | if ( !extract_attr( this.tree ) ) 1103 | this.tree.splice( 1, 0, {} ); 1104 | 1105 | var attrs = extract_attr( this.tree ); 1106 | 1107 | // make a references hash if it doesn't exist 1108 | if ( attrs.references === undefined ) 1109 | attrs.references = {}; 1110 | 1111 | var b = this.loop_re_over_block(re, block, function( m ) { 1112 | 1113 | if ( m[2] && m[2][0] === "<" && m[2][m[2].length-1] === ">" ) 1114 | m[2] = m[2].substring( 1, m[2].length - 1 ); 1115 | 1116 | var ref = attrs.references[ m[1].toLowerCase() ] = { 1117 | href: m[2] 1118 | }; 1119 | 1120 | if ( m[4] !== undefined ) 1121 | ref.title = m[4]; 1122 | else if ( m[5] !== undefined ) 1123 | ref.title = m[5]; 1124 | 1125 | } ); 1126 | 1127 | if ( b.length ) 1128 | next.unshift( mk_block( b, block.trailing ) ); 1129 | 1130 | return []; 1131 | }, 1132 | 1133 | para: function para( block ) { 1134 | // everything's a para! 1135 | return [ ["para"].concat( this.processInline( block ) ) ]; 1136 | } 1137 | }, 1138 | 1139 | inline: { 1140 | 1141 | __oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) { 1142 | var m, 1143 | res; 1144 | 1145 | patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__; 1146 | var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" ); 1147 | 1148 | m = re.exec( text ); 1149 | if (!m) { 1150 | // Just boring text 1151 | return [ text.length, text ]; 1152 | } 1153 | else if ( m[1] ) { 1154 | // Some un-interesting text matched. Return that first 1155 | return [ m[1].length, m[1] ]; 1156 | } 1157 | 1158 | var res; 1159 | if ( m[2] in this.dialect.inline ) { 1160 | res = this.dialect.inline[ m[2] ].call( 1161 | this, 1162 | text.substr( m.index ), m, previous_nodes || [] ); 1163 | } 1164 | // Default for now to make dev easier. just slurp special and output it. 1165 | res = res || [ m[2].length, m[2] ]; 1166 | return res; 1167 | }, 1168 | 1169 | __call__: function inline( text, patterns ) { 1170 | 1171 | var out = [], 1172 | res; 1173 | 1174 | function add(x) { 1175 | //D:self.debug(" adding output", uneval(x)); 1176 | if ( typeof x === "string" && typeof out[out.length-1] === "string" ) 1177 | out[ out.length-1 ] += x; 1178 | else 1179 | out.push(x); 1180 | } 1181 | 1182 | while ( text.length > 0 ) { 1183 | res = this.dialect.inline.__oneElement__.call(this, text, patterns, out ); 1184 | text = text.substr( res.shift() ); 1185 | forEach(res, add ); 1186 | } 1187 | 1188 | return out; 1189 | }, 1190 | 1191 | // These characters are intersting elsewhere, so have rules for them so that 1192 | // chunks of plain text blocks don't include them 1193 | "]": function () {}, 1194 | "}": function () {}, 1195 | 1196 | __escape__ : /^\\[\\`\*_{}\[\]()#\+.!\-]/, 1197 | 1198 | "\\": function escaped( text ) { 1199 | // [ length of input processed, node/children to add... ] 1200 | // Only esacape: \ ` * _ { } [ ] ( ) # * + - . ! 1201 | if ( this.dialect.inline.__escape__.exec( text ) ) 1202 | return [ 2, text.charAt( 1 ) ]; 1203 | else 1204 | // Not an esacpe 1205 | return [ 1, "\\" ]; 1206 | }, 1207 | 1208 | "![": function image( text ) { 1209 | 1210 | // Unlike images, alt text is plain text only. no other elements are 1211 | // allowed in there 1212 | 1213 | // ![Alt text](/path/to/img.jpg "Optional title") 1214 | // 1 2 3 4 <--- captures 1215 | var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*([^")]*?)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ ); 1216 | 1217 | if ( m ) { 1218 | if ( m[2] && m[2][0] === "<" && m[2][m[2].length-1] === ">" ) 1219 | m[2] = m[2].substring( 1, m[2].length - 1 ); 1220 | 1221 | m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0]; 1222 | 1223 | var attrs = { alt: m[1], href: m[2] || "" }; 1224 | if ( m[4] !== undefined) 1225 | attrs.title = m[4]; 1226 | 1227 | return [ m[0].length, [ "img", attrs ] ]; 1228 | } 1229 | 1230 | // ![Alt text][id] 1231 | m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ ); 1232 | 1233 | if ( m ) { 1234 | // We can't check if the reference is known here as it likely wont be 1235 | // found till after. Check it in md tree->hmtl tree conversion 1236 | return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ]; 1237 | } 1238 | 1239 | // Just consume the '![' 1240 | return [ 2, "![" ]; 1241 | }, 1242 | 1243 | "[": function link( text ) { 1244 | 1245 | var orig = String(text); 1246 | // Inline content is possible inside `link text` 1247 | var res = inline_until_char.call( this, text.substr(1), "]" ); 1248 | 1249 | // No closing ']' found. Just consume the [ 1250 | if ( !res ) 1251 | return [ 1, "[" ]; 1252 | 1253 | var consumed = 1 + res[ 0 ], 1254 | children = res[ 1 ], 1255 | link, 1256 | attrs; 1257 | 1258 | // At this point the first [...] has been parsed. See what follows to find 1259 | // out which kind of link we are (reference or direct url) 1260 | text = text.substr( consumed ); 1261 | 1262 | // [link text](/path/to/img.jpg "Optional title") 1263 | // 1 2 3 <--- captures 1264 | // This will capture up to the last paren in the block. We then pull 1265 | // back based on if there a matching ones in the url 1266 | // ([here](/url/(test)) 1267 | // The parens have to be balanced 1268 | var m = text.match( /^\s*\([ \t]*([^"']*)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ ); 1269 | if ( m ) { 1270 | var url = m[1]; 1271 | consumed += m[0].length; 1272 | 1273 | if ( url && url[0] === "<" && url[url.length-1] === ">" ) 1274 | url = url.substring( 1, url.length - 1 ); 1275 | 1276 | // If there is a title we don't have to worry about parens in the url 1277 | if ( !m[3] ) { 1278 | var open_parens = 1; // One open that isn't in the capture 1279 | for ( var len = 0; len < url.length; len++ ) { 1280 | switch ( url[len] ) { 1281 | case "(": 1282 | open_parens++; 1283 | break; 1284 | case ")": 1285 | if ( --open_parens === 0) { 1286 | consumed -= url.length - len; 1287 | url = url.substring(0, len); 1288 | } 1289 | break; 1290 | } 1291 | } 1292 | } 1293 | 1294 | // Process escapes only 1295 | url = this.dialect.inline.__call__.call( this, url, /\\/ )[0]; 1296 | 1297 | attrs = { href: url || "" }; 1298 | if ( m[3] !== undefined) 1299 | attrs.title = m[3]; 1300 | 1301 | link = [ "link", attrs ].concat( children ); 1302 | return [ consumed, link ]; 1303 | } 1304 | 1305 | // [Alt text][id] 1306 | // [Alt text] [id] 1307 | m = text.match( /^\s*\[(.*?)\]/ ); 1308 | 1309 | if ( m ) { 1310 | 1311 | consumed += m[ 0 ].length; 1312 | 1313 | // [links][] uses links as its reference 1314 | attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) }; 1315 | 1316 | link = [ "link_ref", attrs ].concat( children ); 1317 | 1318 | // We can't check if the reference is known here as it likely wont be 1319 | // found till after. Check it in md tree->hmtl tree conversion. 1320 | // Store the original so that conversion can revert if the ref isn't found. 1321 | return [ consumed, link ]; 1322 | } 1323 | 1324 | // [id] 1325 | // Only if id is plain (no formatting.) 1326 | if ( children.length === 1 && typeof children[0] === "string" ) { 1327 | 1328 | attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) }; 1329 | link = [ "link_ref", attrs, children[0] ]; 1330 | return [ consumed, link ]; 1331 | } 1332 | 1333 | // Just consume the "[" 1334 | return [ 1, "[" ]; 1335 | }, 1336 | 1337 | 1338 | "<": function autoLink( text ) { 1339 | var m; 1340 | 1341 | if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) !== null ) { 1342 | if ( m[3] ) 1343 | return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ]; 1344 | else if ( m[2] === "mailto" ) 1345 | return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ]; 1346 | else 1347 | return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ]; 1348 | } 1349 | 1350 | return [ 1, "<" ]; 1351 | }, 1352 | 1353 | "`": function inlineCode( text ) { 1354 | // Inline code block. as many backticks as you like to start it 1355 | // Always skip over the opening ticks. 1356 | var m = text.match( /(`+)(([\s\S]*?)\1)/ ); 1357 | 1358 | if ( m && m[2] ) 1359 | return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ]; 1360 | else { 1361 | // TODO: No matching end code found - warn! 1362 | return [ 1, "`" ]; 1363 | } 1364 | }, 1365 | 1366 | " \n": function lineBreak() { 1367 | return [ 3, [ "linebreak" ] ]; 1368 | } 1369 | 1370 | } 1371 | }; 1372 | 1373 | // Meta Helper/generator method for em and strong handling 1374 | function strong_em( tag, md ) { 1375 | 1376 | var state_slot = tag + "_state", 1377 | other_slot = tag === "strong" ? "em_state" : "strong_state"; 1378 | 1379 | function CloseTag(len) { 1380 | this.len_after = len; 1381 | this.name = "close_" + md; 1382 | } 1383 | 1384 | return function ( text ) { 1385 | 1386 | if ( this[state_slot][0] === md ) { 1387 | // Most recent em is of this type 1388 | //D:this.debug("closing", md); 1389 | this[state_slot].shift(); 1390 | 1391 | // "Consume" everything to go back to the recrusion in the else-block below 1392 | return[ text.length, new CloseTag(text.length-md.length) ]; 1393 | } 1394 | else { 1395 | // Store a clone of the em/strong states 1396 | var other = this[other_slot].slice(), 1397 | state = this[state_slot].slice(); 1398 | 1399 | this[state_slot].unshift(md); 1400 | 1401 | //D:this.debug_indent += " "; 1402 | 1403 | // Recurse 1404 | var res = this.processInline( text.substr( md.length ) ); 1405 | //D:this.debug_indent = this.debug_indent.substr(2); 1406 | 1407 | var last = res[res.length - 1]; 1408 | 1409 | //D:this.debug("processInline from", tag + ": ", uneval( res ) ); 1410 | 1411 | var check = this[state_slot].shift(); 1412 | if ( last instanceof CloseTag ) { 1413 | res.pop(); 1414 | // We matched! Huzzah. 1415 | var consumed = text.length - last.len_after; 1416 | return [ consumed, [ tag ].concat(res) ]; 1417 | } 1418 | else { 1419 | // Restore the state of the other kind. We might have mistakenly closed it. 1420 | this[other_slot] = other; 1421 | this[state_slot] = state; 1422 | 1423 | // We can't reuse the processed result as it could have wrong parsing contexts in it. 1424 | return [ md.length, md ]; 1425 | } 1426 | } 1427 | }; // End returned function 1428 | } 1429 | 1430 | Gruber.inline["**"] = strong_em("strong", "**"); 1431 | Gruber.inline["__"] = strong_em("strong", "__"); 1432 | Gruber.inline["*"] = strong_em("em", "*"); 1433 | Gruber.inline["_"] = strong_em("em", "_"); 1434 | 1435 | Markdown.dialects.Gruber = Gruber; 1436 | Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block ); 1437 | Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline ); 1438 | 1439 | 1440 | 1441 | var Maruku = DialectHelpers.subclassDialect( Gruber ), 1442 | extract_attr = MarkdownHelpers.extract_attr, 1443 | forEach = MarkdownHelpers.forEach; 1444 | 1445 | Maruku.processMetaHash = function processMetaHash( meta_string ) { 1446 | var meta = split_meta_hash( meta_string ), 1447 | attr = {}; 1448 | 1449 | for ( var i = 0; i < meta.length; ++i ) { 1450 | // id: #foo 1451 | if ( /^#/.test( meta[ i ] ) ) 1452 | attr.id = meta[ i ].substring( 1 ); 1453 | // class: .foo 1454 | else if ( /^\./.test( meta[ i ] ) ) { 1455 | // if class already exists, append the new one 1456 | if ( attr["class"] ) 1457 | attr["class"] = attr["class"] + meta[ i ].replace( /./, " " ); 1458 | else 1459 | attr["class"] = meta[ i ].substring( 1 ); 1460 | } 1461 | // attribute: foo=bar 1462 | else if ( /\=/.test( meta[ i ] ) ) { 1463 | var s = meta[ i ].split( /\=/ ); 1464 | attr[ s[ 0 ] ] = s[ 1 ]; 1465 | } 1466 | } 1467 | 1468 | return attr; 1469 | }; 1470 | 1471 | function split_meta_hash( meta_string ) { 1472 | var meta = meta_string.split( "" ), 1473 | parts = [ "" ], 1474 | in_quotes = false; 1475 | 1476 | while ( meta.length ) { 1477 | var letter = meta.shift(); 1478 | switch ( letter ) { 1479 | case " " : 1480 | // if we're in a quoted section, keep it 1481 | if ( in_quotes ) 1482 | parts[ parts.length - 1 ] += letter; 1483 | // otherwise make a new part 1484 | else 1485 | parts.push( "" ); 1486 | break; 1487 | case "'" : 1488 | case '"' : 1489 | // reverse the quotes and move straight on 1490 | in_quotes = !in_quotes; 1491 | break; 1492 | case "\\" : 1493 | // shift off the next letter to be used straight away. 1494 | // it was escaped so we'll keep it whatever it is 1495 | letter = meta.shift(); 1496 | /* falls through */ 1497 | default : 1498 | parts[ parts.length - 1 ] += letter; 1499 | break; 1500 | } 1501 | } 1502 | 1503 | return parts; 1504 | } 1505 | 1506 | Maruku.block.document_meta = function document_meta( block ) { 1507 | // we're only interested in the first block 1508 | if ( block.lineNumber > 1 ) 1509 | return undefined; 1510 | 1511 | // document_meta blocks consist of one or more lines of `Key: Value\n` 1512 | if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) 1513 | return undefined; 1514 | 1515 | // make an attribute node if it doesn't exist 1516 | if ( !extract_attr( this.tree ) ) 1517 | this.tree.splice( 1, 0, {} ); 1518 | 1519 | var pairs = block.split( /\n/ ); 1520 | for ( var p in pairs ) { 1521 | var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ), 1522 | key = m[ 1 ].toLowerCase(), 1523 | value = m[ 2 ]; 1524 | 1525 | this.tree[ 1 ][ key ] = value; 1526 | } 1527 | 1528 | // document_meta produces no content! 1529 | return []; 1530 | }; 1531 | 1532 | Maruku.block.block_meta = function block_meta( block ) { 1533 | // check if the last line of the block is an meta hash 1534 | var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ ); 1535 | if ( !m ) 1536 | return undefined; 1537 | 1538 | // process the meta hash 1539 | var attr = this.dialect.processMetaHash( m[ 2 ] ), 1540 | hash; 1541 | 1542 | // if we matched ^ then we need to apply meta to the previous block 1543 | if ( m[ 1 ] === "" ) { 1544 | var node = this.tree[ this.tree.length - 1 ]; 1545 | hash = extract_attr( node ); 1546 | 1547 | // if the node is a string (rather than JsonML), bail 1548 | if ( typeof node === "string" ) 1549 | return undefined; 1550 | 1551 | // create the attribute hash if it doesn't exist 1552 | if ( !hash ) { 1553 | hash = {}; 1554 | node.splice( 1, 0, hash ); 1555 | } 1556 | 1557 | // add the attributes in 1558 | for ( var a in attr ) 1559 | hash[ a ] = attr[ a ]; 1560 | 1561 | // return nothing so the meta hash is removed 1562 | return []; 1563 | } 1564 | 1565 | // pull the meta hash off the block and process what's left 1566 | var b = block.replace( /\n.*$/, "" ), 1567 | result = this.processBlock( b, [] ); 1568 | 1569 | // get or make the attributes hash 1570 | hash = extract_attr( result[ 0 ] ); 1571 | if ( !hash ) { 1572 | hash = {}; 1573 | result[ 0 ].splice( 1, 0, hash ); 1574 | } 1575 | 1576 | // attach the attributes to the block 1577 | for ( var a in attr ) 1578 | hash[ a ] = attr[ a ]; 1579 | 1580 | return result; 1581 | }; 1582 | 1583 | Maruku.block.definition_list = function definition_list( block, next ) { 1584 | // one or more terms followed by one or more definitions, in a single block 1585 | var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/, 1586 | list = [ "dl" ], 1587 | i, m; 1588 | 1589 | // see if we're dealing with a tight or loose block 1590 | if ( ( m = block.match( tight ) ) ) { 1591 | // pull subsequent tight DL blocks out of `next` 1592 | var blocks = [ block ]; 1593 | while ( next.length && tight.exec( next[ 0 ] ) ) 1594 | blocks.push( next.shift() ); 1595 | 1596 | for ( var b = 0; b < blocks.length; ++b ) { 1597 | var m = blocks[ b ].match( tight ), 1598 | terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ), 1599 | defns = m[ 2 ].split( /\n:\s+/ ); 1600 | 1601 | // print( uneval( m ) ); 1602 | 1603 | for ( i = 0; i < terms.length; ++i ) 1604 | list.push( [ "dt", terms[ i ] ] ); 1605 | 1606 | for ( i = 0; i < defns.length; ++i ) { 1607 | // run inline processing over the definition 1608 | list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) ); 1609 | } 1610 | } 1611 | } 1612 | else { 1613 | return undefined; 1614 | } 1615 | 1616 | return [ list ]; 1617 | }; 1618 | 1619 | // splits on unescaped instances of @ch. If @ch is not a character the result 1620 | // can be unpredictable 1621 | 1622 | Maruku.block.table = function table ( block ) { 1623 | 1624 | var _split_on_unescaped = function( s, ch ) { 1625 | ch = ch || '\\s'; 1626 | if ( ch.match(/^[\\|\[\]{}?*.+^$]$/) ) 1627 | ch = '\\' + ch; 1628 | var res = [ ], 1629 | r = new RegExp('^((?:\\\\.|[^\\\\' + ch + '])*)' + ch + '(.*)'), 1630 | m; 1631 | while ( ( m = s.match( r ) ) ) { 1632 | res.push( m[1] ); 1633 | s = m[2]; 1634 | } 1635 | res.push(s); 1636 | return res; 1637 | }; 1638 | 1639 | var leading_pipe = /^ {0,3}\|(.+)\n {0,3}\|\s*([\-:]+[\-| :]*)\n((?:\s*\|.*(?:\n|$))*)(?=\n|$)/, 1640 | // find at least an unescaped pipe in each line 1641 | no_leading_pipe = /^ {0,3}(\S(?:\\.|[^\\|])*\|.*)\n {0,3}([\-:]+\s*\|[\-| :]*)\n((?:(?:\\.|[^\\|])*\|.*(?:\n|$))*)(?=\n|$)/, 1642 | i, 1643 | m; 1644 | if ( ( m = block.match( leading_pipe ) ) ) { 1645 | // remove leading pipes in contents 1646 | // (header and horizontal rule already have the leading pipe left out) 1647 | m[3] = m[3].replace(/^\s*\|/gm, ''); 1648 | } else if ( ! ( m = block.match( no_leading_pipe ) ) ) { 1649 | return undefined; 1650 | } 1651 | 1652 | var table = [ "table", [ "thead", [ "tr" ] ], [ "tbody" ] ]; 1653 | 1654 | // remove trailing pipes, then split on pipes 1655 | // (no escaped pipes are allowed in horizontal rule) 1656 | m[2] = m[2].replace(/\|\s*$/, '').split('|'); 1657 | 1658 | // process alignment 1659 | var html_attrs = [ ]; 1660 | forEach (m[2], function (s) { 1661 | if (s.match(/^\s*-+:\s*$/)) 1662 | html_attrs.push({align: "right"}); 1663 | else if (s.match(/^\s*:-+\s*$/)) 1664 | html_attrs.push({align: "left"}); 1665 | else if (s.match(/^\s*:-+:\s*$/)) 1666 | html_attrs.push({align: "center"}); 1667 | else 1668 | html_attrs.push({}); 1669 | }); 1670 | 1671 | // now for the header, avoid escaped pipes 1672 | m[1] = _split_on_unescaped(m[1].replace(/\|\s*$/, ''), '|'); 1673 | for (i = 0; i < m[1].length; i++) { 1674 | table[1][1].push(['th', html_attrs[i] || {}].concat( 1675 | this.processInline(m[1][i].trim()))); 1676 | } 1677 | 1678 | // now for body contents 1679 | forEach (m[3].replace(/\|\s*$/mg, '').split('\n'), function (row) { 1680 | var html_row = ['tr']; 1681 | row = _split_on_unescaped(row, '|'); 1682 | for (i = 0; i < row.length; i++) 1683 | html_row.push(['td', html_attrs[i] || {}].concat(this.processInline(row[i].trim()))); 1684 | table[2].push(html_row); 1685 | }, this); 1686 | 1687 | return [table]; 1688 | }; 1689 | 1690 | Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) { 1691 | if ( !out.length ) 1692 | return [ 2, "{:" ]; 1693 | 1694 | // get the preceeding element 1695 | var before = out[ out.length - 1 ]; 1696 | 1697 | if ( typeof before === "string" ) 1698 | return [ 2, "{:" ]; 1699 | 1700 | // match a meta hash 1701 | var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ ); 1702 | 1703 | // no match, false alarm 1704 | if ( !m ) 1705 | return [ 2, "{:" ]; 1706 | 1707 | // attach the attributes to the preceeding element 1708 | var meta = this.dialect.processMetaHash( m[ 1 ] ), 1709 | attr = extract_attr( before ); 1710 | 1711 | if ( !attr ) { 1712 | attr = {}; 1713 | before.splice( 1, 0, attr ); 1714 | } 1715 | 1716 | for ( var k in meta ) 1717 | attr[ k ] = meta[ k ]; 1718 | 1719 | // cut out the string and replace it with nothing 1720 | return [ m[ 0 ].length, "" ]; 1721 | }; 1722 | 1723 | 1724 | Markdown.dialects.Maruku = Maruku; 1725 | Markdown.dialects.Maruku.inline.__escape__ = /^\\[\\`\*_{}\[\]()#\+.!\-|:]/; 1726 | Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block ); 1727 | Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline ); 1728 | 1729 | 1730 | // Include all our depndencies and; 1731 | expose.Markdown = Markdown; 1732 | expose.parse = Markdown.parse; 1733 | expose.toHTML = Markdown.toHTML; 1734 | expose.toHTMLTree = Markdown.toHTMLTree; 1735 | expose.renderJsonML = Markdown.renderJsonML; 1736 | 1737 | })(function() { 1738 | window.markdown = {}; 1739 | return window.markdown; 1740 | }()); -------------------------------------------------------------------------------- /js/mddoc.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | var converter = new showdown.Converter() 4 | var alertnum = 1 5 | var db = new PouchDB('md') 6 | 7 | var createAlert = function(title, message, keep) { 8 | console.log(title, message, keep) 9 | /* var num = alertnum++; 10 | var html = "
    \n" + 11 | "\n" + 13 | "" + title + " "+message + 14 | "
    "; 15 | $('#alerts').html( $('#alerts').html() + html); 16 | if(keep && keep===true) { 17 | 18 | } else { 19 | setTimeout(function() { 20 | $('#alert' + num).alert('close'); 21 | }, 5000); 22 | }*/ 23 | }; 24 | 25 | var getTS = function() { 26 | return Math.round(+new Date()/1000); 27 | }; 28 | 29 | var map = function(doc) { 30 | if(doc.doc_id) { 31 | emit(doc.ts, null); 32 | } 33 | }; 34 | 35 | var map2 = function(doc) { 36 | if(doc.doc_id) { 37 | emit(doc.doc_id, doc._rev); 38 | } 39 | }; 40 | 41 | var getDocList = async function() { 42 | var retval = { }; 43 | try { 44 | const data = await db.query( map, { descending: true, include_docs:true}) 45 | for(var i in data.rows) { 46 | var doc = data.rows[i].doc; 47 | if(Object.keys(retval).indexOf(doc.doc_id) == -1) { 48 | retval[doc.doc_id] = doc; 49 | } 50 | } 51 | var thedocs = [] 52 | for(var i in retval) { 53 | thedocs.push(retval[i]); 54 | } 55 | thedocs.sort(function(a, b){return b.ts-a.ts}); 56 | return thedocs 57 | } catch (err) { 58 | return err 59 | } 60 | } 61 | 62 | var app = new Vue({ 63 | el: '#app', 64 | data: { 65 | markdown: '', 66 | docName: '', 67 | lastSaved: '', 68 | message: 'Hello Vue!', 69 | showJumbo : true, 70 | showPreview: true, 71 | docId: '', 72 | lastSaved: '', 73 | docList: [] 74 | }, 75 | computed: { 76 | convertedMarkdown: function() { 77 | console.log('here') 78 | return converter.makeHtml(this.markdown); 79 | } 80 | }, 81 | methods: { 82 | newClicked: function() { 83 | this.markdown = '' 84 | this.docName = '' 85 | this.lastSaved = '' 86 | createAlert("New Document created", "") 87 | this.showJumbo = false 88 | this.docId = '' 89 | this.lastSaved = '' 90 | this.docList = [] 91 | }, 92 | saveClicked: async function() { 93 | if(!this.docId) { 94 | var uuid4 = UUID.create() 95 | this.docId = uuid4.toString(); 96 | } 97 | var doc = { 98 | doc_id: this.docId, 99 | doc_name: this.docName, 100 | body: this.markdown, 101 | ts: getTS() 102 | }; 103 | if(doc.doc_name.length === 0) { 104 | alert("Please name your document before saving it"); 105 | return false; 106 | } 107 | const self = this 108 | await db.post(doc) 109 | createAlert("Document saved", this.docName); 110 | self.lastSaved = doc.body; 111 | return false; 112 | }, 113 | loadClicked: async function() { 114 | this.docList = await getDocList() 115 | }, 116 | loadDoc: async function(doc) { 117 | this.markdown = doc.body 118 | this.docName = doc.doc_name 119 | this.showJumbo = false 120 | this.docId = doc.doc_id 121 | this.docList = [] 122 | }, 123 | dismissDocListClicked: function() { 124 | this.docList = [] 125 | } 126 | } 127 | }) 128 | -------------------------------------------------------------------------------- /js/old.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/glynnbird/md/153b208bc601ea368e3570c2517acf0542ce53f9/js/old.js -------------------------------------------------------------------------------- /js/pouchdb-5.2.1.min.js: -------------------------------------------------------------------------------- 1 | // PouchDB 5.2.1 2 | // 3 | // (c) 2012-2016 Dale Harvey and the PouchDB team 4 | // PouchDB may be freely distributed under the Apache license, version 2.0. 5 | // For all details and documentation: 6 | // http://pouchdb.com 7 | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.PouchDB=e()}}(function(){var e;return function t(e,n,r){function o(a,s){if(!n[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var f=n[a]={exports:{}};e[a][0].call(f.exports,function(t){var n=e[a][1][t];return o(n?n:t)},f,f.exports,t,e,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a=31}function o(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,i=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(i=o))}),e.splice(i,0,r),e}function i(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(e){try{null==e?n.storage.removeItem("debug"):n.storage.debug=e}catch(t){}}function s(){var e;try{e=n.storage.debug}catch(t){}return e}function u(){try{return window.localStorage}catch(e){}}n=t.exports=e(3),n.log=i,n.formatArgs=o,n.save=a,n.load=s,n.useColors=r,n.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:u(),n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{3:3}],3:[function(e,t,n){function r(){return n.colors[f++%n.colors.length]}function o(e){function t(){}function o(){var e=o,t=+new Date,i=t-(c||t);e.diff=i,e.prev=c,e.curr=t,c=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var a=Array.prototype.slice.call(arguments);a[0]=n.coerce(a[0]),"string"!=typeof a[0]&&(a=["%o"].concat(a));var s=0;a[0]=a[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var o=n.formatters[r];if("function"==typeof o){var i=a[s];t=o.call(e,i),a.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(a=n.formatArgs.apply(e,a));var u=o.log||n.log||console.log.bind(console);u.apply(e,a)}t.enabled=!1,o.enabled=!0;var i=n.enabled(e)?o:t;return i.namespace=e,i}function i(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,o=0;r>o;o++)t[o]&&(e=t[o].replace(/\*/g,".*?"),"-"===e[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")))}function a(){n.enable("")}function s(e){var t,r;for(t=0,r=n.skips.length;r>t;t++)if(n.skips[t].test(e))return!1;for(t=0,r=n.names.length;r>t;t++)if(n.names[t].test(e))return!0;return!1}function u(e){return e instanceof Error?e.stack||e.message:e}n=t.exports=o,n.coerce=u,n.disable=a,n.enable=i,n.enabled=s,n.humanize=e(9),n.names=[],n.skips=[],n.formatters={};var c,f=0},{9:9}],4:[function(e,t,n){function r(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function o(e){return"function"==typeof e}function i(e){return"number"==typeof e}function a(e){return"object"==typeof e&&null!==e}function s(e){return void 0===e}t.exports=r,r.EventEmitter=r,r.prototype._events=void 0,r.prototype._maxListeners=void 0,r.defaultMaxListeners=10,r.prototype.setMaxListeners=function(e){if(!i(e)||0>e||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},r.prototype.emit=function(e){var t,n,r,i,u,c;if(this._events||(this._events={}),"error"===e&&(!this._events.error||a(this._events.error)&&!this._events.error.length)){if(t=arguments[1],t instanceof Error)throw t;throw TypeError('Uncaught, unspecified "error" event.')}if(n=this._events[e],s(n))return!1;if(o(n))switch(arguments.length){case 1:n.call(this);break;case 2:n.call(this,arguments[1]);break;case 3:n.call(this,arguments[1],arguments[2]);break;default:i=Array.prototype.slice.call(arguments,1),n.apply(this,i)}else if(a(n))for(i=Array.prototype.slice.call(arguments,1),c=n.slice(),r=c.length,u=0;r>u;u++)c[u].apply(this,i);return!0},r.prototype.addListener=function(e,t){var n;if(!o(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,o(t.listener)?t.listener:t),this._events[e]?a(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,a(this._events[e])&&!this._events[e].warned&&(n=s(this._maxListeners)?r.defaultMaxListeners:this._maxListeners,n&&n>0&&this._events[e].length>n&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},r.prototype.on=r.prototype.addListener,r.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!o(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},r.prototype.removeListener=function(e,t){var n,r,i,s;if(!o(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(n=this._events[e],i=n.length,r=-1,n===t||o(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(a(n)){for(s=i;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){r=s;break}if(0>r)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(r,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},r.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(n=this._events[e],o(n))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},r.prototype.listeners=function(e){var t;return t=this._events&&this._events[e]?o(this._events[e])?[this._events[e]]:this._events[e].slice():[]},r.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(o(t))return 1;if(t)return t.length}return 0},r.listenerCount=function(e,t){return e.listenerCount(t)}},{}],5:[function(e,t,n){(function(e){"use strict";function n(){f=!0;for(var e,t,n=l.length;n;){for(t=l,l=[],e=-1;++e1e4)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*l;case"days":case"day":case"d":return n*f;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*u;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n}}}}function o(e){return e>=f?Math.round(e/f)+"d":e>=c?Math.round(e/c)+"h":e>=u?Math.round(e/u)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function i(e){return a(e,f,"day")||a(e,c,"hour")||a(e,u,"minute")||a(e,s,"second")||e+" ms"}function a(e,t,n){return t>e?void 0:1.5*t>e?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var s=1e3,u=60*s,c=60*u,f=24*c,l=365.25*f;t.exports=function(e,t){return t=t||{},"string"==typeof e?r(e):t["long"]?i(e):o(e)}},{}],10:[function(e,t,n){"use strict";function r(e){if(null!==e)switch(typeof e){case"boolean":return e?1:0;case"number":return f(e);case"string":return e.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"");case"object":var t=Array.isArray(e),r=t?e:Object.keys(e),o=-1,i=r.length,a="";if(t)for(;++oo;o++){var i=n.collate(e[o],t[o]);if(0!==i)return i}return e.length===t.length?0:e.length>t.length?1:-1}function s(e,t){return e===t?0:e>t?1:-1}function u(e,t){for(var r=Object.keys(e),o=Object.keys(t),i=Math.min(r.length,o.length),a=0;i>a;a++){var s=n.collate(r[a],o[a]);if(0!==s)return s;if(s=n.collate(e[r[a]],t[o[a]]),0!==s)return s}return r.length===o.length?0:r.length>o.length?1:-1}function c(e){var t=["boolean","number","string","object"],n=t.indexOf(typeof e);return~n?null===e?1:Array.isArray(e)?5:3>n?n+2:n+3:Array.isArray(e)?5:void 0}function f(e){if(0===e)return"1";var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=0>e,o=r?"0":"2",i=(r?-n:n)-l,a=p.padLeft(i.toString(),"0",d);o+=h+a;var s=Math.abs(parseFloat(t[0]));r&&(s=10-s);var u=s.toFixed(20);return u=u.replace(/\.?0+$/,""),o+=h+u}var l=-324,d=3,h="",p=e(11);n.collate=function(e,t){if(e===t)return 0;e=n.normalizeKey(e),t=n.normalizeKey(t);var r=c(e),o=c(t);if(r-o!==0)return r-o;if(null===e)return 0;switch(typeof e){case"number":return e-t;case"boolean":return e===t?0:t>e?-1:1;case"string":return s(e,t)}return Array.isArray(e)?a(e,t):u(e,t)},n.normalizeKey=function(e){switch(typeof e){case"undefined":return null;case"number":return e===1/0||e===-(1/0)||isNaN(e)?null:e;case"object":var t=e;if(Array.isArray(e)){var r=e.length;e=new Array(r);for(var o=0;r>o;o++)e[o]=n.normalizeKey(t[o])}else{if(e instanceof Date)return e.toJSON();if(null!==e){e={};for(var i in t)if(t.hasOwnProperty(i)){var a=t[i];"undefined"!=typeof a&&(e[i]=n.normalizeKey(a))}}}}return e},n.toIndexableString=function(e){var t="\x00";return e=n.normalizeKey(e),c(e)+h+r(e)+t},n.parseIndexableString=function(e){for(var t=[],n=[],r=0;;){var a=e[r++];if("\x00"!==a)switch(a){case"1":t.push(null);break;case"2":t.push("1"===e[r]),r++;break;case"3":var s=o(e,r);t.push(s.num),r+=s.length;break;case"4":for(var u="";;){var c=e[r];if("\x00"===c)break;u+=c,r++}u=u.replace(/\u0001\u0001/g,"\x00").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,""),t.push(u);break;case"5":var f={element:[],index:t.length};t.push(f.element),n.push(f);break;case"6":var l={element:{},index:t.length};t.push(l.element),n.push(l);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+a)}else{if(1===t.length)return t.pop();i(t,n)}}}},{11:11}],11:[function(e,t,n){"use strict";function r(e,t,n){for(var r="",o=n-e.length;r.lengthn;n++){if(n===o)return 1;var i=e.charAt(n),a=t.charAt(n);if(i!==a)return a>i?-1:1}return o>r?-1:0},n.intToDecimalForm=function(e){var t=0>e,n="";do{var r=t?-Math.ceil(e%10):Math.floor(e%10);n=r+n,e=t?Math.ceil(e/10):Math.floor(e/10)}while(e);return t&&"0"!==n&&(n="-"+n),n}},{}],12:[function(e,t,n){"use strict";function r(){this.store={}}function o(e){if(this.store=new r,e&&Array.isArray(e))for(var t=0,n=e.length;n>t;t++)this.add(e[t])}n.Map=r,n.Set=o,r.prototype.mangle=function(e){if("string"!=typeof e)throw new TypeError("key must be a string but Got "+e);return"$"+e},r.prototype.unmangle=function(e){return e.substring(1)},r.prototype.get=function(e){var t=this.mangle(e);return t in this.store?this.store[t]:void 0},r.prototype.set=function(e,t){var n=this.mangle(e);return this.store[n]=t,!0},r.prototype.has=function(e){var t=this.mangle(e);return t in this.store},r.prototype["delete"]=function(e){var t=this.mangle(e);return t in this.store?(delete this.store[t],!0):!1},r.prototype.forEach=function(e){for(var t=Object.keys(this.store),n=0,r=t.length;r>n;n++){var o=t[n],i=this.store[o];o=this.unmangle(o),e(i,o)}},o.prototype.add=function(e){return this.store.set(e,!0)},o.prototype.has=function(e){return this.store.has(e)},o.prototype["delete"]=function(e){return this.store["delete"](e)}},{}],13:[function(e,t,n){function r(){f=!1,s.length?c=s.concat(c):l=-1,c.length&&o()}function o(){if(!f){var e=setTimeout(r);f=!0;for(var t=c.length;t;){for(s=c,c=[];++l1)for(var n=1;n>>32-o,n)}function n(e,n,r,o,i,a,s){return t(n&r|~n&o,e,n,i,a,s)}function r(e,n,r,o,i,a,s){return t(n&o|r&~o,e,n,i,a,s)}function o(e,n,r,o,i,a,s){return t(n^r^o,e,n,i,a,s)}function i(e,n,r,o,i,a,s){return t(r^(n|~o),e,n,i,a,s)}function a(e,t){var a=e[0],s=e[1],u=e[2],c=e[3];a=n(a,s,u,c,t[0],7,-680876936),c=n(c,a,s,u,t[1],12,-389564586),u=n(u,c,a,s,t[2],17,606105819),s=n(s,u,c,a,t[3],22,-1044525330),a=n(a,s,u,c,t[4],7,-176418897),c=n(c,a,s,u,t[5],12,1200080426),u=n(u,c,a,s,t[6],17,-1473231341),s=n(s,u,c,a,t[7],22,-45705983),a=n(a,s,u,c,t[8],7,1770035416),c=n(c,a,s,u,t[9],12,-1958414417),u=n(u,c,a,s,t[10],17,-42063),s=n(s,u,c,a,t[11],22,-1990404162),a=n(a,s,u,c,t[12],7,1804603682),c=n(c,a,s,u,t[13],12,-40341101),u=n(u,c,a,s,t[14],17,-1502002290),s=n(s,u,c,a,t[15],22,1236535329),a=r(a,s,u,c,t[1],5,-165796510),c=r(c,a,s,u,t[6],9,-1069501632),u=r(u,c,a,s,t[11],14,643717713),s=r(s,u,c,a,t[0],20,-373897302),a=r(a,s,u,c,t[5],5,-701558691),c=r(c,a,s,u,t[10],9,38016083),u=r(u,c,a,s,t[15],14,-660478335),s=r(s,u,c,a,t[4],20,-405537848),a=r(a,s,u,c,t[9],5,568446438),c=r(c,a,s,u,t[14],9,-1019803690),u=r(u,c,a,s,t[3],14,-187363961),s=r(s,u,c,a,t[8],20,1163531501),a=r(a,s,u,c,t[13],5,-1444681467),c=r(c,a,s,u,t[2],9,-51403784),u=r(u,c,a,s,t[7],14,1735328473),s=r(s,u,c,a,t[12],20,-1926607734),a=o(a,s,u,c,t[5],4,-378558),c=o(c,a,s,u,t[8],11,-2022574463),u=o(u,c,a,s,t[11],16,1839030562),s=o(s,u,c,a,t[14],23,-35309556),a=o(a,s,u,c,t[1],4,-1530992060),c=o(c,a,s,u,t[4],11,1272893353),u=o(u,c,a,s,t[7],16,-155497632),s=o(s,u,c,a,t[10],23,-1094730640),a=o(a,s,u,c,t[13],4,681279174),c=o(c,a,s,u,t[0],11,-358537222),u=o(u,c,a,s,t[3],16,-722521979),s=o(s,u,c,a,t[6],23,76029189),a=o(a,s,u,c,t[9],4,-640364487),c=o(c,a,s,u,t[12],11,-421815835),u=o(u,c,a,s,t[15],16,530742520),s=o(s,u,c,a,t[2],23,-995338651),a=i(a,s,u,c,t[0],6,-198630844),c=i(c,a,s,u,t[7],10,1126891415),u=i(u,c,a,s,t[14],15,-1416354905),s=i(s,u,c,a,t[5],21,-57434055),a=i(a,s,u,c,t[12],6,1700485571),c=i(c,a,s,u,t[3],10,-1894986606),u=i(u,c,a,s,t[10],15,-1051523),s=i(s,u,c,a,t[1],21,-2054922799),a=i(a,s,u,c,t[8],6,1873313359),c=i(c,a,s,u,t[15],10,-30611744),u=i(u,c,a,s,t[6],15,-1560198380),s=i(s,u,c,a,t[13],21,1309151649),a=i(a,s,u,c,t[4],6,-145523070),c=i(c,a,s,u,t[11],10,-1120210379),u=i(u,c,a,s,t[2],15,718787259),s=i(s,u,c,a,t[9],21,-343485551),e[0]=g(a,e[0]),e[1]=g(s,e[1]),e[2]=g(u,e[2]),e[3]=g(c,e[3])}function s(e){var t,n=[];for(t=0;64>t;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n}function u(e){var t,n=[];for(t=0;64>t;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n}function c(e){var t,n,r,o,i,u,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;c>=t;t+=64)a(f,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;n>t;t+=1)r[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(f,r),t=0;16>t;t+=1)r[t]=0;return o=8*c,o=o.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(o[2],16),u=parseInt(o[1],16)||0,r[14]=i,r[15]=u,a(f,r),f}function f(e){var t,n,r,o,i,s,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;c>=t;t+=64)a(f,u(e.subarray(t-64,t)));for(e=c>t-64?e.subarray(t-64):new Uint8Array(0),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;n>t;t+=1)r[t>>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(a(f,r),t=0;16>t;t+=1)r[t]=0;return o=8*c,o=o.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(o[2],16),s=parseInt(o[1],16)||0,r[14]=i,r[15]=s,a(f,r),f}function l(e){var t,n="";for(t=0;4>t;t+=1)n+=b[e>>8*t+4&15]+b[e>>8*t&15];return n}function d(e){var t;for(t=0;tn;n+=1)i[n]=e.charCodeAt(n);return t?i:o}function v(e){return String.fromCharCode.apply(null,new Uint8Array(e))}function y(e,t,n){var r=new Uint8Array(e.byteLength+t.byteLength);return r.set(new Uint8Array(e)),r.set(new Uint8Array(t),e.byteLength),n?r:r.buffer}function _(e){var t,n=[],r=e.length;for(t=0;r-1>t;t+=2)n.push(parseInt(e.substr(t,2),16));return String.fromCharCode.apply(String,n)}function m(){this.reset()}var g=function(e,t){return e+t&4294967295},b=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];return"5d41402abc4b2a76b9719d911017c592"!==d(c("hello"))&&(g=function(e,t){var n=(65535&e)+(65535&t),r=(e>>16)+(t>>16)+(n>>16);return r<<16|65535&n}),"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||!function(){function t(e,t){return e=0|e||0,0>e?Math.max(e+t,0):Math.min(e,t)}ArrayBuffer.prototype.slice=function(n,r){var o,i,a,s,u=this.byteLength,c=t(n,u),f=u;return r!==e&&(f=t(r,u)),c>f?new ArrayBuffer(0):(o=f-c,i=new ArrayBuffer(o),a=new Uint8Array(i),s=new Uint8Array(this,c,o),a.set(s),i)}}(),m.prototype.append=function(e){return this.appendBinary(h(e)),this},m.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;n>=t;t+=64)a(this._hash,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substring(t-64),this},m.prototype.end=function(e){var t,n,r=this._buff,o=r.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;o>t;t+=1)i[t>>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),n=d(this._hash),e&&(n=_(n)),this.reset(),n},m.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},m.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash}},m.prototype.setState=function(e){return this._buff=e.buff,this._length=e.length,this._hash=e.hash,this},m.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},m.prototype._finish=function(e,t){var n,r,o,i=t;if(e[i>>2]|=128<<(i%4<<3),i>55)for(a(this._hash,e),i=0;16>i;i+=1)e[i]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),o=parseInt(n[1],16)||0,e[14]=r,e[15]=o,a(this._hash,e)},m.hash=function(e,t){return m.hashBinary(h(e),t)},m.hashBinary=function(e,t){var n=c(e),r=d(n);return t?_(r):r},m.ArrayBuffer=function(){this.reset()},m.ArrayBuffer.prototype.append=function(e){var t,n=y(this._buff.buffer,e,!0),r=n.length;for(this._length+=e.byteLength,t=64;r>=t;t+=64)a(this._hash,u(n.subarray(t-64,t)));return this._buff=r>t-64?new Uint8Array(n.buffer.slice(t-64)):new Uint8Array(0),this},m.ArrayBuffer.prototype.end=function(e){var t,n,r=this._buff,o=r.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;o>t;t+=1)i[t>>2]|=r[t]<<(t%4<<3);return this._finish(i,o),n=d(this._hash),e&&(n=_(n)),this.reset(),n},m.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},m.ArrayBuffer.prototype.getState=function(){var e=m.prototype.getState.call(this);return e.buff=v(e.buff),e},m.ArrayBuffer.prototype.setState=function(e){return e.buff=p(e.buff,!0),m.prototype.setState.call(this,e)},m.ArrayBuffer.prototype.destroy=m.prototype.destroy,m.ArrayBuffer.prototype._finish=m.prototype._finish,m.ArrayBuffer.hash=function(e,t){var n=f(new Uint8Array(e)),r=d(n);return t?_(r):r},m})},{}],16:[function(e,t,n){"use strict";function r(e,t,n){var r=n[n.length-1];e===r.element&&(n.pop(),r=n[n.length-1]);var o=r.element,i=r.index;if(Array.isArray(o))o.push(e);else if(i===t.length-2){var a=t.pop();o[a]=e}else t.push(e)}n.stringify=function(e){var t=[];t.push({obj:e});for(var n,r,o,i,a,s,u,c,f,l,d,h="";n=t.pop();)if(r=n.obj,o=n.prefix||"",i=n.val||"",h+=o,i)h+=i;else if("object"!=typeof r)h+="undefined"==typeof r?null:JSON.stringify(r);else if(null===r)h+="null";else if(Array.isArray(r)){for(t.push({val:"]"}),a=r.length-1;a>=0;a--)s=0===a?"":",",t.push({obj:r[a],prefix:s});t.push({val:"["})}else{u=[];for(c in r)r.hasOwnProperty(c)&&u.push(c);for(t.push({val:"}"}),a=u.length-1;a>=0;a--)f=u[a],l=r[f],d=a>0?",":"",d+=JSON.stringify(f)+":",t.push({obj:l,prefix:d});t.push({val:"{"})}return h},n.parse=function(e){for(var t,n,o,i,a,s,u,c,f,l=[],d=[],h=0;;)if(t=e[h++],"}"!==t&&"]"!==t&&"undefined"!=typeof t)switch(t){case" ":case" ":case"\n":case":":case",":break;case"n":h+=3,r(null,l,d);break;case"t":h+=3,r(!0,l,d);break;case"f":h+=4,r(!1,l,d);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":for(n="",h--;;){if(o=e[h++],!/[\d\.\-e\+]/.test(o)){h--;break}n+=o}r(parseFloat(n),l,d);break;case'"':for(i="",a=void 0,s=0;;){if(u=e[h++],'"'===u&&("\\"!==a||s%2!==1))break;i+=u,a=u,"\\"===a?s++:s=0}r(JSON.parse('"'+i+'"'),l,d);break;case"[":c={element:[],index:l.length},l.push(c.element),d.push(c);break;case"{":f={element:{},index:l.length},l.push(f.element),d.push(f);break;default:throw new Error("unexpectedly reached end of input: "+t)}else{if(1===l.length)return l.pop();r(l.pop(),l,d)}}},{}],17:[function(e,t,n){(function(n,r){"use strict";function o(e){return"default"in e?e["default"]:e}function i(e,t){for(var n={},r=0,o=t.length;o>r;r++){var i=t[r];i in e&&(n[i]=e[i])}return n}function a(e){return e instanceof ArrayBuffer||"undefined"!=typeof Blob&&e instanceof Blob}function s(e){if("function"==typeof e.slice)return e.slice(0);var t=new ArrayBuffer(e.byteLength),n=new Uint8Array(t),r=new Uint8Array(e);return n.set(r),t}function u(e){if(e instanceof ArrayBuffer)return s(e);var t=e.size,n=e.type;return"function"==typeof e.slice?e.slice(0,t,n):e.webkitSlice(0,t,n)}function c(e){var t,n,r;if(!e||"object"!=typeof e)return e;if(Array.isArray(e)){for(t=[],n=0,r=e.length;r>n;n++)t[n]=c(e[n]);return t}if(e instanceof Date)return e.toISOString();if(a(e))return u(e);t={};for(n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var o=c(e[n]);"undefined"!=typeof o&&(t[n]=o)}return t}function f(e){var t=!1;return Yn(function(n){if(t)throw new Error("once called more than once");t=!0,e.apply(this,n)})}function l(e){return Yn(function(t){t=c(t);var r,o=this,i="function"==typeof t[t.length-1]?t.pop():!1;i&&(r=function(e,t){n.nextTick(function(){i(e,t)})});var a=new ar(function(n,r){var i;try{var a=f(function(e,t){e?r(e):n(t)});t.push(a),i=e.apply(o,t),i&&"function"==typeof i.then&&n(i)}catch(s){r(s)}});return r&&a.then(function(e){r(null,e)},r),a})}function d(e,t){function n(e,t,n){if(sr.enabled){for(var r=[e._db_name,t],o=0;oc;c++)i.push({pos:u+1,ids:s[c]});else{var l=!!a[1].deleted,d=a[0];(!t||(r!==l?r:n!==u?u>n:d>t))&&(t=d,n=u,r=l)}}return n+"-"+t}function y(e){return e.ids}function _(e,t){t||(t=v(e));for(var n,r=t.substring(t.indexOf("-")+1),o=e.rev_tree.map(y);n=o.pop();){if(n[0]===r)return!!n[1].deleted;o=o.concat(n[2])}}function m(e){return rr("return "+e+";",{})}function g(e){return new Function("doc",["var emitted = false;","var emit = function (a, b) {"," emitted = true;","};","var view = "+e+";","view(doc);","if (emitted) {"," return true;","}"].join("\n"))}function b(e){if(!e)return null;var t=e.split("/");return 2===t.length?t:1===t.length?[e,e]:null}function w(e){var t=b(e);return t?t.join("/"):null}function E(e,t){for(var n,r=e.slice();n=r.pop();)for(var o=n.pos,i=n.ids,a=i[2],s=t(0===a.length,o,i[0],n.ctx,i[1]),u=0,c=a.length;c>u;u++)r.push({pos:o+1,ids:a[u],ctx:s})}function S(e,t){return e.pos-t.pos}function k(e){var t=[];E(e,function(e,n,r,o,i){e&&t.push({rev:n+"-"+r,pos:n,opts:i})}),t.sort(S).reverse();for(var n=0,r=t.length;r>n;n++)delete t[n].pos;return t}function q(e){for(var t=v(e),n=k(e.rev_tree),r=[],o=0,i=n.length;i>o;o++){var a=n[o];a.rev===t||a.opts.deleted||r.push(a.rev)}return r}function x(e){Error.call(this,e.reason),this.status=e.status,this.name=e.error,this.message=e.reason,this.error=!0}function A(e,t,n){function r(t){for(var r in e)"function"!=typeof e[r]&&(this[r]=e[r]);void 0!==n&&(this.name=n),void 0!==t&&(this.reason=t)}return r.prototype=x.prototype,new r(t)}function T(e){var t,n,r,o,i;return n=e.error===!0&&"string"==typeof e.name?e.name:e.error,i=e.reason,r=Ir("name",n,i),e.missing||"missing"===i||"deleted"===i||"not_found"===n?r=fr:"doc_validation"===n?(r=br, 8 | o=i):"bad_request"===n&&r.message!==i&&(r=wr),r||(r=Ir("status",e.status,i)||yr),t=A(r,i,n),o&&(t.message=o),e.id&&(t.id=e.id),e.status&&(t.status=e.status),e.missing&&(t.missing=e.missing),t}function O(e,t,n){function r(){o.cancel()}$n.EventEmitter.call(this);var o=this;this.db=e,t=t?c(t):{};var i=t.complete=f(function(t,n){t?o.emit("error",t):o.emit("complete",n),o.removeAllListeners(),e.removeListener("destroyed",r)});n&&(o.on("complete",function(e){n(null,e)}),o.on("error",n)),e.once("destroyed",r),t.onChange=function(e){t.isCancelled||(o.emit("change",e),o.startSeq&&o.startSeq<=e.seq&&(o.startSeq=!1))};var a=new ar(function(e,n){t.complete=function(t,r){t?n(t):e(r)}});o.once("cancel",function(){e.removeListener("destroyed",r),t.complete(null,{status:"cancelled"})}),this.then=a.then.bind(a),this["catch"]=a["catch"].bind(a),this.then(function(e){i(null,e)},i),e.taskqueue.isReady?o.doChanges(t):e.taskqueue.addTask(function(){o.isCancelled?o.emit("cancel"):o.doChanges(t)})}function j(e,t,n){var r=[{rev:e._rev}];"all_docs"===n.style&&(r=k(t.rev_tree).map(function(e){return{rev:e.rev}}));var o={id:t.id,changes:r,doc:e};return _(t,e._rev)&&(o.deleted=!0),n.conflicts&&(o.doc._conflicts=q(t),o.doc._conflicts.length||delete o.doc._conflicts),o}function C(e,t,n){function r(){var e=[];l.forEach(function(t){t.docs.forEach(function(n){e.push({id:t.id,docs:[n]})})}),n(null,{results:e})}function o(){++f===c&&r()}function a(e,t,n){l[e]={id:t,docs:n},o()}var s=Array.isArray(t)?t:t.docs,u={};s.forEach(function(e){e.id in u?u[e.id].push(e):u[e.id]=[e]});var c=Object.keys(u).length,f=0,l=new Array(c);Object.keys(u).forEach(function(n,r){var o=u[n],s=i(o[0],["atts_since","attachments"]);s.open_revs=o.map(function(e){return e.rev}),s.open_revs=s.open_revs.filter(function(e){return e});var c=function(e){return e};0===s.open_revs.length&&(delete s.open_revs,c=function(e){return[{ok:e}]}),["revs","attachments","binary"].forEach(function(e){e in t&&(s[e]=t[e])}),e.get(n,s,function(e,t){a(r,n,e?[{error:e}]:c(t))})})}function L(e){return/^_local/.test(e)}function I(e){for(var t,n=[],r=e.slice();t=r.pop();){var o=t.pos,i=t.ids,a=i[0],s=i[1],u=i[2],c=0===u.length,f=t.history?t.history.slice():[];f.push({id:a,opts:s}),c&&n.push({pos:o+1-f.length,ids:f});for(var l=0,d=u.length;d>l;l++)r.push({pos:o+1,ids:u[l],history:f})}return n.reverse()}function R(e){return 0|Math.random()*e}function D(e,t){t=t||Rr.length;var n="",r=-1;if(e){for(;++ri;i++)o=[r[i],{status:"missing"},[o]];return[{pos:n,ids:o}]}function U(e,t){var n,r,o,i={status:"available"};if(e._deleted&&(i.deleted=!0),t)if(e._id||(e._id=D()),r=D(32,16).toLowerCase(),e._rev){if(o=F(e._rev),o.error)return o;e._rev_tree=[{pos:o.prefix,ids:[o.id,{status:"missing"},[[r,i,[]]]]}],n=o.prefix+1}else e._rev_tree=[{pos:1,ids:[r,i,[]]}],n=1;else if(e._revisions&&(e._rev_tree=M(e._revisions,i),n=e._revisions.start,r=e._revisions.ids[0]),!e._rev_tree){if(o=F(e._rev),o.error)return o;n=o.prefix,r=o.id,e._rev_tree=[{pos:n,ids:[r,i,[]]}]}B(e._id),e._rev=n+"-"+r;var a={metadata:{},data:{}};for(var s in e)if(Object.prototype.hasOwnProperty.call(e,s)){var u="_"===s[0];if(u&&!Dr[s]){var c=A(br,s);throw c.message=br.message+": "+s,c}u&&!Nr[s]?a.metadata[s.slice(1)]=e[s]:a.data[s]=e[s]}return a}function P(e,t){return t>e?-1:e>t?1:0}function H(e,t){for(var n=0;n0?t.keys.slice(t.skip):t.keys;if(t.descending&&r.reverse(),!r.length)return e._allDocs({limit:0},n);var o={offset:t.skip};return ar.all(r.map(function(n){var r=Vn.extend({key:n,deleted:"ok"},t);return["limit","skip","keys"].forEach(function(e){delete r[e]}),new ar(function(t,i){e._allDocs(r,function(e,r){return e?i(e):(o.total_rows=r.total_rows,void t(r.rows[0]||{key:n,error:"not_found"}))})})})).then(function(e){return o.rows=e,o})}function X(e){var t=e._compactionQueue[0],r=t.opts,o=t.callback;e.get("_local/compaction")["catch"](function(){return!1}).then(function(t){t&&t.last_seq&&(r.last_seq=t.last_seq),e._compact(r,function(t,r){t?o(t):o(null,r),n.nextTick(function(){e._compactionQueue.shift(),e._compactionQueue.length&&X(e)})})})}function z(e){return"_"===e.charAt(0)?e+"is not a valid attachment name, attachment names cannot start with '_'":!1}function Q(){$n.EventEmitter.call(this)}function $(){this.isReady=!1,this.failed=!1,this.queue=[]}function Y(e){e&&r.debug&&console.error(e)}function Z(e,t){function n(){i.emit("destroyed",o),i.emit(o,"destroyed")}function r(){e.removeListener("destroyed",n),e.emit("destroyed",e)}var o=t.originalName,i=e.constructor,a=i._destructionListeners;e.once("destroyed",n),a.has(o)||a.set(o,[]),a.get(o).push(r)}function ee(e,t,n){if(!(this instanceof ee))return new ee(e,t,n);var r=this;("function"==typeof t||"undefined"==typeof t)&&(n=t,t={}),e&&"object"==typeof e&&(t=e,e=void 0),"undefined"==typeof n&&(n=Y),e=e||t.name,t=c(t),delete t.name,this.__opts=t;var o=n;r.auto_compaction=t.auto_compaction,r.prefix=ee.prefix,Q.call(r),r.taskqueue=new $;var i=new ar(function(o,i){n=function(e,t){return e?i(e):(delete t.then,void o(t))},t=c(t);var a,s,u=t.name||e;return function(){try{if("string"!=typeof u)throw s=new Error("Missing/invalid DB name"),s.code=400,s;if(a=ee.parseAdapter(u,t),t.originalName=u,t.name=a.name,t.prefix&&"http"!==a.adapter&&"https"!==a.adapter&&(t.name=t.prefix+t.name),t.adapter=t.adapter||a.adapter,r._adapter=t.adapter,Zn("pouchdb:adapter")("Picked adapter: "+t.adapter),r._db_name=u,!ee.adapters[t.adapter])throw s=new Error("Adapter is missing"),s.code=404,s;if(!ee.adapters[t.adapter].valid())throw s=new Error("Invalid Adapter"),s.code=404,s}catch(e){r.taskqueue.fail(e)}}(),s?i(s):(r.adapter=t.adapter,r.replicate={},r.replicate.from=function(e,t,n){return r.constructor.replicate(e,r,t,n)},r.replicate.to=function(e,t,n){return r.constructor.replicate(r,e,t,n)},r.sync=function(e,t,n){return r.constructor.sync(r,e,t,n)},r.replicate.sync=r.sync,void ee.adapters[t.adapter].call(r,t,function(e){return e?(r.taskqueue.fail(e),void n(e)):(Z(r,t),r.emit("created",r),ee.emit("created",t.originalName),r.taskqueue.ready(r),void n(null,r))}))});i.then(function(e){o(null,e)},o),r.then=i.then.bind(i),r["catch"]=i["catch"].bind(i)}function te(){return"undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage&&"undefined"!=typeof chrome.storage.local}function ne(){return Br}function re(e){Object.keys($n.EventEmitter.prototype).forEach(function(t){"function"==typeof $n.EventEmitter.prototype[t]&&(e[t]=Mr[t].bind(Mr))});var t=e._destructionListeners=new Qn.Map;e.on("destroyed",function(e){t.has(e)&&(t.get(e).forEach(function(e){e()}),t["delete"](e))})}function oe(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(n){if("TypeError"!==n.name)throw n;for(var r="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder,o=new r,i=0;i0&&(r=setTimeout(function(){n.reject(new Error("Load timeout for resource: "+e.url))},e.timeout)),n.promise.then(function(t){return o={statusCode:t.status},e.timeout>0&&clearTimeout(r),o.statusCode>=200&&o.statusCode<300?e.binary?t.blob():t.text():t.json()}).then(function(e){o.statusCode>=200&&o.statusCode<300?t(null,o,e):t(e,o)})["catch"](function(e){t(e,o)}),{abort:n.reject}}function ue(e,t){var n,r,o=function(){n.abort()};n=e.xhr?new e.xhr:new XMLHttpRequest;try{n.open(e.method,e.url)}catch(i){t(i,{statusCode:413})}n.withCredentials="withCredentials"in e?e.withCredentials:!0,"GET"===e.method?delete e.headers["Content-Type"]:e.json&&(e.headers.Accept="application/json",e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json",e.body&&e.processData&&"string"!=typeof e.body&&(e.body=JSON.stringify(e.body))),e.binary&&(n.responseType="arraybuffer"),"body"in e||(e.body=null);for(var a in e.headers)e.headers.hasOwnProperty(a)&&n.setRequestHeader(a,e.headers[a]);return e.timeout>0&&(r=setTimeout(o,e.timeout),n.onprogress=function(){clearTimeout(r),r=setTimeout(o,e.timeout)},"undefined"!=typeof n.upload&&(n.upload.onprogress=n.onprogress)),n.onreadystatechange=function(){if(4===n.readyState){var r={statusCode:n.status};if(n.status>=200&&n.status<300){var o;o=e.binary?oe([n.response||""],{type:n.getResponseHeader("Content-Type")}):n.responseText,t(null,r,o)}else{var i={};try{i=JSON.parse(n.response)}catch(a){}t(i,r)}}},e.body&&e.body instanceof Blob?ie(e.body,function(e){n.send(e)}):n.send(e.body),{abort:o}}function ce(){try{return new XMLHttpRequest,!0}catch(e){return!1}}function fe(e,t){return Ur||e.xhr?ue(e,t):se(e,t)}function le(){return""}function de(e,t){function n(t,n,r){if(!e.binary&&e.json&&"string"==typeof t)try{t=JSON.parse(t)}catch(o){return r(o)}Array.isArray(t)&&(t=t.map(function(e){return e.error||e.missing?T(e):e})),e.binary&&Pr(t,n),r(null,t,n)}function r(e,t){var n,r;if(e.code&&e.status){var o=new Error(e.message||e.code);return o.status=e.status,t(o)}try{n=JSON.parse(e.responseText),r=T(n)}catch(i){r=T(e)}t(r)}e=c(e);var o={method:"GET",headers:{},json:!0,processData:!0,timeout:1e4,cache:!1};return e=Vn.extend(o,e),e.json&&(e.binary||(e.headers.Accept="application/json"),e.headers["Content-Type"]=e.headers["Content-Type"]||"application/json"),e.binary&&(e.encoding=null,e.json=!1),e.processData||(e.json=!1),fe(e,function(o,i,a){if(o)return o.status=i?i.statusCode:400,r(o,t);var s,u=i.headers&&i.headers["content-type"],c=a||le();if(!e.binary&&(e.json||!e.processData)&&"object"!=typeof c&&(/json/.test(u)||/^[\s]*\{/.test(c)&&/\}[\s]*$/.test(c)))try{c=JSON.parse(c.toString())}catch(f){}i.statusCode>=200&&i.statusCode<300?n(c,i,t):(s=T(c),s.status=i.statusCode,t(s))})}function he(e,t){var n=navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",r=-1!==n.indexOf("safari")&&-1===n.indexOf("chrome"),o=-1!==n.indexOf("msie"),i=r&&"POST"===e.method||o&&"GET"===e.method,a="cache"in e?e.cache:!0;if(i||!a){var s=-1!==e.url.indexOf("?");e.url+=(s?"&":"?")+"_nonce="+Date.now()}return de(e,t)}function pe(e){for(var t=Kr.exec(e),n={},r=14;r--;){var o=Hr[r],i=t[r]||"",a=-1!==["user","password"].indexOf(o);n[o]=a?decodeURIComponent(i):i}return n[Wr]={},n[Hr[12]].replace(Jr,function(e,t,r){t&&(n[Wr][t]=r)}),n}function ve(e){for(var t=e.length,n=new ArrayBuffer(t),r=new Uint8Array(n),o=0;t>o;o++)r[o]=e.charCodeAt(o);return n}function ye(e,t){return oe([ve(e)],{type:t})}function _e(e,t,n){try{return!e(t,n)}catch(r){var o="Filter function threw: "+r.toString();return A(wr,o)}}function me(e){var t={},n=e.filter&&"function"==typeof e.filter;return t.query=e.query_params,function(r){r.doc||(r.doc={});var o=n&&_e(e.filter,r.doc,t);if("object"==typeof o)return o;if(o)return!1;if(e.include_docs){if(!e.attachments)for(var i in r.doc._attachments)r.doc._attachments.hasOwnProperty(i)&&(r.doc._attachments[i].stub=!0)}else delete r.doc;return!0}}function ge(e,t){"console"in r&&"info"in console&&console.info("The above "+e+" is totally normal. "+t)}function be(e,t,n,r,o){return e.get(t)["catch"](function(n){if(404===n.status)return"http"===e.type()&&ge(404,"PouchDB is just checking if a remote checkpoint exists."),{session_id:r,_id:t,history:[],replicator:Yr,version:$r};throw n}).then(function(i){return o.cancelled?void 0:(i.history=(i.history||[]).filter(function(e){return e.session_id!==r}),i.history.unshift({last_seq:n,session_id:r}),i.history=i.history.slice(0,Zr),i.version=$r,i.replicator=Yr,i.session_id=r,i.last_seq=n,e.put(i)["catch"](function(i){if(409===i.status)return be(e,t,n,r,o);throw i}))})}function we(e,t,n,r){this.src=e,this.target=t,this.id=n,this.returnValue=r}function Ee(e,t){if(e.session_id===t.session_id)return{last_seq:e.last_seq,history:e.history||[]};var n=e.history||[],r=t.history||[];return Se(n,r)}function Se(e,t){var n=e[0],r=e.slice(1),o=t[0],i=t.slice(1);if(!n||0===t.length)return{last_seq:eo,history:[]};var a=n.session_id;if(ke(a,t))return{last_seq:n.last_seq,history:e};var s=o.session_id;return ke(s,r)?{last_seq:o.last_seq,history:i}:Se(r,i)}function ke(e,t){var n=t[0],r=t.slice(1);return e&&0!==t.length?e===n.session_id?!0:ke(e,r):!1}function qe(e){return"number"==typeof e.status&&4===Math.floor(e.status/100)}function xe(e,t){e=parseInt(e,10)||0,t=parseInt(t,10),t!==t||e>=t?t=(e||1)<<1:t+=1;var n=Math.random(),r=t-e;return~~(r*n+e)}function Ae(e){var t=0;return e||(t=2e3),xe(e,t)}function Te(e,t,n,r){return e.retry===!1?(t.emit("error",n),void t.removeAllListeners()):("function"!=typeof e.back_off_function&&(e.back_off_function=Ae),t.emit("requestError",n),("active"===t.state||"pending"===t.state)&&(t.emit("paused",n),t.state="stopped",t.once("active",function(){e.current_back_off=no})),e.current_back_off=e.current_back_off||no,e.current_back_off=e.back_off_function(e.current_back_off),void setTimeout(r,e.current_back_off))}function Oe(e){return Vr(e)}function je(e,t,n,r){(n>0||r0||r0}function i(r){return e.allDocs({keys:r,include_docs:!0}).then(function(e){if(n.cancelled)throw new Error("cancelled");e.rows.forEach(function(e){!e.deleted&&e.doc&&Re(e.value.rev)&&!o(e.doc)&&(u.push(e.doc),delete t[e.id])})})}function a(){var e=Object.keys(t).filter(function(e){var n=t[e].missing;return 1===n.length&&Re(n[0])});return e.length>0?i(e):void 0}function s(){return u}t=c(t);var u=[];return ar.resolve().then(a).then(r).then(s)}function Be(e,t,n,r,o){function i(){return S?ar.resolve():Ie(e,t,n).then(function(n){E=n,S=new we(e,t,E,r)})}function a(){if(B=[],0!==w.docs.length){var e=w.docs;return t.bulkDocs({docs:e,new_edits:!1}).then(function(t){if(r.cancelled)throw p(),new Error("cancelled");var n=[],i={};t.forEach(function(e){e.error&&(o.doc_write_failures++,n.push(e),i[e.id]=e)}),N=N.concat(n),o.docs_written+=w.docs.length-n.length;var a=n.filter(function(e){return"unauthorized"!==e.name&&"forbidden"!==e.name});if(e.forEach(function(e){var t=i[e._id];t?r.emit("denied",c(t)):B.push(e)}),a.length>0){var s=new Error("bulkDocs error");throw s.other_errors=n,h("target.bulkDocs failed to write docs",s),new Error("bulkWrite partial failure")}},function(t){throw o.doc_write_failures+=e.length,t})}}function s(){o.last_seq=O=w.seq;var e=c(o);return B.length&&(e.docs=B,r.emit("change",e)),x=!0,S.writeCheckpoint(w.seq,F).then(function(){if(x=!1,r.cancelled)throw p(),new Error("cancelled");w=void 0,m()})["catch"](function(e){throw x=!1,h("writeCheckpoint completed with error",e),e})}function u(){var e={};return w.changes.forEach(function(t){"_user/"!==t.id&&(e[t.id]=t.changes.map(function(e){return e.rev}))}),t.revsDiff(e).then(function(e){if(r.cancelled)throw p(),new Error("cancelled");w.diffs=e})}function f(){return Ne(e,w.diffs,r).then(function(e){e.forEach(function(e){delete w.diffs[e._id],o.docs_read++,w.docs.push(e)})})}function l(){if(!r.cancelled&&!w){if(0===k.length)return void d(!0);w=k.shift(),u().then(f).then(a).then(s).then(l)["catch"](function(e){h("batch processing terminated with error",e)})}}function d(e){return 0===q.changes.length?void(0!==k.length||w||((j&&M.live||A)&&(r.state="pending",r.emit("paused")),A&&p())):void((e||A||q.changes.length>=C)&&(k.push(q),q={seq:0,changes:[],docs:[]},("pending"===r.state||"stopped"===r.state)&&(r.state="active",r.emit("active")),l()))}function h(e,t){T||(t.message||(t.message=e),o.ok=!1,o.status="aborting",o.errors.push(t),N=N.concat(t),k=[],q={seq:0,changes:[],docs:[]},p())}function p(){if(!(T||r.cancelled&&(o.status="cancelled",x))){o.status=o.status||"complete",o.end_time=new Date,o.last_seq=O,T=!0;var i=N.filter(function(e){return"unauthorized"!==e.name&&"forbidden"!==e.name});if(i.length>0){var a=N.pop();N.length>0&&(a.other_errors=N),a.result=o,Te(n,r,a,function(){Be(e,t,n,r)})}else o.errors=N,r.emit("complete",o),r.removeAllListeners()}}function v(e){if(r.cancelled)return p();var t=me(n)(e);t&&(q.seq=e.seq,q.changes.push(e),d(M.live))}function y(e){return I=!1,r.cancelled?p():(e.results.length>0?(M.since=e.last_seq,m()):j?(M.live=!0,m()):A=!0,void d(!0))}function _(e){return I=!1,r.cancelled?p():void h("changes rejected",e)}function m(){function t(){i.cancel()}function o(){r.removeListener("cancel",t)}if(!I&&!A&&k.lengtho;o++)t+=String.fromCharCode(n[o]);return t}function Ke(e,t){if("undefined"==typeof FileReader)return t(Je((new FileReaderSync).readAsArrayBuffer(e)));var n=new FileReader,r="function"==typeof n.readAsBinaryString;n.onloadend=function(e){var n=e.target.result||"";return r?t(n):void t(Je(n))},r?n.readAsBinaryString(e):n.readAsArrayBuffer(e)}function Ge(e){return new ar(function(t){Ke(e,function(e){t(Vr(e))})})}function Ve(e){for(var t=[],n=0,r=e.length;r>n;n++)t=t.concat(e[n]);return t}function Xe(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach(function(e){var n=t[e];n.data=We(n.data,n.content_type)})}function ze(e){return/^_design/.test(e)?"_design/"+encodeURIComponent(e.slice(8)):/^_local/.test(e)?"_local/"+encodeURIComponent(e.slice(7)):encodeURIComponent(e)}function Qe(e){return e._attachments&&Object.keys(e._attachments)?ar.all(Object.keys(e._attachments).map(function(t){var n=e._attachments[t];return n.data&&"string"!=typeof n.data?Ge(n.data).then(function(e){n.data=e}):void 0})):ar.resolve()}function $e(e){var t=pe(e);(t.user||t.password)&&(t.auth={username:t.user,password:t.password});var n=t.path.replace(/(^\/|\/$)/g,"").split("/");return t.db=n.pop(),-1===t.db.indexOf("%")&&(t.db=encodeURIComponent(t.db)),t.path=n.join("/"),t}function Ye(e,t){return Ze(e,e.db+"/"+t)}function Ze(e,t){var n=e.path?"/":"";return e.protocol+"://"+e.host+(e.port?":"+e.port:"")+"/"+e.path+n+t}function et(e){return"?"+Object.keys(e).map(function(t){return t+"="+encodeURIComponent(e[t])}).join("&")}function tt(e,t){function n(e,t,n){var r=e.ajax||{},o=Vn.extend(c(p),r,t);return ho(o.method+" "+o.url),zr.ajax(o,n)}function r(e,t){return new ar(function(r,o){n(e,t,function(e,t){return e?o(e):void r(t)})})}function o(e,t){return d(e,Yn(function(e){a().then(function(n){return t.apply(this,e)})["catch"](function(t){var n=e.pop();n(t)})}))}function a(){if(e.skipSetup||e.skip_setup)return ar.resolve();if(_)return _;var t={method:"GET",url:h};return _=r({},t)["catch"](function(e){return e&&e.status&&404===e.status?(ge(404,"PouchDB is just detecting if the remote exists."),r({},{method:"PUT",url:h})):ar.reject(e)})["catch"](function(e){return e&&e.status&&412===e.status?!0:ar.reject(e)}),_["catch"](function(){_=null}),_}function s(e){return e.split("/").map(encodeURIComponent).join("/")}var u=this,f=$e;e.getHost&&(f=e.getHost);var l=f(e.name,e),h=Ye(l,"");e=c(e);var p=e.ajax||{};if(u.getUrl=function(){return h},u.getHeaders=function(){return p.headers||{}},e.auth||l.auth){var v=e.auth||l.auth,y=Vr(v.username+":"+v.password);p.headers=p.headers||{},p.headers.Authorization="Basic "+y}var _;setTimeout(function(){t(null,u)}),u.type=function(){return"http"},u.id=o("id",function(e){n({},{method:"GET",url:Ze(l,"")},function(t,n){var r=n&&n.uuid?n.uuid+l.db:Ye(l,"");e(null,r)})}),u.request=o("request",function(e,t){e.url=Ye(l,e.url),n({},e,t)}),u.compact=o("compact",function(e,t){"function"==typeof e&&(t=e,e={}),e=c(e),n(e,{url:Ye(l,"_compact"),method:"POST"},function(){function n(){u.info(function(r,o){o&&!o.compact_running?t(null,{ok:!0}):setTimeout(n,e.interval||200)})}n()})}),u.bulkGet=d("bulkGet",function(e,t){function r(t){var r={};e.revs&&(r.revs=!0),e.attachments&&(r.attachments=!0),n({},{url:Ye(l,"_bulk_get"+et(r)),method:"POST",body:{docs:e.docs}},t)}function o(){function n(e){return function(n,r){u[e]=r.results,++s===o&&t(null,{results:Ve(u)})}}for(var r=co,o=Math.ceil(e.docs.length/r),s=0,u=new Array(o),c=0;o>c;c++){var f=i(e,["revs","attachments"]);f.docs=e.docs.slice(c*r,Math.min(e.docs.length,(c+1)*r)),C(a,f,n(c))}}var a=this,s=Ze(l,""),u=fo[s];"boolean"!=typeof u?r(function(e,n){if(e){var r=Math.floor(e.status/100);4===r||5===r?(fo[s]=!1,ge(e.status,"PouchDB is just detecting if the remote supports the _bulk_get API."),o()):t(e)}else fo[s]=!0,t(null,n)}):u?r(t):o()}),u._info=function(e){a().then(function(){n({},{method:"GET",url:Ye(l,"")},function(t,n){return t?e(t):(n.host=Ye(l,""),void e(null,n))})})["catch"](e)},u.get=o("get",function(e,t,n){function o(e){var n=e._attachments,o=n&&Object.keys(n);return n&&o.length?ar.all(o.map(function(o){var i=n[o],a=ze(e._id)+"/"+s(o)+"?rev="+e._rev;return r(t,{method:"GET",url:Ye(l,a),binary:!0}).then(function(e){return t.binary?e:Ge(e)}).then(function(e){delete i.stub,delete i.length,i.data=e})})):void 0}function i(e){return Array.isArray(e)?ar.all(e.map(function(e){return e.ok?o(e.ok):void 0})):o(e)}"function"==typeof t&&(n=t,t={}),t=c(t);var a={};t.revs&&(a.revs=!0),t.revs_info&&(a.revs_info=!0),t.open_revs&&("all"!==t.open_revs&&(t.open_revs=JSON.stringify(t.open_revs)),a.open_revs=t.open_revs),t.rev&&(a.rev=t.rev),t.conflicts&&(a.conflicts=t.conflicts),e=ze(e);var u={method:"GET",url:Ye(l,e+et(a))};r(t,u).then(function(e){return ar.resolve().then(function(){return t.attachments?i(e):void 0}).then(function(){n(null,e)})})["catch"](n)}),u.remove=o("remove",function(e,t,r,o){var i;"string"==typeof t?(i={_id:e,_rev:t},"function"==typeof r&&(o=r,r={})):(i=e,"function"==typeof t?(o=t,r={}):(o=r,r=t));var a=i._rev||r.rev;n(r,{method:"DELETE",url:Ye(l,ze(i._id))+"?rev="+a},o)}),u.getAttachment=o("getAttachment",function(e,t,r,o){"function"==typeof r&&(o=r,r={});var i=r.rev?"?rev="+r.rev:"",a=Ye(l,ze(e))+"/"+s(t)+i;n(r,{method:"GET",url:a,binary:!0},o)}),u.removeAttachment=o("removeAttachment",function(e,t,r,o){var i=Ye(l,ze(e)+"/"+s(t))+"?rev="+r;n({},{method:"DELETE",url:i},o)}),u.putAttachment=o("putAttachment",function(e,t,r,o,i,a){"function"==typeof i&&(a=i,i=o,o=r,r=null);var u=ze(e)+"/"+s(t),c=Ye(l,u);if(r&&(c+="?rev="+r),"string"==typeof o){var f;try{f=Gr(o)}catch(d){return a(A(_r,"Attachment is not a valid base64 string"))}o=f?ye(f,i):""}var h={headers:{"Content-Type":i},method:"PUT",url:c,processData:!1,body:o,timeout:p.timeout||6e4};n({},h,a)}),u._bulkDocs=function(e,t,r){e.new_edits=t.new_edits,a().then(function(){return ar.all(e.docs.map(Qe))}).then(function(){n(t,{method:"POST",url:Ye(l,"_bulk_docs"),body:e},function(e,t){return e?r(e):(t.forEach(function(e){e.ok=!0}),void r(null,t))})})["catch"](r)},u.allDocs=o("allDocs",function(e,t){"function"==typeof e&&(t=e,e={}),e=c(e);var n,o={},i="GET";e.conflicts&&(o.conflicts=!0),e.descending&&(o.descending=!0),e.include_docs&&(o.include_docs=!0),e.attachments&&(o.attachments=!0),e.key&&(o.key=JSON.stringify(e.key)),e.start_key&&(e.startkey=e.start_key),e.startkey&&(o.startkey=JSON.stringify(e.startkey)),e.end_key&&(e.endkey=e.end_key),e.endkey&&(o.endkey=JSON.stringify(e.endkey)),"undefined"!=typeof e.inclusive_end&&(o.inclusive_end=!!e.inclusive_end),"undefined"!=typeof e.limit&&(o.limit=e.limit),"undefined"!=typeof e.skip&&(o.skip=e.skip);var a=et(o);if("undefined"!=typeof e.keys){var s="keys="+encodeURIComponent(JSON.stringify(e.keys));s.length+a.length+1<=lo?a+="&"+s:(i="POST",n={keys:e.keys})}r(e,{method:i,url:Ye(l,"_all_docs"+a),body:n}).then(function(n){e.include_docs&&e.attachments&&e.binary&&n.rows.forEach(Xe),t(null,n)})["catch"](t)}),u._changes=function(e){var t="batch_size"in e?e.batch_size:uo;e=c(e),e.timeout="timeout"in e?e.timeout:"timeout"in p?p.timeout:3e4;var r,o=e.timeout?{timeout:e.timeout-5e3}:{},i="undefined"!=typeof e.limit?e.limit:!1;r="return_docs"in e?e.return_docs:"returnDocs"in e?e.returnDocs:!0;var s=i;if(e.style&&(o.style=e.style),(e.include_docs||e.filter&&"function"==typeof e.filter)&&(o.include_docs=!0),e.attachments&&(o.attachments=!0),e.continuous&&(o.feed="longpoll"),e.conflicts&&(o.conflicts=!0),e.descending&&(o.descending=!0),"heartbeat"in e?e.heartbeat&&(o.heartbeat=e.heartbeat):o.heartbeat=1e4,e.filter&&"string"==typeof e.filter&&(o.filter=e.filter,"_view"===e.filter&&e.view&&"string"==typeof e.view&&(o.view=e.view)),e.query_params&&"object"==typeof e.query_params)for(var u in e.query_params)e.query_params.hasOwnProperty(u)&&(o[u]=e.query_params[u]); 9 | var f,d="GET";if(e.doc_ids){o.filter="_doc_ids";var h=JSON.stringify(e.doc_ids);h.lengtht?t:s;var c={method:d,url:Ye(l,"_changes"+et(o)),timeout:e.timeout,body:f};y=r,e.aborted||a().then(function(){v=n(e,c,u)})["catch"](u)}},m={results:[]},g=function(n,o){if(!e.aborted){var a=0;if(o&&o.results){a=o.results.length,m.last_seq=o.last_seq;var u={};u.query=e.query_params,o.results=o.results.filter(function(t){s--;var n=me(e)(t);return n&&(e.include_docs&&e.attachments&&e.binary&&Xe(t),r&&m.results.push(t),e.onChange(t)),n})}else if(n)return e.aborted=!0,void e.complete(n);o&&o.last_seq&&(y=o.last_seq);var c=i&&0>=s||o&&t>a||e.descending;(!e.continuous||i&&0>=s)&&c?e.complete(null,m):setTimeout(function(){_(y,g)},0)}};return _(e.since||0,g),{cancel:function(){e.aborted=!0,v&&v.abort()}}},u.revsDiff=o("revsDiff",function(e,t,r){"function"==typeof t&&(r=t,t={}),n(t,{method:"POST",url:Ye(l,"_revs_diff"),body:e},r)}),u._close=function(e){e()},u._destroy=function(t,r){n(t,{url:Ye(l,""),method:"DELETE"},function(t,n){return t&&t.status&&404!==t.status?r(t):(u.emit("destroyed"),u.constructor.emit("destroyed",e.name),void r(null,n))})}}function nt(){this.promise=new ar(function(e){e()})}function rt(e){return or.hash(e)}function ot(e){var t=e.db,n=e.viewName,r=e.map,o=e.reduce,i=e.temporary,a=r.toString()+(o&&o.toString())+"undefined";if(!i&&t._cachedViews){var s=t._cachedViews[a];if(s)return ar.resolve(s)}return t.info().then(function(e){function s(e){e.views=e.views||{};var t=n;-1===t.indexOf("/")&&(t=n+"/"+n);var r=e.views[t]=e.views[t]||{};if(!r[u])return r[u]=!0,e}var u=e.db_name+"-mrview-"+(i?"temp":rt(a));return h(t,"_local/mrviews",s).then(function(){return t.registerDependentDatabase(u).then(function(e){var n=e.db;n.auto_compaction=!0;var s={name:u,db:n,sourceDB:t,adapter:t.adapter,mapFun:r,reduceFun:o};return s.db.get("_local/lastSeq")["catch"](function(e){if(404!==e.status)throw e}).then(function(e){return s.seq=e?e.seq:0,i||(t._cachedViews=t._cachedViews||{},t._cachedViews[a]=s,s.db.once("destroyed",function(){delete t._cachedViews[a]})),s})})})})}function it(e,t,n,r,o,i){return rr("return ("+e.replace(/;\s*$/,"")+");",{emit:t,sum:n,log:r,isArray:o,toJSON:i})}function at(e){return-1===e.indexOf("/")?[e,e]:e.split("/")}function st(e){return 1===e.length&&/^1-/.test(e[0].rev)}function ut(e,t){try{e.emit("error",t)}catch(n){console.error("The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function."),console.error(t)}}function ct(e,t,n){try{return{output:t.apply(null,n)}}catch(r){return ut(e,r),{error:r}}}function ft(e,t){var n=wo(e.key,t.key);return 0!==n?n:wo(e.value,t.value)}function lt(e,t,n){return n=n||0,"number"==typeof t?e.slice(n,t+n):n>0?e.slice(n):e}function dt(e){var t=e.value,n=t&&"object"==typeof t&&t._id||e.id;return n}function ht(e){e.rows.forEach(function(e){var t=e.doc&&e.doc._attachments;t&&Object.keys(t).forEach(function(e){var n=t[e];t[e].data=We(n.data,n.content_type)})})}function pt(e){return function(t){return e.include_docs&&e.attachments&&e.binary&&ht(t),t}}function vt(e){var t="builtin "+e+" function requires map values to be numbers or number arrays";return new Mt(t)}function yt(e){for(var t=0,n=0,r=e.length;r>n;n++){var o=e[n];if("number"!=typeof o){if(!Array.isArray(o))throw vt("_sum");t="number"==typeof t?[t]:t;for(var i=0,a=o.length;a>i;i++){var s=o[i];if("number"!=typeof s)throw vt("_sum");"undefined"==typeof t[i]?t.push(s):t[i]+=s}}else"number"==typeof t?t+=o:t[0]+=o}return t}function _t(e,t,n,r){var o=t[e];"undefined"!=typeof o&&(r&&(o=encodeURIComponent(JSON.stringify(o))),n.push(e+"="+o))}function mt(e){if("undefined"!=typeof e){var t=Number(e);return isNaN(t)||t!==parseInt(e,10)?e:t}}function gt(e){return e.group_level=mt(e.group_level),e.limit=mt(e.limit),e.skip=mt(e.skip),e}function bt(e){if(e){if("number"!=typeof e)return new Bt('Invalid value for integer: "'+e+'"');if(0>e)return new Bt('Invalid value for positive integer: "'+e+'"')}}function wt(e,t){var n=e.descending?"endkey":"startkey",r=e.descending?"startkey":"endkey";if("undefined"!=typeof e[n]&&"undefined"!=typeof e[r]&&wo(e[n],e[r])>0)throw new Bt("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&e.reduce!==!1){if(e.include_docs)throw new Bt("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new Bt("Multi-key fetches for reduce views must use {group: true}")}["group_level","limit","skip"].forEach(function(t){var n=bt(e[t]);if(n)throw n})}function Et(e,t,n){var r,o=[],i="GET";if(_t("reduce",n,o),_t("include_docs",n,o),_t("attachments",n,o),_t("limit",n,o),_t("descending",n,o),_t("group",n,o),_t("group_level",n,o),_t("skip",n,o),_t("stale",n,o),_t("conflicts",n,o),_t("startkey",n,o,!0),_t("start_key",n,o,!0),_t("endkey",n,o,!0),_t("end_key",n,o,!0),_t("inclusive_end",n,o),_t("key",n,o,!0),o=o.join("&"),o=""===o?"":"?"+o,"undefined"!=typeof n.keys){var a=2e3,s="keys="+encodeURIComponent(JSON.stringify(n.keys));s.length+o.length+1<=a?o+=("?"===o[0]?"&":"?")+s:(i="POST","string"==typeof t?r={keys:n.keys}:t.keys=n.keys)}if("string"==typeof t){var u=at(t);return e.request({method:i,url:"_design/"+u[0]+"/_view/"+u[1]+o,body:r}).then(pt(n))}return r=r||{},Object.keys(t).forEach(function(e){Array.isArray(t[e])?r[e]=t[e]:r[e]=t[e].toString()}),e.request({method:"POST",url:"_temp_view"+o,body:r}).then(pt(n))}function St(e,t,n){return new ar(function(r,o){e._query(t,n,function(e,t){return e?o(e):void r(t)})})}function kt(e){return new ar(function(t,n){e._viewCleanup(function(e,r){return e?n(e):void t(r)})})}function qt(e){return function(t){if(404===t.status)return e;throw t}}function xt(e,t,n){function r(){return st(f)?ar.resolve(s):t.db.get(a)["catch"](qt(s))}function o(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):ar.resolve({rows:[]})}function i(e,t){for(var n=[],r={},o=0,i=t.rows.length;i>o;o++){var a=t.rows[o],s=a.doc;if(s&&(n.push(s),r[s._id]=!0,s._deleted=!c[s._id],!s._deleted)){var u=c[s._id];"value"in u&&(s.value=u.value)}}var f=Object.keys(c);return f.forEach(function(e){if(!r[e]){var t={_id:e},o=c[e];"value"in o&&(t.value=o.value),n.push(t)}}),e.keys=Ao(f.concat(e.keys)),n.push(e),n}var a="_local/doc_"+e,s={_id:a,keys:[]},u=n[e],c=u.indexableKeysToKeyValues,f=u.changes;return r().then(function(e){return o(e).then(function(t){return i(e,t)})})}function At(e,t,n){var r="_local/lastSeq";return e.db.get(r)["catch"](qt({_id:r,seq:0})).then(function(r){var o=Object.keys(t);return ar.all(o.map(function(n){return xt(n,e,t)})).then(function(t){var o=Ve(t);return r.seq=n,o.push(r),e.db.bulkDocs({docs:o})})})}function Tt(e){var t="string"==typeof e?e:e.name,n=jo[t];return n||(n=jo[t]=new nt),n}function Ot(e){return xo(Tt(e),function(){return jt(e)})()}function jt(e){function t(e,t){var n={id:o._id,key:So(e)};"undefined"!=typeof t&&null!==t&&(n.value=So(t)),r.push(n)}function n(t,n){return function(){return At(e,t,n)}}var r,o,i;if("function"==typeof e.mapFun&&2===e.mapFun.length){var a=e.mapFun;i=function(e){return a(e,t)}}else i=it(e.mapFun.toString(),t,yt,po,Array.isArray,JSON.parse);var s=e.seq||0,u=new nt;return new ar(function(t,a){function c(){u.finish().then(function(){e.seq=s,t()})}function f(){function t(e){a(e)}e.sourceDB.changes({conflicts:!0,include_docs:!0,style:"all_docs",since:s,limit:Lo}).on("complete",function(t){var a=t.results;if(!a.length)return c();for(var l={},d=0,h=a.length;h>d;d++){var p=a[d];if("_"!==p.doc._id[0]){r=[],o=p.doc,o._deleted||ct(e.sourceDB,i,[o]),r.sort(ft);for(var v,y={},_=0,m=r.length;m>_;_++){var g=r[_],b=[g.key,g.id];0===wo(g.key,v)&&b.push(_);var w=Eo(b);y[w]=g,v=g.key}l[p.doc._id]={indexableKeysToKeyValues:y,changes:p.changes}}s=p.seq}return u.add(n(l,s)),a.lengtha?n.slice(0,a):n),t&&0===wo(t.key[0][0],n)?(t.key.push([n,e.id]),void t.value.push(e.value)):void i.push({key:[[n,e.id]],value:[e.value]})});for(var s=0,u=i.length;u>s;s++){var c=i[s],f=ct(e.sourceDB,r,[c.key,c.value,!1]);if(f.error&&f.error instanceof Mt)throw f.error;c.value=f.error?null:f.output,c.key=c.key[0][0]}return{rows:lt(i,n.limit,n.skip)}}function Lt(e,t){return xo(Tt(e),function(){return It(e,t)})()}function It(e,t){function n(t){return t.include_docs=!0,e.db.allDocs(t).then(function(e){return o=e.total_rows,e.rows.map(function(e){if("value"in e.doc&&"object"==typeof e.doc.value&&null!==e.doc.value){var t=Object.keys(e.doc.value).sort(),n=["id","key","value"];if(!(n>t||t>n))return e.doc.value}var r=ko(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}})})}function r(n){var r;if(r=i?Ct(e,n,t):{total_rows:o,offset:a,rows:n},t.include_docs){var s=Ao(n.map(dt));return e.sourceDB.allDocs({keys:s,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments,binary:t.binary}).then(function(e){var t={};return e.rows.forEach(function(e){e.doc&&(t["$"+e.id]=e.doc)}),n.forEach(function(e){var n=dt(e),r=t["$"+n];r&&(e.doc=r)}),r})}return r}var o,i=e.reduceFun&&t.reduce!==!1,a=t.skip||0;if("undefined"==typeof t.keys||t.keys.length||(t.limit=0,delete t.keys),"undefined"!=typeof t.keys){var s=t.keys,u=s.map(function(e){var t={startkey:Eo([e]),endkey:Eo([e,{}])};return n(t)});return ar.all(u).then(Ve).then(r)}var c={descending:t.descending};if(t.start_key&&(t.startkey=t.start_key),t.end_key&&(t.endkey=t.end_key),"undefined"!=typeof t.startkey&&(c.startkey=Eo(t.descending?[t.startkey,{}]:[t.startkey])),"undefined"!=typeof t.endkey){var f=t.inclusive_end!==!1;t.descending&&(f=!f),c.endkey=Eo(f?[t.endkey,{}]:[t.endkey])}if("undefined"!=typeof t.key){var l=Eo([t.key]),d=Eo([t.key,{}]);c.descending?(c.endkey=l,c.startkey=d):(c.startkey=l,c.endkey=d)}return i||("number"==typeof t.limit&&(c.limit=t.limit),c.skip=a),n(c).then(r)}function Rt(e){return e.request({method:"POST",url:"_view_cleanup"})}function Dt(e){return e.get("_local/mrviews").then(function(t){var n={};Object.keys(t.views).forEach(function(e){var t=at(e),r="_design/"+t[0],o=t[1];n[r]=n[r]||{},n[r][o]=!0});var r={keys:Object.keys(n),include_docs:!0};return e.allDocs(r).then(function(r){var o={};r.rows.forEach(function(e){var r=e.key.substring(8);Object.keys(n[e.key]).forEach(function(n){var i=r+"/"+n;t.views[i]||(i=n);var a=Object.keys(t.views[i]),s=e.doc&&e.doc.views&&e.doc.views[n];a.forEach(function(e){o[e]=o[e]||s})})});var i=Object.keys(o).filter(function(e){return!o[e]}),a=i.map(function(t){return xo(Tt(t),function(){return new e.constructor(t,e.__opts).destroy()})()});return ar.all(a).then(function(){return{ok:!0}})})},qt({ok:!0}))}function Nt(e,t,r){if("http"===e.type())return Et(e,t,r);if("function"==typeof e._query)return St(e,t,r);if("string"!=typeof t){wt(r,t);var o={db:e,viewName:"temp_view/temp_view",map:t.map,reduce:t.reduce,temporary:!0};return Co.add(function(){return ot(o).then(function(e){function t(){return e.db.destroy()}return To(Ot(e).then(function(){return Lt(e,r)}),t)})}),Co.finish()}var i=t,a=at(i),s=a[0],u=a[1];return e.get("_design/"+s).then(function(t){var o=t.views&&t.views[u];if(!o||"string"!=typeof o.map)throw new Ft("ddoc "+s+" has no view named "+u);wt(r,o);var a={db:e,viewName:i,map:o.map,reduce:o.reduce};return ot(a).then(function(e){return"ok"===r.stale||"update_after"===r.stale?("update_after"===r.stale&&n.nextTick(function(){Ot(e)}),Lt(e,r)):Ot(e).then(function(){return Lt(e,r)})})})}function Bt(e){this.status=400,this.name="query_parse_error",this.message=e,this.error=!0;try{Error.captureStackTrace(this,Bt)}catch(t){}}function Ft(e){this.status=404,this.name="not_found",this.message=e,this.error=!0;try{Error.captureStackTrace(this,Ft)}catch(t){}}function Mt(e){this.status=500,this.name="invalid_value",this.message=e,this.error=!0;try{Error.captureStackTrace(this,Mt)}catch(t){}}function Ut(e,t,n){function r(e){try{return Gr(e)}catch(t){var n=A(_r,"Attachment is not a valid base64 string");return{error:n}}}function o(e,n){if(e.stub)return n();if("string"==typeof e.data){var o=r(e.data);if(o.error)return n(o.error);e.length=o.length,"blob"===t?e.data=ye(o,e.content_type):"base64"===t?e.data=Vr(o):e.data=o,io(o).then(function(t){e.digest="md5-"+t,n()})}else ie(e.data,function(r){"binary"===t?e.data=Je(r):"base64"===t&&(e.data=Vr(Je(r))),io(r).then(function(t){e.digest="md5-"+t,e.length=r.byteLength,n()})})}function i(){s++,e.length===s&&(a?n(a):n())}if(!e.length)return n();var a,s=0;e.forEach(function(e){function t(e){a=e,r++,r===n.length&&i()}var n=e.data&&e.data._attachments?Object.keys(e.data._attachments):[],r=0;if(!n.length)return i();for(var s in e.data._attachments)e.data._attachments.hasOwnProperty(s)&&o(e.data._attachments[s],t)})}function Pt(e,t){return e.pos-t.pos}function Ht(e,t,n){for(var r,o=0,i=e.length;i>o;)r=o+i>>>1,n(e[r],t)<0?o=r+1:i=r;return o}function Wt(e,t,n){var r=Ht(e,t,n);e.splice(r,0,t)}function Jt(e,t){for(var n,r,o=t,i=e.length;i>o;o++){var a=e[o],s=[a.id,a.opts,[]];r?(r[2].push(s),r=s):n=r=s}return n}function Kt(e,t){return e[0]0;){var o=n.pop(),i=o.tree1,a=o.tree2;(i[1].status||a[1].status)&&(i[1].status="available"===i[1].status||"available"===a[1].status?"available":"missing");for(var s=0;ss;s++){var c=e[s];if(c.pos===t.pos&&c.ids[0]===t.ids[0])r=Gt(c.ids,t.ids),o.push({pos:c.pos,ids:r.tree}),i=i||r.conflicts,a=!0;else if(n!==!0){var f=c.pos0;){var v=p.pop();if(0!==v.diff)for(var y=v.ids[2],_=0,m=y.length;m>_;_++)p.push({ids:y[_],diff:v.diff-1,parent:v.ids,parentIdx:_});else v.ids[0]===l.ids[0]&&h.push(v)}var g=h[0];g?(r=Gt(g.ids,l.ids),g.parent[2][g.parentIdx]=r.tree,o.push({pos:f.pos,ids:f.ids}),i=i||r.conflicts,a=!0):o.push(c)}else o.push(c)}return a||o.push(t),o.sort(Pt),{tree:o,conflicts:i||"internal_node"}}function Xt(e,t){for(var n,r=I(e),o=0,i=r.length;i>o;o++){var a=r[o],s=a.ids,u=Math.max(0,s.length-t),c={pos:a.pos+u,ids:Jt(s,u)};n=n?Vt(n,c,!0).tree:[c]}return n}function zt(e,t,n){var r=Vt(e,t);return{tree:Xt(r.tree,n),conflicts:r.conflicts}}function Qt(e,t){for(var n,r=e.slice(),o=t.split("-"),i=parseInt(o[0],10),a=o[1];n=r.pop();){if(n.pos===i&&n.ids[0]===a)return!0;for(var s=n.ids[2],u=0,c=s.length;c>u;u++)r.push({pos:n.pos+1,ids:s[u]})}return!1}function $t(e,t,n,r,o,i,a,s){if(Qt(t.rev_tree,n.metadata.rev))return r[o]=n,i();var u=t.winningRev||v(t),c="deleted"in t?t.deleted:_(t,u),f="deleted"in n.metadata?n.metadata.deleted:_(n.metadata),l=/^1-/.test(n.metadata.rev);if(c&&!f&&s&&l){var d=n.data;d._rev=u,d._id=n.metadata.id,n=U(d,s)}var h=zt(t.rev_tree,n.metadata.rev_tree[0],e),p=s&&(c&&f||!c&&"new_leaf"!==h.conflicts||c&&!f&&"new_branch"===h.conflicts);if(p){var y=A(lr);return r[o]=y,i()}var m=n.metadata.rev;n.metadata.rev_tree=h.tree,t.rev_map&&(n.metadata.rev_map=t.rev_map);var g,b=v(n.metadata),w=_(n.metadata,b),E=c===w?0:w>c?-1:1;g=m===b?w:_(n.metadata,m),a(n,b,w,g,!0,E,o,i)}function Yt(e){return"missing"===e.metadata.rev_tree[0].ids[1].status}function Zt(e,t,n,r,o,i,a,s,u){function c(e,t,n){var r=v(e.metadata),o=_(e.metadata,r);if("was_delete"in s&&o)return i[t]=A(fr,"deleted"),n();var u=l&&Yt(e);if(u){var c=A(lr);return i[t]=c,n()}var f=o?0:1;a(e,r,o,o,!1,f,t,n)}function f(){++h===p&&u&&u()}e=e||1e3;var l=s.new_edits,d=new Qn.Map,h=0,p=t.length;t.forEach(function(e,t){if(e._id&&L(e._id)){var r=e._deleted?"_removeLocal":"_putLocal";return void n[r](e,{ctx:o},function(e,n){i[t]=e||n,f()})}var a=e.metadata.id;d.has(a)?(p--,d.get(a).push([e,t])):d.set(a,[[e,t]])}),d.forEach(function(t,n){function o(){++ur;r++){var i=q[r];if(i._id&&L(i._id))e();else{var a=b.get(i.metadata.id);a.onsuccess=t}}}function f(){R||(i.notify(r._meta.name),r._meta.docCount+=x,a(null,C))}function l(e,t){var n=E.get(e);n.onsuccess=function(n){if(n.target.result)t();else{var r=A(jr,"unknown stub attachment with digest "+e);r.status=412,t(r)}}}function d(e){function t(){++o===n.length&&e(r)}var n=[];if(q.forEach(function(e){e.data&&e.data._attachments&&Object.keys(e.data._attachments).forEach(function(t){var r=e.data._attachments[t];r.stub&&n.push(r.digest)})}),!n.length)return e();var r,o=0;n.forEach(function(e){l(e,function(e){e&&!r&&(r=e),t()})})}function h(e,t,n,r,o,i,a,s){x+=i,e.metadata.winningRev=t,e.metadata.deleted=n;var u=e.data;u._id=e.metadata.id,u._rev=e.metadata.rev,r&&(u._deleted=!0);var c=u._attachments&&Object.keys(u._attachments).length;return c?y(e,t,n,o,a,s):void v(e,t,n,o,a,s)}function p(e){var t=en(e.metadata);hn(t,e.metadata.id,g)}function v(e,t,n,o,i,a){function s(i){o&&r.auto_compaction&&p(e),l.seq=i.target.result,delete l.rev;var a=sn(l,t,n),s=b.put(a);s.onsuccess=c}function u(e){e.preventDefault(),e.stopPropagation();var t=w.index("_doc_id_rev"),n=t.getKey(f._doc_id_rev);n.onsuccess=function(e){var t=w.put(f,e.target.result);t.onsuccess=s}}function c(){C[i]={ok:!0,id:l.id,rev:t},I.set(e.metadata.id,e.metadata),_(e,l.seq,a)}var f=e.data,l=e.metadata;f._doc_id_rev=l.id+"::"+l.rev,delete f._id,delete f._rev;var d=w.put(f);d.onsuccess=s,d.onerror=u}function y(e,t,n,r,o,i){function a(){c===f.length&&v(e,t,n,r,o,i)}function s(){c++,a()}var u=e.data,c=0,f=Object.keys(u._attachments);f.forEach(function(t){var n=e.data._attachments[t];if(n.stub)c++,a();else{var r=n.data;delete n.data;var o=n.digest;m(o,r,s)}})}function _(e,t,n){function r(){++i===a.length&&n()}function o(n){var o=e.data._attachments[n].digest,i=S.put({seq:t,digestSeq:o+"::"+t});i.onsuccess=r,i.onerror=function(e){e.preventDefault(),e.stopPropagation(),r()}}var i=0,a=Object.keys(e.data._attachments||{});if(!a.length)return n();for(var s=0;sT;T++){var j=q[T];j._id&&L(j._id)||(j=q[T]=U(j,n.new_edits),j.error&&!k&&(k=j))}if(k)return a(k);var C=new Array(q.length),I=new Qn.Map,R=!1,D=r._meta.blobSupport?"blob":"base64";Ut(q,D,function(e){return e?a(e):void s()})}function yn(e,t,n,r,o){try{if(e&&t)return o?IDBKeyRange.bound(t,e,!n,!1):IDBKeyRange.bound(e,t,!1,!n);if(e)return o?IDBKeyRange.upperBound(e):IDBKeyRange.lowerBound(e);if(t)return o?IDBKeyRange.lowerBound(t,!n):IDBKeyRange.upperBound(t,!n);if(r)return IDBKeyRange.only(r)}catch(i){return{error:i}}return null}function _n(e,t,n,r){return"DataError"===n.name&&0===n.code?r(null,{total_rows:e._meta.docCount,offset:t.skip,rows:[]}):void r(A(kr,n.name,n.message))}function mn(e,t,n,r){function o(e,r){function o(t,n,r){var o=t.id+"::"+r;S.get(o).onsuccess=function(r){n.doc=cn(r.target.result),e.conflicts&&(n.doc._conflicts=q(t)),ln(n.doc,e,g)}}function i(t,n,r){var i={id:r.id,key:r.id,value:{rev:n}},a=r.deleted;if("ok"===e.deleted)k.push(i),a?(i.value.deleted=!0,i.doc=null):e.include_docs&&o(r,i,n);else if(!a&&d--<=0&&(k.push(i),e.include_docs&&o(r,i,n),0===--h))return;t["continue"]()}function a(e){x=t._meta.docCount;var n=e.target.result;if(n){var r=un(n.value),o=r.winningRev;i(n,o,r)}}function s(){r(null,{total_rows:x,offset:e.skip,rows:k})}function u(){e.attachments?dn(k,e.binary).then(s):s()}var c="startkey"in e?e.startkey:!1,f="endkey"in e?e.endkey:!1,l="key"in e?e.key:!1,d=e.skip||0,h="number"==typeof e.limit?e.limit:-1,p=e.inclusive_end!==!1,v="descending"in e&&e.descending?"prev":null,y=yn(c,f,p,l,v);if(y&&y.error)return _n(t,e,y.error,r);var _=[Fo,Mo];e.attachments&&_.push(Uo);var m=pn(n,_,"readonly");if(m.error)return r(m.error);var g=m.txn,b=g.objectStore(Fo),w=g.objectStore(Mo),E=v?b.openCursor(y,v):b.openCursor(y),S=w.index("_doc_id_rev"),k=[],x=0;g.oncomplete=u,E.onsuccess=a}function i(e,n){return 0===e.limit?n(null,{total_rows:t._meta.docCount,offset:e.skip,rows:[]}):void o(e,n)}i(e,r)}function gn(e){return new ar(function(t){var n=oe([""]);e.objectStore(Jo).put(n,"key"),e.onabort=function(e){e.preventDefault(),e.stopPropagation(),t(!1)},e.oncomplete=function(){var e=navigator.userAgent.match(/Chrome\/(\d+)/),n=navigator.userAgent.match(/Edge\//);t(n||!e||parseInt(e[1],10)>=43)}})["catch"](function(){return!1})}function bn(e){te()?chrome.storage.onChanged.addListener(function(t){null!=t.db_name&&e.emit(t.dbName.newValue)}):ne()&&("undefined"!=typeof addEventListener?addEventListener("storage",function(t){e.emit(t.key)}):window.attachEvent("storage",function(t){e.emit(t.key)}))}function wn(){$n.EventEmitter.call(this),this._listeners={},bn(this)}function En(e,t){var n=this;Ko.queue.push({action:function(t){Sn(n,e,t)},callback:t}),on(n.constructor)}function Sn(e,t,r){function o(e){var t=e.createObjectStore(Fo,{keyPath:"id"});e.createObjectStore(Mo,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0}),e.createObjectStore(Uo,{keyPath:"digest"}),e.createObjectStore(Ho,{keyPath:"id",autoIncrement:!1}),e.createObjectStore(Jo),t.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),e.createObjectStore(Wo,{keyPath:"_id"});var n=e.createObjectStore(Po,{autoIncrement:!0});n.createIndex("seq","seq"),n.createIndex("digestSeq","digestSeq",{unique:!0})}function i(e,t){var n=e.objectStore(Fo);n.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1}),n.openCursor().onsuccess=function(e){var r=e.target.result;if(r){var o=r.value,i=_(o);o.deletedOrLocal=i?"1":"0",n.put(o),r["continue"]()}else t()}}function a(e){e.createObjectStore(Wo,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function s(e,t){var n=e.objectStore(Wo),r=e.objectStore(Fo),o=e.objectStore(Mo),i=r.openCursor();i.onsuccess=function(e){var i=e.target.result;if(i){var a=i.value,s=a.id,u=L(s),c=v(a);if(u){var f=s+"::"+c,l=s+"::",d=s+"::~",h=o.index("_doc_id_rev"),p=IDBKeyRange.bound(l,d,!1,!1),y=h.openCursor(p);y.onsuccess=function(e){if(y=e.target.result){var t=y.value;t._doc_id_rev===f&&n.put(t),o["delete"](y.primaryKey),y["continue"]()}else r["delete"](i.primaryKey),i["continue"]()}}else i["continue"]()}else t&&t()}}function u(e){var t=e.createObjectStore(Po,{autoIncrement:!0});t.createIndex("seq","seq"),t.createIndex("digestSeq","digestSeq",{unique:!0})}function f(e,t){var n=e.objectStore(Mo),r=e.objectStore(Uo),o=e.objectStore(Po),i=r.count();i.onsuccess=function(e){var r=e.target.result;return r?void(n.openCursor().onsuccess=function(e){var n=e.target.result;if(!n)return t();for(var r=n.value,i=n.primaryKey,a=Object.keys(r._attachments||{}),s={},u=0;uo&&(o=n),t["continue"]()}}function i(){var e=sn(s,s.winningRev,s.deleted),t=r.put(e);t.onsuccess=function(){a["continue"]()}}var a=e.target.result;if(a){var s=t(a.value);return s.winningRev=s.winningRev||v(s),s.seq?i():void o()}}}var h=t.name,p=null;e._meta=null,e.type=function(){return"idb"},e._id=l(function(t){t(null,e._meta.instanceId)}),e._bulkDocs=function(n,r,o){vn(t,n,r,e,p,En.Changes,o)},e._get=function(e,t,n){function r(){n(a,{doc:o,metadata:i,ctx:s})}var o,i,a,s=t.ctx;if(!s){var u=pn(p,[Fo,Mo,Uo],"readonly");if(u.error)return n(u.error);s=u.txn}s.objectStore(Fo).get(e).onsuccess=function(e){if(i=un(e.target.result),!i)return a=A(fr,"missing"),r();if(_(i)&&!t.rev)return a=A(fr,"deleted"),r();var n=s.objectStore(Mo),u=t.rev||i.winningRev,c=i.id+"::"+u;n.index("_doc_id_rev").get(c).onsuccess=function(e){return o=e.target.result,o&&(o=cn(o)),o?void r():(a=A(fr,"missing"),r())}}},e._getAttachment=function(e,t,n){var r;if(t.ctx)r=t.ctx;else{var o=pn(p,[Fo,Mo,Uo],"readonly");if(o.error)return n(o.error);r=o.txn}var i=e.digest,a=e.content_type;r.objectStore(Uo).get(i).onsuccess=function(e){var r=e.target.result.body;fn(r,a,t.binary,function(e){n(null,e)})}},e._info=function(t){if(null===p||!Vo[h]){var n=new Error("db isn't open");return n.id="idbNull",t(n)}var r,o,i=pn(p,[Mo],"readonly");if(i.error)return t(i.error);var a=i.txn,s=a.objectStore(Mo).openCursor(null,"prev");s.onsuccess=function(t){var n=t.target.result;r=n?n.key:0,o=e._meta.docCount},a.oncomplete=function(){t(null,{doc_count:o,update_seq:r,idb_attachment_format:e._meta.blobSupport?"binary":"base64"})}},e._allDocs=function(t,n){mn(t,e,p,n)},e._changes=function(t){function n(e){function n(){return c.seq!==a?e["continue"]():(u=a,c.winningRev===i._rev?o(i):void r())}function r(){var e=i._id+"::"+c.winningRev,t=_.get(e);t.onsuccess=function(e){o(cn(e.target.result))}}function o(n){var r=t.processChange(n,c,t);r.seq=c.seq;var o=b(r);return"object"==typeof o?t.complete(o):(o&&(g++,l&&m.push(r),t.attachments&&t.include_docs?ln(n,t,d,function(){dn([r],t.binary).then(function(){t.onChange(r)})}):t.onChange(r)),void(g!==f&&e["continue"]()))}var i=cn(e.value),a=e.key;if(s&&!s.has(i._id))return e["continue"]();var c;return(c=w.get(i._id))?n():void(y.get(i._id).onsuccess=function(e){c=un(e.target.result),w.set(i._id,c),n()})}function r(e){var t=e.target.result;t&&n(t)}function o(){var e=[Fo,Mo];t.attachments&&e.push(Uo);var n=pn(p,e,"readonly");if(n.error)return t.complete(n.error);d=n.txn,d.onabort=an(t.complete),d.oncomplete=i,v=d.objectStore(Mo),y=d.objectStore(Fo),_=v.index("_doc_id_rev");var o;o=t.descending?v.openCursor(null,"prev"):v.openCursor(IDBKeyRange.lowerBound(t.since,!0)),o.onsuccess=r}function i(){function e(){t.complete(null,{results:m,last_seq:u})}!t.continuous&&t.attachments?dn(m).then(e):e()}if(t=c(t),t.continuous){var a=h+":"+D();return En.Changes.addListener(h,a,e,t),En.Changes.notify(h),{cancel:function(){En.Changes.removeListener(h,a)}}}var s=t.doc_ids&&new Qn.Set(t.doc_ids);t.since=t.since||0;var u=t.since,f="limit"in t?t.limit:-1;0===f&&(f=1);var l;l="return_docs"in t?t.return_docs:"returnDocs"in t?t.returnDocs:!0;var d,v,y,_,m=[],g=0,b=me(t),w=new Qn.Map;o()},e._close=function(e){return null===p?e(A(vr)):(p.close(),delete Vo[h],p=null,void e())},e._getRevisionTree=function(e,t){var n=pn(p,[Fo],"readonly");if(n.error)return t(n.error);var r=n.txn,o=r.objectStore(Fo).get(e);o.onsuccess=function(e){var n=un(e.target.result);n?t(null,n.rev_tree):t(A(fr))}},e._doCompaction=function(e,t,n){var r=[Fo,Mo,Uo,Po],o=pn(p,r,"readwrite");if(o.error)return n(o.error);var i=o.txn,a=i.objectStore(Fo);a.get(e).onsuccess=function(n){var r=un(n.target.result);E(r.rev_tree,function(e,n,r,o,i){var a=n+"-"+r;-1!==t.indexOf(a)&&(i.status="missing")}),hn(t,e,i);var o=r.winningRev,a=r.deleted;i.objectStore(Fo).put(sn(r,o,a))},i.onabort=an(n),i.oncomplete=function(){n()}},e._getLocal=function(e,t){var n=pn(p,[Wo],"readonly");if(n.error)return t(n.error);var r=n.txn,o=r.objectStore(Wo).get(e);o.onerror=an(t),o.onsuccess=function(e){var n=e.target.result;n?(delete n._doc_id_rev,t(null,n)):t(A(fr))}},e._putLocal=function(e,t,n){"function"==typeof t&&(n=t,t={}),delete e._revisions;var r=e._rev,o=e._id;r?e._rev="0-"+(parseInt(r.split("-")[1],10)+1):e._rev="0-1";var i,a=t.ctx;if(!a){var s=pn(p,[Wo],"readwrite");if(s.error)return n(s.error);a=s.txn,a.onerror=an(n),a.oncomplete=function(){i&&n(null,i)}}var u,c=a.objectStore(Wo);r?(u=c.get(o),u.onsuccess=function(o){var a=o.target.result;if(a&&a._rev===r){var s=c.put(e);s.onsuccess=function(){i={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,i)}}else n(A(lr))}):(u=c.add(e),u.onerror=function(e){n(A(lr)), 10 | e.preventDefault(),e.stopPropagation()},u.onsuccess=function(){i={ok:!0,id:e._id,rev:e._rev},t.ctx&&n(null,i)})},e._removeLocal=function(e,t,n){"function"==typeof t&&(n=t,t={});var r=t.ctx;if(!r){var o=pn(p,[Wo],"readwrite");if(o.error)return n(o.error);r=o.txn,r.oncomplete=function(){i&&n(null,i)}}var i,a=e._id,s=r.objectStore(Wo),u=s.get(a);u.onerror=an(n),u.onsuccess=function(r){var o=r.target.result;o&&o._rev===e._rev?(s["delete"](a),i={ok:!0,id:a,rev:"0-0"},t.ctx&&n(null,i)):n(A(fr))}},e._destroy=function(e,t){En.Changes.removeAllListeners(h),En.openReqList[h]&&En.openReqList[h].result&&(En.openReqList[h].result.close(),delete Vo[h]);var n=indexedDB.deleteDatabase(h);n.onsuccess=function(){En.openReqList[h]&&(En.openReqList[h]=null),ne()&&h in localStorage&&delete localStorage[h],t(null,{ok:!0})},n.onerror=an(t)};var y=Vo[h];if(y)return p=y.idb,e._meta=y.global,void n.nextTick(function(){r(null,e)});var m;m=t.storage?kn(h,t.storage):indexedDB.open(h,Bo),"openReqList"in En||(En.openReqList={}),En.openReqList[h]=m,m.onupgradeneeded=function(e){function t(){var e=c[l-1];l++,e&&e(r,t)}var n=e.target.result;if(e.oldVersion<1)return o(n);var r=e.currentTarget.transaction;e.oldVersion<3&&a(n),e.oldVersion<4&&u(n);var c=[i,s,f,d],l=e.oldVersion;t()},m.onsuccess=function(t){p=t.target.result,p.onversionchange=function(){p.close(),delete Vo[h]},p.onabort=function(e){console.error("Database has a global failure",e.target.error),p.close(),delete Vo[h]};var n=p.transaction([Ho,Jo,Fo],"readwrite"),o=n.objectStore(Ho).get(Ho),i=null,a=null,s=null;o.onsuccess=function(t){var o=function(){null!==i&&null!==a&&null!==s&&(e._meta={name:h,instanceId:s,blobSupport:i,docCount:a},Vo[h]={idb:p,global:e._meta},r(null,e))},u=t.target.result||{id:Ho};h+"_id"in u?(s=u[h+"_id"],o()):(s=D(),u[h+"_id"]=s,n.objectStore(Ho).put(u).onsuccess=function(){o()}),Go||(Go=gn(n)),Go.then(function(e){i=e,o()});var c=n.objectStore(Fo).index("deletedOrLocal");c.count(IDBKeyRange.only("0")).onsuccess=function(e){a=e.target.result,o()}}},m.onerror=function(e){var t="Failed to open indexedDB, are you in private browsing mode?";console.error(t),r(A(kr,t))}}function kn(e,t){try{return indexedDB.open(e,{version:Bo,storage:t})}catch(n){return indexedDB.open(e,Bo)}}function qn(e){return decodeURIComponent(window.escape(e))}function xn(e){return 65>e?e-48:e-55}function An(e,t,n){for(var r="";n>t;)r+=String.fromCharCode(xn(e.charCodeAt(t++))<<4|xn(e.charCodeAt(t++)));return r}function Tn(e,t,n){for(var r="";n>t;)r+=String.fromCharCode(xn(e.charCodeAt(t+2))<<12|xn(e.charCodeAt(t+3))<<8|xn(e.charCodeAt(t))<<4|xn(e.charCodeAt(t+1))),t+=4;return r}function On(e,t){return"UTF-8"===t?qn(An(e,0,e.length)):Tn(e,0,e.length)}function jn(e){return"'"+e+"'"}function Cn(e){return e.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"")}function Ln(e){return e.replace(/\u0001\u0001/g,"\x00").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,"")}function In(e){return delete e._id,delete e._rev,JSON.stringify(e)}function Rn(e,t,n){return e=JSON.parse(e),e._id=t,e._rev=n,e}function Dn(e){for(var t="(";e--;)t+="?",e&&(t+=",");return t+")"}function Nn(e,t,n,r,o){return"SELECT "+e+" FROM "+("string"==typeof t?t:t.join(" JOIN "))+(n?" ON "+n:"")+(r?" WHERE "+("string"==typeof r?r:r.join(" AND ")):"")+(o?" ORDER BY "+o:"")}function Bn(e,t,n){function r(){++i===e.length&&o()}function o(){if(a.length){var e="SELECT DISTINCT digest AS digest FROM "+ei+" WHERE seq IN "+Dn(a.length);n.executeSql(e,a,function(e,t){for(var n=[],r=0;r0;){var e=S.pop();e(null,b)}}function h(e,t){if(0===t){var n="CREATE TABLE IF NOT EXISTS "+Zo+" (dbid, db_version INTEGER)",c="CREATE TABLE IF NOT EXISTS "+$o+" (digest UNIQUE, escaped TINYINT(1), body BLOB)",f="CREATE TABLE IF NOT EXISTS "+ei+" (digest, seq INTEGER)",l="CREATE TABLE IF NOT EXISTS "+zo+" (id unique, json, winningseq, max_seq INTEGER UNIQUE)",h="CREATE TABLE IF NOT EXISTS "+Qo+" (seq INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, json, deleted TINYINT(1), doc_id, rev)",p="CREATE TABLE IF NOT EXISTS "+Yo+" (id UNIQUE, rev, json)";e.executeSql(c),e.executeSql(p),e.executeSql(f,[],function(){e.executeSql(ai),e.executeSql(si)}),e.executeSql(l,[],function(){e.executeSql(ii),e.executeSql(h,[],function(){e.executeSql(ri),e.executeSql(oi),e.executeSql(n,[],function(){var t="INSERT INTO "+Zo+" (db_version, dbid) VALUES (?,?)";b=D();var n=[Xo,b];e.executeSql(t,n,function(){d()})})})})}else{var v=function(){var n=Xo>t;n&&e.executeSql("UPDATE "+Zo+" SET db_version = "+Xo);var r="SELECT dbid FROM "+Zo;e.executeSql(r,[],function(e,t){b=t.rows.item(0).dbid,d()})},y=[r,o,i,a,s,u,v],_=t,m=function(e){y[_-1](e,m),_++};m(e)}}function p(){x.transaction(function(e){f(e,function(){v(e)})},Fn(t),n)}function v(e){var t="SELECT sql FROM sqlite_master WHERE tbl_name = "+Zo;e.executeSql(t,[],function(e,t){t.rows.length?/db_version/.test(t.rows.item(0).sql)?e.executeSql("SELECT db_version FROM "+Zo,[],function(e,t){var n=t.rows.item(0).db_version;h(e,n)}):e.executeSql("ALTER TABLE "+Zo+" ADD COLUMN db_version INTEGER",[],function(){h(e,1)}):h(e,0)})}function y(e,t){if(-1!==g._docCount)return t(g._docCount);var n=Nn("COUNT("+zo+".id) AS 'num'",[zo,Qo],ui,Qo+".deleted=0");e.executeSql(n,[],function(e,n){g._docCount=n.rows.item(0).num,t(g._docCount)})}var m,g=this,b=null,w=Mn(e),S=[];g._docCount=-1,g._name=e.name;var k=Hn({name:g._name,version:ni,description:g._name,size:w,location:e.location,createFromLocation:e.createFromLocation,androidDatabaseImplementation:e.androidDatabaseImplementation});if(k.error)return Fn(t)(k.error);var x=k.db;"function"!=typeof x.readTransaction&&(x.readTransaction=x.transaction),p(),g.type=function(){return"websql"},g._id=l(function(e){e(null,b)}),g._info=function(e){x.readTransaction(function(t){y(t,function(n){var r="SELECT MAX(seq) AS seq FROM "+Qo;t.executeSql(r,[],function(t,r){var o=r.rows.item(0).seq||0;e(null,{doc_count:n,update_seq:o,sqlite_plugin:x._sqlitePlugin,websql_encoding:m})})})},Fn(e))},g._bulkDocs=function(t,n,r){Jn(e,t,n,g,x,Gn.Changes,r)},g._get=function(e,t,n){function r(){n(a,{doc:o,metadata:i,ctx:s})}var o,i,a,s=t.ctx;if(!s)return x.readTransaction(function(r){g._get(e,Vn.extend({ctx:r},t),n)});var u,c;t.rev?(u=Nn(ci,[zo,Qo],zo+".id="+Qo+".doc_id",[Qo+".doc_id=?",Qo+".rev=?"]),c=[e,t.rev]):(u=Nn(ci,[zo,Qo],ui,zo+".id=?"),c=[e]),s.executeSql(u,c,function(e,n){if(!n.rows.length)return a=A(fr,"missing"),r();var s=n.rows.item(0);return i=tn(s.metadata),s.deleted&&!t.rev?(a=A(fr,"deleted"),r()):(o=Rn(s.data,i.id,s.rev),void r())})},g._allDocs=function(e,t){var n,r=[],o="startkey"in e?e.startkey:!1,i="endkey"in e?e.endkey:!1,a="key"in e?e.key:!1,s="descending"in e?e.descending:!1,u="limit"in e?e.limit:-1,c="skip"in e?e.skip:0,f=e.inclusive_end!==!1,l=[],d=[];if(a!==!1)d.push(zo+".id = ?"),l.push(a);else if(o!==!1||i!==!1){if(o!==!1&&(d.push(zo+".id "+(s?"<=":">=")+" ?"),l.push(o)),i!==!1){var h=s?">":"<";f&&(h+="="),d.push(zo+".id "+h+" ?"),l.push(i)}a!==!1&&(d.push(zo+".id = ?"),l.push(a))}"ok"!==e.deleted&&d.push(Qo+".deleted = 0"),x.readTransaction(function(t){y(t,function(o){if(n=o,0!==u){var i=Nn(ci,[zo,Qo],ui,d,zo+".id "+(s?"DESC":"ASC"));i+=" LIMIT "+u+" OFFSET "+c,t.executeSql(i,l,function(t,n){for(var o=0,i=n.rows.length;i>o;o++){var a=n.rows.item(o),s=tn(a.metadata),u=s.id,c=Rn(a.data,u,a.rev),f=c._rev,l={id:u,key:u,value:{rev:f}};if(e.include_docs&&(l.doc=c,l.doc._rev=f,e.conflicts&&(l.doc._conflicts=q(s)),Kn(l.doc,e,g,t)),a.deleted){if("ok"!==e.deleted)continue;l.value.deleted=!0,l.doc=null}r.push(l)}})}})},Fn(t),function(){t(null,{total_rows:n,offset:e.skip,rows:r})})},g._changes=function(e){function t(){var t=zo+".json AS metadata, "+zo+".max_seq AS maxSeq, "+Qo+".json AS winningDoc, "+Qo+".rev AS winningRev ",n=zo+" JOIN "+Qo,u=zo+".id="+Qo+".doc_id AND "+zo+".winningseq="+Qo+".seq",c=["maxSeq > ?"],f=[e.since];e.doc_ids&&(c.push(zo+".id IN "+Dn(e.doc_ids.length)),f=f.concat(e.doc_ids));var l="maxSeq "+(r?"DESC":"ASC"),d=Nn(t,n,u,c,l),h=me(e);e.view||e.filter||(d+=" LIMIT "+o);var p=e.since||0;x.readTransaction(function(t){t.executeSql(d,f,function(t,n){function r(t){return function(){e.onChange(t)}}for(var u=0,c=n.rows.length;c>u;u++){var f=n.rows.item(u),l=tn(f.metadata);p=f.maxSeq;var d=Rn(f.winningDoc,l.id,f.winningRev),v=e.processChange(d,l,e);v.seq=f.maxSeq;var y=h(v);if("object"==typeof y)return e.complete(y);if(y&&(s++,i&&a.push(v),e.attachments&&e.include_docs?Kn(d,e,g,t,r(v)):r(v)()),s===o)break}})},Fn(e.complete),function(){e.continuous||e.complete(null,{results:a,last_seq:p})})}if(e=c(e),e.continuous){var n=g._name+":"+D();return Gn.Changes.addListener(g._name,n,g,e),Gn.Changes.notify(g._name),{cancel:function(){Gn.Changes.removeListener(g._name,n)}}}var r=e.descending;e.since=e.since&&!r?e.since:0;var o="limit"in e?e.limit:-1;0===o&&(o=1);var i;i="return_docs"in e?e.return_docs:"returnDocs"in e?e.returnDocs:!0;var a=[],s=0;t()},g._close=function(e){e()},g._getAttachment=function(e,t,n){var r,o=t.ctx,i=e.digest,a=e.content_type,s="SELECT escaped, CASE WHEN escaped = 1 THEN body ELSE HEX(body) END AS body FROM "+$o+" WHERE digest=?";o.executeSql(s,[i],function(e,o){var i=o.rows.item(0),s=i.escaped?Ln(i.body):On(i.body,m);r=t.binary?ye(s,a):Vr(s),n(null,r)})},g._getRevisionTree=function(e,t){x.readTransaction(function(n){var r="SELECT json AS metadata FROM "+zo+" WHERE id = ?";n.executeSql(r,[e],function(e,n){if(n.rows.length){var r=tn(n.rows.item(0).metadata);t(null,r.rev_tree)}else t(A(fr))})})},g._doCompaction=function(e,t,n){return t.length?void x.transaction(function(n){var r="SELECT json AS metadata FROM "+zo+" WHERE id = ?";n.executeSql(r,[e],function(n,r){var o=tn(r.rows.item(0).metadata);E(o.rev_tree,function(e,n,r,o,i){var a=n+"-"+r;-1!==t.indexOf(a)&&(i.status="missing")});var i="UPDATE "+zo+" SET json = ? WHERE id = ?";n.executeSql(i,[nn(o),e])}),Bn(t,e,n)},Fn(n),function(){n()}):n()},g._getLocal=function(e,t){x.readTransaction(function(n){var r="SELECT json, rev FROM "+Yo+" WHERE id=?";n.executeSql(r,[e],function(n,r){if(r.rows.length){var o=r.rows.item(0),i=Rn(o.json,e,o.rev);t(null,i)}else t(A(fr))})})},g._putLocal=function(e,t,n){function r(e){var r,c;i?(r="UPDATE "+Yo+" SET rev=?, json=? WHERE id=? AND rev=?",c=[o,u,a,i]):(r="INSERT INTO "+Yo+" (id, rev, json) VALUES (?,?,?)",c=[a,o,u]),e.executeSql(r,c,function(e,r){r.rowsAffected?(s={ok:!0,id:a,rev:o},t.ctx&&n(null,s)):n(A(lr))},function(){return n(A(lr)),!1})}"function"==typeof t&&(n=t,t={}),delete e._revisions;var o,i=e._rev,a=e._id;o=i?e._rev="0-"+(parseInt(i.split("-")[1],10)+1):e._rev="0-1";var s,u=In(e);t.ctx?r(t.ctx):x.transaction(r,Fn(n),function(){s&&n(null,s)})},g._removeLocal=function(e,t,n){function r(r){var i="DELETE FROM "+Yo+" WHERE id=? AND rev=?",a=[e._id,e._rev];r.executeSql(i,a,function(r,i){return i.rowsAffected?(o={ok:!0,id:e._id,rev:"0-0"},void(t.ctx&&n(null,o))):n(A(fr))})}"function"==typeof t&&(n=t,t={});var o;t.ctx?r(t.ctx):x.transaction(r,Fn(n),function(){o&&n(null,o)})},g._destroy=function(e,t){Gn.Changes.removeAllListeners(g._name),x.transaction(function(e){var t=[zo,Qo,$o,Zo,Yo,ei];t.forEach(function(t){e.executeSql("DROP TABLE IF EXISTS "+t,[])})},Fn(t),function(){ne()&&(delete window.localStorage["_pouch__websqldb_"+g._name],delete window.localStorage[g._name]),t(null,{ok:!0})})}}var Vn=e(7),Xn=o(Vn),zn=o(e(6)),Qn=o(e(12)),$n=e(4),Yn=o(e(1)),Zn=o(e(2)),er=e(10),tr=o(er),nr=o(e(8)),rr=o(e(14)),or=o(e(15)),ir=o(e(16)),ar="function"==typeof Promise?Promise:nr,sr=Zn("pouchdb:api");zn(x,Error),x.prototype.toString=function(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})};var ur=new x({status:401,error:"unauthorized",reason:"Name or password is incorrect."}),cr=new x({status:400,error:"bad_request",reason:"Missing JSON list of 'docs'"}),fr=new x({status:404,error:"not_found",reason:"missing"}),lr=new x({status:409,error:"conflict",reason:"Document update conflict"}),dr=new x({status:400,error:"invalid_id",reason:"_id field must contain a string"}),hr=new x({status:412,error:"missing_id",reason:"_id is required for puts"}),pr=new x({status:400,error:"bad_request",reason:"Only reserved document ids may start with underscore."}),vr=new x({status:412,error:"precondition_failed",reason:"Database not open"}),yr=new x({status:500,error:"unknown_error",reason:"Database encountered an unknown error"}),_r=new x({status:500,error:"badarg",reason:"Some query argument is invalid"}),mr=new x({status:400,error:"invalid_request",reason:"Request was invalid"}),gr=new x({status:400,error:"query_parse_error",reason:"Some query parameter is invalid"}),br=new x({status:500,error:"doc_validation",reason:"Bad special document member"}),wr=new x({status:400,error:"bad_request",reason:"Something wrong with the request"}),Er=new x({status:400,error:"bad_request",reason:"Document must be a JSON object"}),Sr=new x({status:404,error:"not_found",reason:"Database not found"}),kr=new x({status:500,error:"indexed_db_went_bad",reason:"unknown"}),qr=new x({status:500,error:"web_sql_went_bad",reason:"unknown"}),xr=new x({status:500,error:"levelDB_went_went_bad",reason:"unknown"}),Ar=new x({status:403,error:"forbidden",reason:"Forbidden by design doc validate_doc_update function"}),Tr=new x({status:400,error:"bad_request",reason:"Invalid rev format"}),Or=new x({status:412,error:"file_exists",reason:"The database could not be created, the file already exists."}),jr=new x({status:412,error:"missing_stub"}),Cr=new x({status:413,error:"invalid_url",reason:"Provided URL is invalid"}),Lr={UNAUTHORIZED:ur,MISSING_BULK_DOCS:cr,MISSING_DOC:fr,REV_CONFLICT:lr,INVALID_ID:dr,MISSING_ID:hr,RESERVED_ID:pr,NOT_OPEN:vr,UNKNOWN_ERROR:yr,BAD_ARG:_r,INVALID_REQUEST:mr,QUERY_PARSE_ERROR:gr,DOC_VALIDATION:br,BAD_REQUEST:wr,NOT_AN_OBJECT:Er,DB_MISSING:Sr,WSQ_ERROR:qr,LDB_ERROR:xr,FORBIDDEN:Ar,INVALID_REV:Tr,FILE_EXISTS:Or,MISSING_STUB:jr,IDB_ERROR:kr,INVALID_URL:Cr},Ir=function(e,t,n){var r=Object.keys(Lr).filter(function(n){var r=Lr[n];return"function"!=typeof r&&r[e]===t}),o=n&&r.filter(function(e){var t=Lr[e];return t.message===n})[0]||r[0];return o?Lr[o]:null};zn(O,$n.EventEmitter),O.prototype.cancel=function(){this.isCancelled=!0,this.db.taskqueue.isReady&&this.emit("cancel")},O.prototype.doChanges=function(e){var t=this,n=e.complete;if(e=c(e),"live"in e&&!("continuous"in e)&&(e.continuous=e.live),e.processChange=j,"latest"===e.since&&(e.since="now"),e.since||(e.since=0),"now"===e.since)return void this.db.info().then(function(r){return t.isCancelled?void n(null,{status:"cancelled"}):(e.since=r.update_seq,void t.doChanges(e))},n);if(e.continuous&&"now"!==e.since&&this.db.info().then(function(e){t.startSeq=e.update_seq},function(e){if("idbNull"!==e.id)throw e}),e.filter&&"string"==typeof e.filter&&("_view"===e.filter?e.view=w(e.view):e.filter=w(e.filter),"http"!==this.db.type()&&!e.doc_ids))return this.filterChanges(e);"descending"in e||(e.descending=!1),e.limit=0===e.limit?1:e.limit,e.complete=n;var r=this.db._changes(e);if(r&&"function"==typeof r.cancel){var o=t.cancel;t.cancel=Yn(function(e){r.cancel(),o.apply(this,e)})}},O.prototype.filterChanges=function(e){var t=this,n=e.complete;if("_view"===e.filter){if(!e.view||"string"!=typeof e.view){var r=A(wr,"`view` filter parameter not found or invalid.");return n(r)}var o=b(e.view);this.db.get("_design/"+o[0],function(r,i){if(t.isCancelled)return n(null,{status:"cancelled"});if(r)return n(T(r));var a=i&&i.views&&i.views[o[1]]&&i.views[o[1]].map;return a?(e.filter=g(a),void t.doChanges(e)):n(A(fr,i.views?"missing json key: "+o[1]:"missing json key: views"))})}else{var i=b(e.filter);if(!i)return t.doChanges(e);this.db.get("_design/"+i[0],function(r,o){if(t.isCancelled)return n(null,{status:"cancelled"});if(r)return n(T(r));var a=o&&o.filters&&o.filters[i[1]];return a?(e.filter=m(a),void t.doChanges(e)):n(A(fr,o&&o.filters?"missing json key: "+i[1]:"missing json key: filters"))})}};var Rr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(""),Dr=N(["_id","_rev","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]),Nr=N(["_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);zn(Q,$n.EventEmitter),Q.prototype.post=d("post",function(e,t,n){return"function"==typeof t&&(n=t,t={}),"object"!=typeof e||Array.isArray(e)?n(A(Er)):void this.bulkDocs({docs:[e]},t,W(n))}),Q.prototype.put=d("put",Yn(function(e){var t,n,r,o,i=e.shift(),a="_id"in i;if("object"!=typeof i||Array.isArray(i))return(o=e.pop())(A(Er));for(;;)if(t=e.shift(),n=typeof t,"string"!==n||a?"string"!==n||!a||"_rev"in i?"object"===n?r=t:"function"===n&&(o=t):i._rev=t:(i._id=t,a=!0),!e.length)break;return r=r||{},B(i._id),L(i._id)&&"function"==typeof this._putLocal?i._deleted?this._removeLocal(i,o):this._putLocal(i,o):void this.bulkDocs({docs:[i]},r,W(o))})),Q.prototype.putAttachment=d("putAttachment",function(e,t,n,r,o,i){function a(e){return e._attachments=e._attachments||{},e._attachments[t]={content_type:o,data:r},s.put(e)}var s=this;return"function"==typeof o&&(i=o,o=r,r=n,n=null),"undefined"==typeof o&&(o=r,r=n,n=null),s.get(e).then(function(e){if(e._rev!==n)throw A(lr);return a(e)},function(t){if(t.reason===fr.message)return a({_id:e});throw t})}),Q.prototype.removeAttachment=d("removeAttachment",function(e,t,n,r){var o=this;o.get(e,function(e,i){return e?void r(e):i._rev!==n?void r(A(lr)):i._attachments?(delete i._attachments[t],0===Object.keys(i._attachments).length&&delete i._attachments,void o.put(i,r)):r()})}),Q.prototype.remove=d("remove",function(e,t,n,r){var o;"string"==typeof t?(o={_id:e,_rev:t},"function"==typeof n&&(r=n,n={})):(o=e,"function"==typeof t?(r=t,n={}):(r=n,n=t)),n=n||{},n.was_delete=!0;var i={_id:o._id,_rev:o._rev||n.rev};return i._deleted=!0,L(i._id)&&"function"==typeof this._removeLocal?this._removeLocal(o,r):void this.bulkDocs({docs:[i]},n,W(r))}),Q.prototype.revsDiff=d("revsDiff",function(e,t,n){function r(e,t){s.has(e)||s.set(e,{missing:[]}),s.get(e).missing.push(t)}function o(t,n){var o=e[t].slice(0);E(n,function(e,n,i,a,s){var u=n+"-"+i,c=o.indexOf(u);-1!==c&&(o.splice(c,1),"available"!==s.status&&r(t,u))}),o.forEach(function(e){r(t,e)})}"function"==typeof t&&(n=t,t={});var i=Object.keys(e);if(!i.length)return n(null,{});var a=0,s=new Qn.Map;i.map(function(t){this._getRevisionTree(t,function(r,u){if(r&&404===r.status&&"missing"===r.message)s.set(t,{missing:e[t]});else{if(r)return n(r);o(t,u)}if(++a===i.length){var c={};return s.forEach(function(e,t){c[t]=e}),n(null,c)}})},this)}),Q.prototype.bulkGet=d("bulkGet",function(e,t){C(this,e,t)}),Q.prototype.compactDocument=d("compactDocument",function(e,t,n){var r=this;this._getRevisionTree(e,function(o,i){if(o)return n(o);var a=G(i),s=[],u=[];Object.keys(a).forEach(function(e){a[e]>t&&s.push(e)}),E(i,function(e,t,n,r,o){var i=t+"-"+n;"available"===o.status&&-1!==s.indexOf(i)&&u.push(i)}),r._doCompaction(e,u,n)})}),Q.prototype.compact=d("compact",function(e,t){"function"==typeof e&&(t=e,e={});var n=this;e=e||{},n._compactionQueue=n._compactionQueue||[],n._compactionQueue.push({opts:e,callback:t}),1===n._compactionQueue.length&&X(n)}),Q.prototype._compact=function(e,t){function n(e){a.push(o.compactDocument(e.id,0))}function r(e){var n=e.last_seq;ar.all(a).then(function(){return h(o,"_local/compaction",function(e){return!e.last_seq||e.last_seqs)c(u,e,r,o),ro(n);else{c(u,e,r,o);var f=u.end(!0),l=Oe(f);t(null,l),u.destroy()}}var r="string"==typeof e,o=r?e.length:e.byteLength,i=Math.min(oo,o),a=Math.ceil(o/i),s=0,u=r?new or:new or.ArrayBuffer,c=r?Ce:je;n()});zn(Fe,$n.EventEmitter),Fe.prototype.cancel=function(){this.cancelled=!0,this.state="cancelled",this.emit("cancel")},Fe.prototype.ready=function(e,t){function n(){o.cancel()}function r(){e.removeListener("destroyed",n),t.removeListener("destroyed",n)}var o=this;o._readyCalled||(o._readyCalled=!0,e.once("destroyed",n),t.once("destroyed",n),o.once("complete",r))};var ao={replicate:Ue,toPouch:Me},so=ao.replicate;zn(He,$n.EventEmitter),He.prototype.cancel=function(){this.canceled||(this.canceled=!0,this.push.cancel(),this.pull.cancel())};var uo=25,co=50,fo={},lo=1800,ho=Zn("pouchdb:http");tt.valid=function(){return!0},nt.prototype.add=function(e){return this.promise=this.promise["catch"](function(){}).then(function(){return e()}),this.promise},nt.prototype.finish=function(){return this.promise};var po,vo=function(e,t){return t&&e.then(function(e){n.nextTick(function(){t(null,e)})},function(e){n.nextTick(function(){t(e)})}),e},yo=function(e){return Yn(function(t){var n=t.pop(),r=e.apply(this,t);return"function"==typeof n&&vo(r,n),r})},_o=function(e,t){return e.then(function(e){return t().then(function(){return e})},function(e){return t().then(function(){throw e})})},mo=function(e,t){return function(){var n=arguments,r=this;return e.add(function(){return t.apply(r,n)})}},go=function(e){for(var t={},n=0,r=e.length;r>n;n++)t["$"+e[n]]=!0;var o=Object.keys(t),i=new Array(o.length);for(n=0,r=o.length;r>n;n++)i[n]=o[n].substring(1);return i},bo={uniq:go,sequentialize:mo,fin:_o,callbackify:yo,promisedCallback:vo},wo=tr.collate,Eo=tr.toIndexableString,So=tr.normalizeKey,ko=tr.parseIndexableString;po="undefined"!=typeof console&&"function"==typeof console.log?Function.prototype.bind.call(console.log,console):function(){};var qo=bo.callbackify,xo=bo.sequentialize,Ao=bo.uniq,To=bo.fin,Oo=bo.promisedCallback,jo={},Co=new nt,Lo=50,Io={_sum:function(e,t){return yt(t)},_count:function(e,t){return t.length},_stats:function(e,t){function n(e){for(var t=0,n=0,r=e.length;r>n;n++){var o=e[n];t+=o*o}return t}return{sum:yt(t),min:Math.min.apply(null,t),max:Math.max.apply(null,t),count:t.length,sumsqr:n(t)}}},Ro=qo(function(){var e=this;return"http"===e.type()?Rt(e):"function"==typeof e._viewCleanup?kt(e):Dt(e)}),Do=function(e,t,n){"function"==typeof t&&(n=t,t={}),t=t?gt(t):{},"function"==typeof e&&(e={map:e});var r=this,o=ar.resolve().then(function(){return Nt(r,e,t)});return Oo(o,n),o};zn(Bt,Error),zn(Ft,Error),zn(Mt,Error);var No={query:Do,viewCleanup:Ro},Bo=5,Fo="document-store",Mo="by-sequence",Uo="attach-store",Po="attach-seq-store",Ho="meta-store",Wo="local-store",Jo="detect-blob-support",Ko={running:!1,queue:[]};zn(wn,$n.EventEmitter),wn.prototype.addListener=function(e,t,n,r){function o(){function e(){s=!1}if(a._listeners[t]){if(s)return void(s="waiting");s=!0;var u=i(r,["style","include_docs","attachments","conflicts","filter","doc_ids","view","since","query_params","binary"]);n.changes(u).on("change",function(e){e.seq>r.since&&!r.cancelled&&(r.since=e.seq,r.onChange(e))}).on("complete",function(){"waiting"===s&&setTimeout(function(){o()},0),s=!1}).on("error",e)}}if(!this._listeners[t]){var a=this,s=!1;this._listeners[t]=o,this.on(e,o)}},wn.prototype.removeListener=function(e,t){t in this._listeners&&$n.EventEmitter.prototype.removeListener.call(this,e,this._listeners[t])},wn.prototype.notifyLocalWindows=function(e){te()?chrome.storage.local.set({dbName:e}):ne()&&(localStorage[e]="a"===localStorage[e]?"b":"a")},wn.prototype.notify=function(e){this.emit(e),this.notifyLocalWindows(e)};var Go,Vo={};En.valid=function(){var e="undefined"!=typeof openDatabase&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform);return!e&&"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange},En.Changes=new wn;var Xo=7,zo=jn("document-store"),Qo=jn("by-sequence"),$o=jn("attach-store"),Yo=jn("local-store"),Zo=jn("metadata-store"),ei=jn("attach-seq-store"),ti={},ni=1,ri="CREATE INDEX IF NOT EXISTS 'by-seq-deleted-idx' ON "+Qo+" (seq, deleted)",oi="CREATE UNIQUE INDEX IF NOT EXISTS 'by-seq-doc-id-rev' ON "+Qo+" (doc_id, rev)",ii="CREATE INDEX IF NOT EXISTS 'doc-winningseq-idx' ON "+zo+" (winningseq)",ai="CREATE INDEX IF NOT EXISTS 'attach-seq-seq-idx' ON "+ei+" (seq)",si="CREATE UNIQUE INDEX IF NOT EXISTS 'attach-seq-digest-idx' ON "+ei+" (digest, seq)",ui=Qo+".seq = "+zo+".winningseq",ci=Qo+".seq AS seq, "+Qo+".deleted AS deleted, "+Qo+".json AS data, "+Qo+".rev AS rev, "+zo+".json AS metadata";Gn.valid=Wn,Gn.Changes=new wn;var fi={idb:En,websql:Gn};ee.ajax=he,ee.utils=zr,ee.Errors=Lr,ee.replicate=ao.replicate,ee.sync=Pe,ee.version="5.2.1",ee.adapter("http",tt),ee.adapter("https",tt),ee.plugin(No),Object.keys(fi).forEach(function(e){ee.adapter(e,fi[e],!0)}),t.exports=ee}).call(this,e(13),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{1:1,10:10,12:12,13:13,14:14,15:15,16:16,2:2,4:4,6:6,7:7,8:8}]},{},[17])(17)}); 12 | -------------------------------------------------------------------------------- /js/uuid.js: -------------------------------------------------------------------------------- 1 | function UUIDjs() { 2 | }; 3 | 4 | UUIDjs.maxFromBits = function(bits) { 5 | return Math.pow(2, bits); 6 | }; 7 | 8 | UUIDjs.limitUI04 = UUIDjs.maxFromBits(4); 9 | UUIDjs.limitUI06 = UUIDjs.maxFromBits(6); 10 | UUIDjs.limitUI08 = UUIDjs.maxFromBits(8); 11 | UUIDjs.limitUI12 = UUIDjs.maxFromBits(12); 12 | UUIDjs.limitUI14 = UUIDjs.maxFromBits(14); 13 | UUIDjs.limitUI16 = UUIDjs.maxFromBits(16); 14 | UUIDjs.limitUI32 = UUIDjs.maxFromBits(32); 15 | UUIDjs.limitUI40 = UUIDjs.maxFromBits(40); 16 | UUIDjs.limitUI48 = UUIDjs.maxFromBits(48); 17 | 18 | // Returns a random integer between min and max 19 | // Using Math.round() will give you a non-uniform distribution! 20 | // @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/random 21 | function getRandomInt(min, max) { 22 | return Math.floor(Math.random() * (max - min + 1)) + min; 23 | } 24 | 25 | UUIDjs.randomUI04 = function() { 26 | return getRandomInt(0, UUIDjs.limitUI04-1); 27 | }; 28 | UUIDjs.randomUI06 = function() { 29 | return getRandomInt(0, UUIDjs.limitUI06-1); 30 | }; 31 | UUIDjs.randomUI08 = function() { 32 | return getRandomInt(0, UUIDjs.limitUI08-1); 33 | }; 34 | UUIDjs.randomUI12 = function() { 35 | return getRandomInt(0, UUIDjs.limitUI12-1); 36 | }; 37 | UUIDjs.randomUI14 = function() { 38 | return getRandomInt(0, UUIDjs.limitUI14-1); 39 | }; 40 | UUIDjs.randomUI16 = function() { 41 | return getRandomInt(0, UUIDjs.limitUI16-1); 42 | }; 43 | UUIDjs.randomUI32 = function() { 44 | return getRandomInt(0, UUIDjs.limitUI32-1); 45 | }; 46 | UUIDjs.randomUI40 = function() { 47 | return (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << 40 - 30)) * (1 << 30); 48 | }; 49 | UUIDjs.randomUI48 = function() { 50 | return (0 | Math.random() * (1 << 30)) + (0 | Math.random() * (1 << 48 - 30)) * (1 << 30); 51 | }; 52 | 53 | UUIDjs.paddedString = function(string, length, z) { 54 | string = String(string); 55 | z = (!z) ? '0' : z; 56 | var i = length - string.length; 57 | for (; i > 0; i >>>= 1, z += z) { 58 | if (i & 1) { 59 | string = z + string; 60 | } 61 | } 62 | return string; 63 | }; 64 | 65 | UUIDjs.prototype.fromParts = function(timeLow, timeMid, timeHiAndVersion, clockSeqHiAndReserved, clockSeqLow, node) { 66 | this.version = (timeHiAndVersion >> 12) & 0xF; 67 | this.hex = UUIDjs.paddedString(timeLow.toString(16), 8) 68 | + '-' 69 | + UUIDjs.paddedString(timeMid.toString(16), 4) 70 | + '-' 71 | + UUIDjs.paddedString(timeHiAndVersion.toString(16), 4) 72 | + '-' 73 | + UUIDjs.paddedString(clockSeqHiAndReserved.toString(16), 2) 74 | + UUIDjs.paddedString(clockSeqLow.toString(16), 2) 75 | + '-' 76 | + UUIDjs.paddedString(node.toString(16), 12); 77 | return this; 78 | }; 79 | 80 | UUIDjs.prototype.toString = function() { 81 | return this.hex; 82 | }; 83 | UUIDjs.prototype.toURN = function() { 84 | return 'urn:uuid:' + this.hex; 85 | }; 86 | 87 | UUIDjs.prototype.toBytes = function() { 88 | var parts = this.hex.split('-'); 89 | var ints = []; 90 | var intPos = 0; 91 | for (var i = 0; i < parts.length; i++) { 92 | for (var j = 0; j < parts[i].length; j+=2) { 93 | ints[intPos++] = parseInt(parts[i].substr(j, 2), 16); 94 | } 95 | } 96 | return ints; 97 | }; 98 | 99 | UUIDjs.prototype.equals = function(uuid) { 100 | if (!(uuid instanceof UUID)) { 101 | return false; 102 | } 103 | if (this.hex !== uuid.hex) { 104 | return false; 105 | } 106 | return true; 107 | }; 108 | 109 | UUIDjs.getTimeFieldValues = function(time) { 110 | var ts = time - Date.UTC(1582, 9, 15); 111 | var hm = ((ts / 0x100000000) * 10000) & 0xFFFFFFF; 112 | return { low: ((ts & 0xFFFFFFF) * 10000) % 0x100000000, 113 | mid: hm & 0xFFFF, hi: hm >>> 16, timestamp: ts }; 114 | }; 115 | 116 | UUIDjs._create4 = function() { 117 | return new UUIDjs().fromParts( 118 | UUIDjs.randomUI32(), 119 | UUIDjs.randomUI16(), 120 | 0x4000 | UUIDjs.randomUI12(), 121 | 0x80 | UUIDjs.randomUI06(), 122 | UUIDjs.randomUI08(), 123 | UUIDjs.randomUI48() 124 | ); 125 | }; 126 | 127 | UUIDjs._create1 = function() { 128 | var now = new Date().getTime(); 129 | var sequence = UUIDjs.randomUI14(); 130 | var node = (UUIDjs.randomUI08() | 1) * 0x10000000000 + UUIDjs.randomUI40(); 131 | var tick = UUIDjs.randomUI04(); 132 | var timestamp = 0; 133 | var timestampRatio = 1/4; 134 | 135 | if (now != timestamp) { 136 | if (now < timestamp) { 137 | sequence++; 138 | } 139 | timestamp = now; 140 | tick = UUIDjs.randomUI04(); 141 | } else if (Math.random() < timestampRatio && tick < 9984) { 142 | tick += 1 + UUIDjs.randomUI04(); 143 | } else { 144 | sequence++; 145 | } 146 | 147 | var tf = UUIDjs.getTimeFieldValues(timestamp); 148 | var tl = tf.low + tick; 149 | var thav = (tf.hi & 0xFFF) | 0x1000; 150 | 151 | sequence &= 0x3FFF; 152 | var cshar = (sequence >>> 8) | 0x80; 153 | var csl = sequence & 0xFF; 154 | 155 | return new UUIDjs().fromParts(tl, tf.mid, thav, cshar, csl, node); 156 | }; 157 | 158 | UUIDjs.create = function(version) { 159 | version = version || 4; 160 | return this['_create' + version](); 161 | }; 162 | 163 | UUIDjs.fromTime = function(time, last) { 164 | last = (!last) ? false : last; 165 | var tf = UUIDjs.getTimeFieldValues(time); 166 | var tl = tf.low; 167 | var thav = (tf.hi & 0xFFF) | 0x1000; // set version '0001' 168 | if (last === false) { 169 | return new UUIDjs().fromParts(tl, tf.mid, thav, 0, 0, 0); 170 | } else { 171 | return new UUIDjs().fromParts(tl, tf.mid, thav, 0x80 | UUIDjs.limitUI06, UUIDjs.limitUI08 - 1, UUIDjs.limitUI48 - 1); 172 | } 173 | }; 174 | 175 | UUIDjs.firstFromTime = function(time) { 176 | return UUIDjs.fromTime(time, false); 177 | }; 178 | UUIDjs.lastFromTime = function(time) { 179 | return UUIDjs.fromTime(time, true); 180 | }; 181 | 182 | UUIDjs.fromURN = function(strId) { 183 | var r, p = /^(?:urn:uuid:|\{)?([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{2})([0-9a-f]{2})-([0-9a-f]{12})(?:\})?$/i; 184 | if ((r = p.exec(strId))) { 185 | return new UUIDjs().fromParts(parseInt(r[1], 16), parseInt(r[2], 16), 186 | parseInt(r[3], 16), parseInt(r[4], 16), 187 | parseInt(r[5], 16), parseInt(r[6], 16)); 188 | } 189 | return null; 190 | }; 191 | 192 | UUIDjs.fromBytes = function(ints) { 193 | if (ints.length < 5) { 194 | return null; 195 | } 196 | var str = ''; 197 | var pos = 0; 198 | var parts = [4, 2, 2, 2, 6]; 199 | for (var i = 0; i < parts.length; i++) { 200 | for (var j = 0; j < parts[i]; j++) { 201 | var octet = ints[pos++].toString(16); 202 | if (octet.length == 1) { 203 | octet = '0' + octet; 204 | } 205 | str += octet; 206 | } 207 | if (parts[i] !== 6) { 208 | str += '-'; 209 | } 210 | } 211 | return UUIDjs.fromURN(str); 212 | }; 213 | 214 | UUIDjs.fromBinary = function(binary) { 215 | var ints = []; 216 | for (var i = 0; i < binary.length; i++) { 217 | ints[i] = binary.charCodeAt(i); 218 | if (ints[i] > 255 || ints[i] < 0) { 219 | throw new Error('Unexpected byte in binary data.'); 220 | } 221 | } 222 | return UUIDjs.fromBytes(ints); 223 | }; 224 | 225 | // Aliases to support legacy code. Do not use these when writing new code as 226 | // they may be removed in future versions! 227 | UUIDjs.new = function() { 228 | return this.create(4); 229 | }; 230 | UUIDjs.newTS = function() { 231 | return this.create(1); 232 | }; 233 | 234 | var UUID = UUIDjs; --------------------------------------------------------------------------------