diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea351c553520e1bc62d53b97a316194c48ac49e6 --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b5d016edd9c4eef0bb227af4a01c49e73c5f78dc --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "7.19.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.31.0", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0", + "raw-body": "2.5.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/stream-browserify/.airtap.yml b/node_modules/stream-browserify/.airtap.yml new file mode 100644 index 0000000000000000000000000000000000000000..2619593928441740099f5c2ae4266981aa42ac5a --- /dev/null +++ b/node_modules/stream-browserify/.airtap.yml @@ -0,0 +1,20 @@ +sauce_connect: true +loopback: airtap.local +browsers: + - name: chrome + version: latest + - name: firefox + # extended support releases 52, 60, 68 + version: [52, 60, 68, latest] + - name: safari + version: 9..latest + - name: iphone + version: latest + - name: ie + version: 9..latest + - name: microsoftedge + version: 13..latest +browserify: + - plugin: ./test/use-stream.js + - require: tape + expose: tape diff --git a/node_modules/stream-browserify/.github/FUNDING.yml b/node_modules/stream-browserify/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..1c5a6e9063c3a98d71b13ed6ed887ee002c99c2f --- /dev/null +++ b/node_modules/stream-browserify/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/stream-browserify +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/stream-browserify/.travis.yml b/node_modules/stream-browserify/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..0153d92629973b02c01836492c3fc55023bc552c --- /dev/null +++ b/node_modules/stream-browserify/.travis.yml @@ -0,0 +1,24 @@ +os: linux +dist: bionic +language: node_js +jobs: + include: + - name: Run browser tests with airtap + node_js: stable + script: npm run test:browsers + addons: + sauce_connect: true + hosts: + - airtap.local + - name: Test on stable Node.js + node_js: stable + - name: Test on Node.js 12.x + node_js: 12 + - name: Test on Node.js 10.x + node_js: 10 + - name: Test on Node.js 8.x + node_js: 8 + - name: Test on Node.js 6.x + node_js: 6 + - name: Test on Node.js 4.x + node_js: 4 diff --git a/node_modules/stream-browserify/CHANGELOG.md b/node_modules/stream-browserify/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..2a21e5bf04026abf0366a9fcf4d4f320195e1d2c --- /dev/null +++ b/node_modules/stream-browserify/CHANGELOG.md @@ -0,0 +1,8 @@ +# stream-browserify change log + +All notable changes to this project will be documented in this file. + +This project adheres to [Semantic Versioning](http://semver.org/). + +## 3.0.0 +* Upgrade to `readable-stream` 3. For breaking changes, see the [readable-stream notes](https://github.com/nodejs/readable-stream#version-3xx). diff --git a/node_modules/stream-browserify/LICENSE b/node_modules/stream-browserify/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3e7d0c01e4867c801292fd69562c7da94a88cd42 --- /dev/null +++ b/node_modules/stream-browserify/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) James Halliday + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/stream-browserify/index.js b/node_modules/stream-browserify/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9ddc30d80bbe9c4beab2c7ff3ef1489cbec9d193 --- /dev/null +++ b/node_modules/stream-browserify/index.js @@ -0,0 +1,129 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/lib/_stream_readable.js'); +Stream.Writable = require('readable-stream/lib/_stream_writable.js'); +Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); +Stream.Transform = require('readable-stream/lib/_stream_transform.js'); +Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); +Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') +Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/stream-browserify/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..f478d58dca85b2c396e2da8a2251be0071c4e9e0 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/stream-browserify/node_modules/readable-stream/GOVERNANCE.md b/node_modules/stream-browserify/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000000000000000000000000000000000000..16ffb93f24bece9519cc4a220a0c1d3c91481453 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/stream-browserify/node_modules/readable-stream/LICENSE b/node_modules/stream-browserify/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2873b3b2e595072e66330369d83e8af46655970c --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/stream-browserify/node_modules/readable-stream/README.md b/node_modules/stream-browserify/node_modules/readable-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..19117c1a059d1bfa7c6ff04d430bf21bb05b0621 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/stream-browserify/node_modules/readable-stream/errors-browser.js b/node_modules/stream-browserify/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..fb8e73e1893b100932468397b89076261f47ae61 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/errors.js b/node_modules/stream-browserify/node_modules/readable-stream/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..8471526d6e7f752d581942611d749ef6355ad1f5 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/experimentalWarning.js b/node_modules/stream-browserify/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..78e841495bf24d46a2995496bdf2816935b1e66e --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000000000000000000000000000000000000..19abfa604d5ef7bf3646c1a70a848c3f0df8105a --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..24a6bdde2903fac66f638e578b831a7600761207 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000000000000000000000000000000000000..df1f608d532606ba1df4eeaf3b6f577791dcd9ad --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000000000000000000000000000000000000..1ccb7157be8b8c35df891c2c0905685a144a2e9a --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000000000000000000000000000000000000..292415e23a192be6b7a7f35db37befa489117552 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..742c5a4674794d9e7667c02dcbeb44bf8001b4d6 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000000000000000000000000000000000000..69bda497d35f347f1a510eef0fe2408e8d31923c --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000000000000000000000000000000000000..31a17c4dc463880722098b62598fe21bc9672132 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..59c671b5af769bc5797843837056ae419ab22e80 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ce56f3c90f60d3416e8e0328375c4b20213872 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000000000000000000000000000000000000..0a34ee92e3df85fd31734c3d95a43697df8fbbb9 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f39241f98dd890dda9d4dbea076540ed43cabc --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000000000000000000000000000000000000..3fbf8927e00179deca5a8855b4b4c17da9450676 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..9332a3fdae7060505c0a081614e697fa6cb56dc0 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2ad5b6ee57f4778a1f4838f7970093c7941c1c --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/stream-browserify/node_modules/readable-stream/package.json b/node_modules/stream-browserify/node_modules/readable-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ade59e71aa0f170b4ec49a32cf0d04ab5f73ad86 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/stream-browserify/node_modules/readable-stream/readable-browser.js b/node_modules/stream-browserify/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..adbf60de832f9d6e066625f09d708670291e1bfd --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/stream-browserify/node_modules/readable-stream/readable.js b/node_modules/stream-browserify/node_modules/readable-stream/readable.js new file mode 100644 index 0000000000000000000000000000000000000000..9e0ca120ded827e5ba3343f826fa7462a841e092 --- /dev/null +++ b/node_modules/stream-browserify/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/stream-browserify/package.json b/node_modules/stream-browserify/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0ba5a5d56a24a3ad9799a7b10566e465896719d7 --- /dev/null +++ b/node_modules/stream-browserify/package.json @@ -0,0 +1,54 @@ +{ + "name": "stream-browserify", + "version": "3.0.0", + "description": "the stream module from node core for browsers", + "main": "index.js", + "dependencies": { + "inherits": "~2.0.4", + "readable-stream": "^3.5.0" + }, + "devDependencies": { + "airtap": "^1.0.2", + "safe-buffer": "^5.1.2", + "tape": "^4.13.0", + "through": "^2.3.8" + }, + "scripts": { + "test": "node test", + "test:browsers": "airtap -- test/index.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/browserify/stream-browserify.git" + }, + "homepage": "https://github.com/browserify/stream-browserify", + "keywords": [ + "stream", + "browser", + "browserify" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/3.5", + "firefox/10", + "firefox/nightly", + "chrome/10", + "chrome/latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/stream-browserify/readme.markdown b/node_modules/stream-browserify/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..16eb8ddcf94c2d32cfb68e64b1d8bb4635350075 --- /dev/null +++ b/node_modules/stream-browserify/readme.markdown @@ -0,0 +1,32 @@ +# stream-browserify + +the stream module from node core, for browsers! + +This module uses [`readable-stream`](https://github.com/nodejs/readable-stream), with additions for compatibility with npm packages that use old Node.js stream APIs. + +[![build status](https://secure.travis-ci.org/browserify/stream-browserify.svg?branch=master)](http://travis-ci.org/browserify/stream-browserify) + +## Install + +You usually do not have to install `stream-browserify` yourself! If your code runs in Node.js, `stream` is built in, or `readable-stream` can be used. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) also include the `stream-browserify` module. + +But if none of those apply, with [npm](https://npmjs.org) do: + +```bash +npm install stream-browserify +``` + +## API + +Consult the node core +[documentation on streams](http://nodejs.org/docs/latest/api/stream.html). + +## Browser Support + +Cross-browser testing generously provided by [Sauce Labs](https://saucelabs.com). + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/stream-browserify.svg)](https://saucelabs.com/u/stream-browserify) + +## License + +[MIT](./LICENSE) diff --git a/node_modules/stream-browserify/security.md b/node_modules/stream-browserify/security.md new file mode 100644 index 0000000000000000000000000000000000000000..a14ace6a57db70992630a568df6a7bf57763d26b --- /dev/null +++ b/node_modules/stream-browserify/security.md @@ -0,0 +1,10 @@ +# Security Policy + +## Supported Versions +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/stream-browserify/test/buf.js b/node_modules/stream-browserify/test/buf.js new file mode 100644 index 0000000000000000000000000000000000000000..ade09b2334d95998fc037c4c60dea89d65c14de6 --- /dev/null +++ b/node_modules/stream-browserify/test/buf.js @@ -0,0 +1,33 @@ +var path = require('path'); +var test = require('tape'); +var Buffer = require('safe-buffer').Buffer; + +var Writable = require('..').Writable; +var inherits = require('inherits'); + +inherits(TestWritable, Writable); + +function TestWritable(opt) { + if (!(this instanceof TestWritable)) + return new TestWritable(opt); + Writable.call(this, opt); + this._written = []; +} + +TestWritable.prototype._write = function(chunk, encoding, cb) { + this._written.push(chunk); + cb(); +}; + +var buf = Buffer.from([ 88 ]); + +test('.writable writing ArrayBuffer', function(t) { + var writable = new TestWritable(); + + writable.write(buf); + writable.end(); + + t.equal(writable._written.length, 1); + t.equal(writable._written[0].toString(), 'X') + t.end() +}); diff --git a/node_modules/stream-browserify/test/index.js b/node_modules/stream-browserify/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c85f61174ccc846d4afb7fac56ae4370ee9b405f --- /dev/null +++ b/node_modules/stream-browserify/test/index.js @@ -0,0 +1,2 @@ +require('./buf'); +require('./pipeline'); diff --git a/node_modules/stream-browserify/test/pipeline.js b/node_modules/stream-browserify/test/pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..a66f4f2c67dbf6e01948883d59327f77b8ace69b --- /dev/null +++ b/node_modules/stream-browserify/test/pipeline.js @@ -0,0 +1,38 @@ +var test = require('tape'); +var pipeline = require('..').pipeline; +var stream = require('..'); +var Buffer = require('safe-buffer').Buffer; + +test('supports pipeline', function(t) { + t.plan(4); + var readable = new stream.Readable({ + read: function () { + this.push(Buffer.from('chunk', 'ascii')); + } + }); + var transform1 = new stream.Transform({ + transform: function (chunk, enc, cb) { + cb(new Error('fail')); + } + }); + var transform2 = new stream.PassThrough(); + transform2.on('close', function () { + t.pass('transform2.close called'); + }); + var writable = new stream.Writable({ + write: function (chunk, enc, cb) { cb(); } + }); + writable.on('close', function () { + t.pass('writable.close called'); + }); + + pipeline( + readable, + transform1, + transform2, + writable, + function(err) { + t.ok(err); + t.equal(err.message, 'fail'); + }); +}); diff --git a/node_modules/stream-browserify/test/use-stream.js b/node_modules/stream-browserify/test/use-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..263c5b2f5d10d2d945398863ecdeb3a3a48b77f4 --- /dev/null +++ b/node_modules/stream-browserify/test/use-stream.js @@ -0,0 +1,4 @@ +// browserify plugin to swap out the `stream` builtin node shim with the stream-browserify version in this repo. +module.exports = function (b) { + b._mdeps.options.modules.stream = require.resolve('../index.js'); +}; diff --git a/node_modules/stream-http/LICENSE b/node_modules/stream-http/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..72674657171d8192807b63e8ce7cd812e39ff204 --- /dev/null +++ b/node_modules/stream-http/LICENSE @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2015 John Hiesey + +Permission is hereby granted, free of charge, +to any person obtaining a copy of this software and +associated documentation files (the "Software"), to +deal in the Software without restriction, including +without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom +the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/stream-http/README.md b/node_modules/stream-http/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c4e6f01d1c19981fd7c21c9c00f1d8e159de1828 --- /dev/null +++ b/node_modules/stream-http/README.md @@ -0,0 +1,134 @@ +# stream-http [![Build Status](https://travis-ci.org/jhiesey/stream-http.svg?branch=master)](https://travis-ci.org/jhiesey/stream-http) + +[![Sauce Test Status](https://app.saucelabs.com/browser-matrix/stream-http.svg)](https://app.saucelabs.com/u/stream-http) + +This module is an implementation of Node's native `http` module for the browser. +It tries to match Node's API and behavior as closely as possible, but some features +aren't available, since browsers don't give nearly as much control over requests. + +This is heavily inspired by, and intended to replace, [http-browserify](https://github.com/substack/http-browserify). + +## What does it do? + +In accordance with its name, `stream-http` tries to provide data to its caller before +the request has completed whenever possible. + +Backpressure, allowing the browser to only pull data from the server as fast as it is +consumed, is supported in: +* Chrome >= 58 (using `fetch` and `WritableStream`) + +The following browsers support true streaming, where only a small amount of the request +has to be held in memory at once: +* Chrome >= 43 (using the `fetch` API) +* Firefox >= 9 (using `moz-chunked-arraybuffer` responseType with xhr) + +All other supported browsers support pseudo-streaming, where the data is available before +the request finishes, but the entire response must be held in memory. This works for both +text and binary data. + +### IE note: +As of version 3.0.0, IE10 and below are no longer supported. IE11 support will remain for +now. + +## How do you use it? + +The intent is to have the same API as the client part of the +[Node HTTP module](https://nodejs.org/api/http.html). The interfaces are the same wherever +practical, although limitations in browsers make an exact clone of the Node API impossible. + +This module implements `http.request`, `http.get`, and most of `http.ClientRequest` +and `http.IncomingMessage` in addition to `http.METHODS` and `http.STATUS_CODES`. See the +Node docs for how these work. + +### Extra features compared to Node + +* The `message.url` property provides access to the final URL after all redirects. This +is useful since the browser follows all redirects silently, unlike Node. It is available +in Chrome 37 and newer, Firefox 32 and newer, and Safari 9 and newer. + +* The `options.withCredentials` boolean flag, used to indicate if the browser should send +cookies or authentication information with a CORS request. Default false. + +This module has to make some tradeoffs to support binary data and/or streaming. Generally, +the module can make a fairly good decision about which underlying browser features to use, +but sometimes it helps to get a little input from the developer. + +* The `options.mode` field passed into `http.request` or `http.get` can take on one of the +following values: + * 'default' (or any falsy value, including `undefined`): Try to provide partial data before +the request completes, but not at the cost of correctness for binary data or correctness of +the 'content-type' response header. This mode will also avoid slower code paths whenever +possible, which is particularly useful when making large requests in a browser like Safari +that has a weaker JavaScript engine. + * 'allow-wrong-content-type': Provides partial data in more cases than 'default', but +at the expense of causing the 'content-type' response header to be incorrectly reported +(as 'text/plain; charset=x-user-defined') in some browsers, notably Safari and Chrome 42 +and older. Preserves binary data whenever possible. In some cases the implementation may +also be a bit slow. This was the default in versions of this module before 1.5. + * 'prefer-streaming': Provide data before the request completes even if binary data (anything +that isn't a single-byte ASCII or UTF8 character) will be corrupted. Of course, this option +is only safe for text data. May also cause the 'content-type' response header to be +incorrectly reported (as 'text/plain; charset=x-user-defined'). + * 'disable-fetch': Force the use of plain XHR regardless of the browser declaring a fetch +capability. Preserves the correctness of binary data and the 'content-type' response header. + * 'prefer-fast': Deprecated; now a synonym for 'default', which has the same performance +characteristics as this mode did in versions before 1.5. + +* `options.requestTimeout` allows setting a timeout in millisecionds for XHR and fetch (if +supported by the browser). This is a limit on how long the entire process takes from +beginning to end. Note that this is not the same as the node `setTimeout` functions, +which apply to pauses in data transfer over the underlying socket, or the node `timeout` +option, which applies to opening the connection. + +### Features missing compared to Node + +* `http.Agent` is only a stub +* The 'socket', 'connect', 'upgrade', and 'continue' events on `http.ClientRequest`. +* Any operations, other than `request.setTimeout`, that operate directly on the underlying +socket. +* Any options that are disallowed for security reasons. This includes setting or getting +certain headers. +* `message.httpVersion` +* `message.rawHeaders` is modified by the browser, and may not quite match what is sent by +the server. +* `message.trailers` and `message.rawTrailers` will remain empty. +* Redirects are followed silently by the browser, so it isn't possible to access the 301/302 +redirect pages. + +## Example + +``` js +http.get('/bundle.js', function (res) { + var div = document.getElementById('result'); + div.innerHTML += 'GET /beep
'; + + res.on('data', function (buf) { + div.innerHTML += buf; + }); + + res.on('end', function () { + div.innerHTML += '
__END__'; + }); +}) +``` + +## Running tests + +There are two sets of tests: the tests that run in Node (found in `test/node`) and the tests +that run in the browser (found in `test/browser`). Normally the browser tests run on +[Sauce Labs](http://saucelabs.com/). + +Running `npm test` will run both sets of tests, but in order for the Sauce Labs tests to run +you will need to sign up for an account (free for open source projects) and put the +credentials in a [`.airtaprc` file](https://github.com/airtap/airtap/blob/master/doc/airtaprc.md). +You will also need to run a [Sauce Connect Proxy](https://wiki.saucelabs.com/display/DOCS/Sauce+Connect+Proxy) +with the same credentials. + +To run just the Node tests, run `npm run test-node`. + +To run the browser tests locally, run `npm run test-browser-local` and point your browser to +the link shown in your terminal. + +## License + +MIT. Copyright (C) John Hiesey and other contributors. diff --git a/node_modules/stream-http/index.js b/node_modules/stream-http/index.js new file mode 100644 index 0000000000000000000000000000000000000000..84bfe5118df7629d87044de6e672e08529ad919b --- /dev/null +++ b/node_modules/stream-http/index.js @@ -0,0 +1,85 @@ +var ClientRequest = require('./lib/request') +var response = require('./lib/response') +var extend = require('xtend') +var statusCodes = require('builtin-status-codes') +var url = require('url') + +var http = exports + +http.request = function (opts, cb) { + if (typeof opts === 'string') + opts = url.parse(opts) + else + opts = extend(opts) + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' + + var protocol = opts.protocol || defaultProtocol + var host = opts.hostname || opts.host + var port = opts.port + var path = opts.path || '/' + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']' + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path + opts.method = (opts.method || 'GET').toUpperCase() + opts.headers = opts.headers || {} + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts) + if (cb) + req.on('response', cb) + return req +} + +http.get = function get (opts, cb) { + var req = http.request(opts, cb) + req.end() + return req +} + +http.ClientRequest = ClientRequest +http.IncomingMessage = response.IncomingMessage + +http.Agent = function () {} +http.Agent.defaultMaxSockets = 4 + +http.globalAgent = new http.Agent() + +http.STATUS_CODES = statusCodes + +http.METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' +] \ No newline at end of file diff --git a/node_modules/stream-http/lib/capability.js b/node_modules/stream-http/lib/capability.js new file mode 100644 index 0000000000000000000000000000000000000000..eca763548f2d5697c8f2c91ce7b4751e4ec53600 --- /dev/null +++ b/node_modules/stream-http/lib/capability.js @@ -0,0 +1,59 @@ +exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) + +exports.writableStream = isFunction(global.WritableStream) + +exports.abortController = isFunction(global.AbortController) + +// The xhr request to example.com may violate some restrictive CSP configurations, +// so if we're running in a browser that supports `fetch`, avoid calling getXHR() +// and assume support for certain features below. +var xhr +function getXHR () { + // Cache the xhr value + if (xhr !== undefined) return xhr + + if (global.XMLHttpRequest) { + xhr = new global.XMLHttpRequest() + // If XDomainRequest is available (ie only, where xhr might not work + // cross domain), use the page location. Otherwise use example.com + // Note: this doesn't actually make an http request. + try { + xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com') + } catch(e) { + xhr = null + } + } else { + // Service workers don't have XHR + xhr = null + } + return xhr +} + +function checkTypeSupport (type) { + var xhr = getXHR() + if (!xhr) return false + try { + xhr.responseType = type + return xhr.responseType === type + } catch (e) {} + return false +} + +// If fetch is supported, then arraybuffer will be supported too. Skip calling +// checkTypeSupport(), since that calls getXHR(). +exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer') + +// These next two tests unavoidably show warnings in Chrome. Since fetch will always +// be used if it's available, just return false for these to avoid the warnings. +exports.msstream = !exports.fetch && checkTypeSupport('ms-stream') +exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer') + +// If fetch is supported, then overrideMimeType will be supported too. Skip calling +// getXHR(). +exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) + +function isFunction (value) { + return typeof value === 'function' +} + +xhr = null // Help gc diff --git a/node_modules/stream-http/lib/request.js b/node_modules/stream-http/lib/request.js new file mode 100644 index 0000000000000000000000000000000000000000..097eb80e0f1f5abc720839abd9c6bb18168fad64 --- /dev/null +++ b/node_modules/stream-http/lib/request.js @@ -0,0 +1,352 @@ +var capability = require('./capability') +var inherits = require('inherits') +var response = require('./response') +var stream = require('readable-stream') + +var IncomingMessage = response.IncomingMessage +var rStates = response.readyStates + +function decideMode (preferBinary, useFetch) { + if (capability.fetch && useFetch) { + return 'fetch' + } else if (capability.mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (capability.msstream) { + return 'ms-stream' + } else if (capability.arraybuffer && preferBinary) { + return 'arraybuffer' + } else { + return 'text' + } +} + +var ClientRequest = module.exports = function (opts) { + var self = this + stream.Writable.call(self) + + self._opts = opts + self._body = [] + self._headers = {} + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64')) + Object.keys(opts.headers).forEach(function (name) { + self.setHeader(name, opts.headers[name]) + }) + + var preferBinary + var useFetch = true + if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { + // If the use of XHR should be preferred. Not typically needed. + useFetch = false + preferBinary = true + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !capability.overrideMimeType + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch) + self._fetchTimer = null + self._socketTimeout = null + self._socketTimer = null + + self.on('finish', function () { + self._onFinish() + }) +} + +inherits(ClientRequest, stream.Writable) + +ClientRequest.prototype.setHeader = function (name, value) { + var self = this + var lowerName = name.toLowerCase() + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + } +} + +ClientRequest.prototype.getHeader = function (name) { + var header = this._headers[name.toLowerCase()] + if (header) + return header.value + return null +} + +ClientRequest.prototype.removeHeader = function (name) { + var self = this + delete self._headers[name.toLowerCase()] +} + +ClientRequest.prototype._onFinish = function () { + var self = this + + if (self._destroyed) + return + var opts = self._opts + + if ('timeout' in opts && opts.timeout !== 0) { + self.setTimeout(opts.timeout) + } + + var headersObj = self._headers + var body = null + if (opts.method !== 'GET' && opts.method !== 'HEAD') { + body = new Blob(self._body, { + type: (headersObj['content-type'] || {}).value || '' + }); + } + + // create flattened list of headers + var headersList = [] + Object.keys(headersObj).forEach(function (keyName) { + var name = headersObj[keyName].name + var value = headersObj[keyName].value + if (Array.isArray(value)) { + value.forEach(function (v) { + headersList.push([name, v]) + }) + } else { + headersList.push([name, value]) + } + }) + + if (self._mode === 'fetch') { + var signal = null + if (capability.abortController) { + var controller = new AbortController() + signal = controller.signal + self._fetchAbortController = controller + + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { + self._fetchTimer = global.setTimeout(function () { + self.emit('requestTimeout') + if (self._fetchAbortController) + self._fetchAbortController.abort() + }, opts.requestTimeout) + } + } + + global.fetch(self._opts.url, { + method: self._opts.method, + headers: headersList, + body: body || undefined, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin', + signal: signal + }).then(function (response) { + self._fetchResponse = response + self._resetTimers(false) + self._connect() + }, function (reason) { + self._resetTimers(true) + if (!self._destroyed) + self.emit('error', reason) + }) + } else { + var xhr = self._xhr = new global.XMLHttpRequest() + try { + xhr.open(self._opts.method, self._opts.url, true) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined') + + if ('requestTimeout' in opts) { + xhr.timeout = opts.requestTimeout + xhr.ontimeout = function () { + self.emit('requestTimeout') + } + } + + headersList.forEach(function (header) { + xhr.setRequestHeader(header[0], header[1]) + }) + + self._response = null + xhr.onreadystatechange = function () { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress() + break + } + } + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function () { + self._onXHRProgress() + } + } + + xhr.onerror = function () { + if (self._destroyed) + return + self._resetTimers(true) + self.emit('error', new Error('XHR error')) + } + + try { + xhr.send(body) + } catch (err) { + process.nextTick(function () { + self.emit('error', err) + }) + return + } + } +} + +/** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ +function statusValid (xhr) { + try { + var status = xhr.status + return (status !== null && status !== 0) + } catch (e) { + return false + } +} + +ClientRequest.prototype._onXHRProgress = function () { + var self = this + + self._resetTimers(false) + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect() + + self._response._onXHRProgress(self._resetTimers.bind(self)) +} + +ClientRequest.prototype._connect = function () { + var self = this + + if (self._destroyed) + return + + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self)) + self._response.on('error', function(err) { + self.emit('error', err) + }) + + self.emit('response', self._response) +} + +ClientRequest.prototype._write = function (chunk, encoding, cb) { + var self = this + + self._body.push(chunk) + cb() +} + +ClientRequest.prototype._resetTimers = function (done) { + var self = this + + global.clearTimeout(self._socketTimer) + self._socketTimer = null + + if (done) { + global.clearTimeout(self._fetchTimer) + self._fetchTimer = null + } else if (self._socketTimeout) { + self._socketTimer = global.setTimeout(function () { + self.emit('timeout') + }, self._socketTimeout) + } +} + +ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function (err) { + var self = this + self._destroyed = true + self._resetTimers(true) + if (self._response) + self._response._destroyed = true + if (self._xhr) + self._xhr.abort() + else if (self._fetchAbortController) + self._fetchAbortController.abort() + + if (err) + self.emit('error', err) +} + +ClientRequest.prototype.end = function (data, encoding, cb) { + var self = this + if (typeof data === 'function') { + cb = data + data = undefined + } + + stream.Writable.prototype.end.call(self, data, encoding, cb) +} + +ClientRequest.prototype.setTimeout = function (timeout, cb) { + var self = this + + if (cb) + self.once('timeout', cb) + + self._socketTimeout = timeout + self._resetTimers(false) +} + +ClientRequest.prototype.flushHeaders = function () {} +ClientRequest.prototype.setNoDelay = function () {} +ClientRequest.prototype.setSocketKeepAlive = function () {} + +// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method +var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'via' +] diff --git a/node_modules/stream-http/lib/response.js b/node_modules/stream-http/lib/response.js new file mode 100644 index 0000000000000000000000000000000000000000..91d190078b56154ddff5672df83962ebade68db8 --- /dev/null +++ b/node_modules/stream-http/lib/response.js @@ -0,0 +1,211 @@ +var capability = require('./capability') +var inherits = require('inherits') +var stream = require('readable-stream') + +var rStates = exports.readyStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 +} + +var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, resetTimers) { + var self = this + stream.Readable.call(self) + + self._mode = mode + self.headers = {} + self.rawHeaders = [] + self.trailers = {} + self.rawTrailers = [] + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function () { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + process.nextTick(function () { + self.emit('close') + }) + }) + + if (mode === 'fetch') { + self._fetchResponse = response + + self.url = response.url + self.statusCode = response.status + self.statusMessage = response.statusText + + response.headers.forEach(function (header, key){ + self.headers[key.toLowerCase()] = header + self.rawHeaders.push(key, header) + }) + + if (capability.writableStream) { + var writable = new WritableStream({ + write: function (chunk) { + resetTimers(false) + return new Promise(function (resolve, reject) { + if (self._destroyed) { + reject() + } else if(self.push(Buffer.from(chunk))) { + resolve() + } else { + self._resumeFetch = resolve + } + }) + }, + close: function () { + resetTimers(true) + if (!self._destroyed) + self.push(null) + }, + abort: function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + } + }) + + try { + response.body.pipeTo(writable).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + return + } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this + } + // fallback for when writableStream or pipeTo aren't available + var reader = response.body.getReader() + function read () { + reader.read().then(function (result) { + if (self._destroyed) + return + resetTimers(result.done) + if (result.done) { + self.push(null) + return + } + self.push(Buffer.from(result.value)) + read() + }).catch(function (err) { + resetTimers(true) + if (!self._destroyed) + self.emit('error', err) + }) + } + read() + } else { + self._xhr = xhr + self._pos = 0 + + self.url = xhr.responseURL + self.statusCode = xhr.status + self.statusMessage = xhr.statusText + var headers = xhr.getAllResponseHeaders().split(/\r?\n/) + headers.forEach(function (header) { + var matches = header.match(/^([^:]+):\s*(.*)/) + if (matches) { + var key = matches[1].toLowerCase() + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = [] + } + self.headers[key].push(matches[2]) + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2] + } else { + self.headers[key] = matches[2] + } + self.rawHeaders.push(matches[1], matches[2]) + } + }) + + self._charset = 'x-user-defined' + if (!capability.overrideMimeType) { + var mimeType = self.rawHeaders['mime-type'] + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/) + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase() + } + } + if (!self._charset) + self._charset = 'utf-8' // best guess + } + } +} + +inherits(IncomingMessage, stream.Readable) + +IncomingMessage.prototype._read = function () { + var self = this + + var resolve = self._resumeFetch + if (resolve) { + self._resumeFetch = null + resolve() + } +} + +IncomingMessage.prototype._onXHRProgress = function (resetTimers) { + var self = this + + var xhr = self._xhr + + var response = null + switch (self._mode) { + case 'text': + response = xhr.responseText + if (response.length > self._pos) { + var newData = response.substr(self._pos) + if (self._charset === 'x-user-defined') { + var buffer = Buffer.alloc(newData.length) + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff + + self.push(buffer) + } else { + self.push(newData, self._charset) + } + self._pos = response.length + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response + self.push(Buffer.from(new Uint8Array(response))) + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(Buffer.from(new Uint8Array(response))) + break + case 'ms-stream': + response = xhr.response + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global.MSStreamReader() + reader.onprogress = function () { + if (reader.result.byteLength > self._pos) { + self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos)))) + self._pos = reader.result.byteLength + } + } + reader.onload = function () { + resetTimers(true) + self.push(null) + } + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response) + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + resetTimers(true) + self.push(null) + } +} diff --git a/node_modules/stream-http/node_modules/readable-stream/CONTRIBUTING.md b/node_modules/stream-http/node_modules/readable-stream/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..f478d58dca85b2c396e2da8a2251be0071c4e9e0 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +## Moderation Policy + +The [Node.js Moderation Policy] applies to this WG. + +## Code of Conduct + +The [Node.js Code of Conduct][] applies to this WG. + +[Node.js Code of Conduct]: +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md +[Node.js Moderation Policy]: +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md diff --git a/node_modules/stream-http/node_modules/readable-stream/GOVERNANCE.md b/node_modules/stream-http/node_modules/readable-stream/GOVERNANCE.md new file mode 100644 index 0000000000000000000000000000000000000000..16ffb93f24bece9519cc4a220a0c1d3c91481453 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/GOVERNANCE.md @@ -0,0 +1,136 @@ +### Streams Working Group + +The Node.js Streams is jointly governed by a Working Group +(WG) +that is responsible for high-level guidance of the project. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Conduct guidelines +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project +[README.md](./README.md#current-project-team-members). + +### Collaborators + +The readable-stream GitHub repository is +maintained by the WG and additional Collaborators who are added by the +WG on an ongoing basis. + +Individuals making significant and valuable contributions are made +Collaborators and given commit-access to the project. These +individuals are identified by the WG and their addition as +Collaborators is discussed during the WG meeting. + +_Note:_ If you make a significant contribution and are not considered +for commit-access log an issue or contact a WG member directly and it +will be brought up in the next WG meeting. + +Modifications of the contents of the readable-stream repository are +made on +a collaborative basis. Anybody with a GitHub account may propose a +modification via pull request and it will be considered by the project +Collaborators. All pull requests must be reviewed and accepted by a +Collaborator with sufficient expertise who is able to take full +responsibility for the change. In the case of pull requests proposed +by an existing Collaborator, an additional Collaborator is required +for sign-off. Consensus should be sought if additional Collaborators +participate and there is disagreement around a particular +modification. See _Consensus Seeking Process_ below for further detail +on the consensus model used for governance. + +Collaborators may opt to elevate significant or controversial +modifications, or modifications that have not found consensus to the +WG for discussion by assigning the ***WG-agenda*** tag to a pull +request or issue. The WG should serve as the final arbiter where +required. + +For the current list of Collaborators, see the project +[README.md](./README.md#members). + +### WG Membership + +WG seats are not time-limited. There is no fixed size of the WG. +However, the expected target is between 6 and 12, to ensure adequate +coverage of important areas of expertise, balanced with the ability to +make decisions efficiently. + +There is no specific set of requirements or qualifications for WG +membership beyond these rules. + +The WG may add additional members to the WG by unanimous consensus. + +A WG member may be removed from the WG by voluntary resignation, or by +unanimous consensus of all other WG members. + +Changes to WG membership should be posted in the agenda, and may be +suggested as any other agenda item (see "WG Meetings" below). + +If an addition or removal is proposed during a meeting, and the full +WG is not in attendance to participate, then the addition or removal +is added to the agenda for the subsequent meeting. This is to ensure +that all members are given the opportunity to participate in all +membership decisions. If a WG member is unable to attend a meeting +where a planned membership decision is being made, then their consent +is assumed. + +No more than 1/3 of the WG members may be affiliated with the same +employer. If removal or resignation of a WG member, or a change of +employment by a WG member, creates a situation where more than 1/3 of +the WG membership shares an employer, then the situation must be +immediately remedied by the resignation or removal of one or more WG +members affiliated with the over-represented employer(s). + +### WG Meetings + +The WG meets occasionally on a Google Hangout On Air. A designated moderator +approved by the WG runs the meeting. Each meeting should be +published to YouTube. + +Items are added to the WG agenda that are considered contentious or +are modifications of governance, contribution policy, WG membership, +or release process. + +The intention of the agenda is not to approve or review all patches; +that should happen continuously on GitHub and be handled by the larger +group of Collaborators. + +Any community member or contributor can ask that something be added to +the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +WG member or the moderator can add the item to the agenda by adding +the ***WG-agenda*** tag to the issue. + +Prior to each WG meeting the moderator will share the Agenda with +members of the WG. WG members can add any items they like to the +agenda at the beginning of each meeting. The moderator and the WG +cannot veto or remove items. + +The WG may invite persons or representatives from certain projects to +participate in a non-voting capacity. + +The moderator is responsible for summarizing the discussion of each +agenda item and sends it as a pull request after the meeting. + +### Consensus Seeking Process + +The WG follows a +[Consensus +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) +decision-making model. + +When an agenda item has appeared to reach a consensus the moderator +will ask "Does anyone object?" as a final call for dissent from the +consensus. + +If an agenda item cannot reach a consensus a WG member can call for +either a closing vote or a vote to table the issue to the next +meeting. The call for a vote must be seconded by a majority of the WG +or else the discussion will continue. Simple majority wins. + +Note that changes to WG membership require a majority consensus. See +"WG Membership" above. diff --git a/node_modules/stream-http/node_modules/readable-stream/LICENSE b/node_modules/stream-http/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2873b3b2e595072e66330369d83e8af46655970c --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/LICENSE @@ -0,0 +1,47 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" diff --git a/node_modules/stream-http/node_modules/readable-stream/README.md b/node_modules/stream-http/node_modules/readable-stream/README.md new file mode 100644 index 0000000000000000000000000000000000000000..19117c1a059d1bfa7c6ff04d430bf21bb05b0621 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/README.md @@ -0,0 +1,106 @@ +# readable-stream + +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) + + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) + + +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream) + +```bash +npm install --save readable-stream +``` + +This package is a mirror of the streams implementations in Node.js. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.18.1/docs/api/stream.html). + +If you want to guarantee a stable streams base, regardless of what version of +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html). + +As of version 2.0.0 **readable-stream** uses semantic versioning. + +## Version 3.x.x + +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows: + +1. Error codes: https://github.com/nodejs/node/pull/13310, + https://github.com/nodejs/node/pull/13291, + https://github.com/nodejs/node/pull/16589, + https://github.com/nodejs/node/pull/15042, + https://github.com/nodejs/node/pull/15665, + https://github.com/nodejs/readable-stream/pull/344 +2. 'readable' have precedence over flowing + https://github.com/nodejs/node/pull/18994 +3. make virtual methods errors consistent + https://github.com/nodejs/node/pull/18813 +4. updated streams error handling + https://github.com/nodejs/node/pull/18438 +5. writable.end should return this. + https://github.com/nodejs/node/pull/18780 +6. readable continues to read when push('') + https://github.com/nodejs/node/pull/18211 +7. add custom inspect to BufferList + https://github.com/nodejs/node/pull/17907 +8. always defer 'readable' with nextTick + https://github.com/nodejs/node/pull/17979 + +## Version 2.x.x +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11. + +### Big Thanks + +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce] + +# Usage + +You can swap your `require('stream')` with `require('readable-stream')` +without any changes, if you are just using one of the main classes and +functions. + +```js +const { + Readable, + Writable, + Transform, + Duplex, + pipeline, + finished +} = require('readable-stream') +```` + +Note that `require('stream')` will return `Stream`, while +`require('readable-stream')` will return `Readable`. We discourage using +whatever is exported directly, but rather use one of the properties as +shown in the example above. + +# Streams Working Group + +`readable-stream` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + + +## Team Members + +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com> + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com> +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com> + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com> +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com> + +[sauce]: https://saucelabs.com diff --git a/node_modules/stream-http/node_modules/readable-stream/errors-browser.js b/node_modules/stream-http/node_modules/readable-stream/errors-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..fb8e73e1893b100932468397b89076261f47ae61 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/errors-browser.js @@ -0,0 +1,127 @@ +'use strict'; + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +var codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error; + } + + function getMessage(arg1, arg2, arg3) { + if (typeof message === 'string') { + return message; + } else { + return message(arg1, arg2, arg3); + } + } + + var NodeError = + /*#__PURE__*/ + function (_Base) { + _inheritsLoose(NodeError, _Base); + + function NodeError(arg1, arg2, arg3) { + return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; + } + + return NodeError; + }(Base); + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + codes[code] = NodeError; +} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js + + +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + var len = expected.length; + expected = expected.map(function (i) { + return String(i); + }); + + if (len > 2) { + return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; + } else if (len === 2) { + return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); + } else { + return "of ".concat(thing, " ").concat(expected[0]); + } + } else { + return "of ".concat(thing, " ").concat(String(expected)); + } +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith + + +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith + + +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + + return str.substring(this_len - search.length, this_len) === search; +} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes + + +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"'; +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + var determiner; + + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + var msg; + + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } else { + var type = includes(name, '.') ? 'property' : 'argument'; + msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); + } + + msg += ". Received type ".concat(typeof actual); + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented'; +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg; +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); +module.exports.codes = codes; diff --git a/node_modules/stream-http/node_modules/readable-stream/errors.js b/node_modules/stream-http/node_modules/readable-stream/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..8471526d6e7f752d581942611d749ef6355ad1f5 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/errors.js @@ -0,0 +1,116 @@ +'use strict'; + +const codes = {}; + +function createErrorType(code, message, Base) { + if (!Base) { + Base = Error + } + + function getMessage (arg1, arg2, arg3) { + if (typeof message === 'string') { + return message + } else { + return message(arg1, arg2, arg3) + } + } + + class NodeError extends Base { + constructor (arg1, arg2, arg3) { + super(getMessage(arg1, arg2, arg3)); + } + } + + NodeError.prototype.name = Base.name; + NodeError.prototype.code = code; + + codes[code] = NodeError; +} + +// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js +function oneOf(expected, thing) { + if (Array.isArray(expected)) { + const len = expected.length; + expected = expected.map((i) => String(i)); + if (len > 2) { + return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + + expected[len - 1]; + } else if (len === 2) { + return `one of ${thing} ${expected[0]} or ${expected[1]}`; + } else { + return `of ${thing} ${expected[0]}`; + } + } else { + return `of ${thing} ${String(expected)}`; + } +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith +function startsWith(str, search, pos) { + return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith +function endsWith(str, search, this_len) { + if (this_len === undefined || this_len > str.length) { + this_len = str.length; + } + return str.substring(this_len - search.length, this_len) === search; +} + +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes +function includes(str, search, start) { + if (typeof start !== 'number') { + start = 0; + } + + if (start + search.length > str.length) { + return false; + } else { + return str.indexOf(search, start) !== -1; + } +} + +createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { + return 'The value "' + value + '" is invalid for option "' + name + '"' +}, TypeError); +createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { + // determiner: 'must be' or 'must not be' + let determiner; + if (typeof expected === 'string' && startsWith(expected, 'not ')) { + determiner = 'must not be'; + expected = expected.replace(/^not /, ''); + } else { + determiner = 'must be'; + } + + let msg; + if (endsWith(name, ' argument')) { + // For cases like 'first argument' + msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; + } else { + const type = includes(name, '.') ? 'property' : 'argument'; + msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + } + + msg += `. Received type ${typeof actual}`; + return msg; +}, TypeError); +createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); +createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { + return 'The ' + name + ' method is not implemented' +}); +createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); +createErrorType('ERR_STREAM_DESTROYED', function (name) { + return 'Cannot call ' + name + ' after a stream was destroyed'; +}); +createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); +createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); +createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); +createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); +createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { + return 'Unknown encoding: ' + arg +}, TypeError); +createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + +module.exports.codes = codes; diff --git a/node_modules/stream-http/node_modules/readable-stream/experimentalWarning.js b/node_modules/stream-http/node_modules/readable-stream/experimentalWarning.js new file mode 100644 index 0000000000000000000000000000000000000000..78e841495bf24d46a2995496bdf2816935b1e66e --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/experimentalWarning.js @@ -0,0 +1,17 @@ +'use strict' + +var experimentalWarnings = new Set(); + +function emitExperimentalWarning(feature) { + if (experimentalWarnings.has(feature)) return; + var msg = feature + ' is an experimental feature. This feature could ' + + 'change at any time'; + experimentalWarnings.add(feature); + process.emitWarning(msg, 'ExperimentalWarning'); +} + +function noop() {} + +module.exports.emitExperimentalWarning = process.emitWarning + ? emitExperimentalWarning + : noop; diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000000000000000000000000000000000000..19abfa604d5ef7bf3646c1a70a848c3f0df8105a --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,126 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +}; +/**/ + +module.exports = Duplex; +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); +require('inherits')(Duplex, Readable); +{ + // Allow the keys array to be GC'ed. + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + Readable.call(this, options); + Writable.call(this, options); + this.allowHalfOpen = true; + if (options) { + if (options.readable === false) this.readable = false; + if (options.writable === false) this.writable = false; + if (options.allowHalfOpen === false) { + this.allowHalfOpen = false; + this.once('end', onend); + } + } +} +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); +Object.defineProperty(Duplex.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +Object.defineProperty(Duplex.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); + +// the no-half-open enforcer +function onend() { + // If the writable side ended, then we're ok. + if (this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(onEndNT, this); +} +function onEndNT(self) { + self.end(); +} +Object.defineProperty(Duplex.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000000000000000000000000000000000000..24a6bdde2903fac66f638e578b831a7600761207 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,37 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; +var Transform = require('./_stream_transform'); +require('inherits')(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + Transform.call(this, options); +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000000000000000000000000000000000000..df1f608d532606ba1df4eeaf3b6f577791dcd9ad --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,1027 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +module.exports = Readable; + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; +var EElistenerCount = function EElistenerCount(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} + +/**/ +var debugUtil = require('util'); +var debug; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function debug() {}; +} +/**/ + +var BufferList = require('./internal/streams/buffer_list'); +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; + +// Lazy loaded to improve the startup performance. +var StringDecoder; +var createReadableStreamAsyncIterator; +var from; +require('inherits')(Readable, Stream); +var errorOrDestroy = destroyImpl.errorOrDestroy; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} +function ReadableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + this.paused = true; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'end' (and potentially 'finish') + this.autoDestroy = !!options.autoDestroy; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + if (!(this instanceof Readable)) return new Readable(options); + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + this._readableState = new ReadableState(options, this, isDuplex); + + // legacy + this.readable = true; + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + Stream.call(this); +} +Object.defineProperty(Readable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + debug('readableAddChunk', chunk); + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + errorOrDestroy(stream, er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (addToFront) { + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed) { + return false; + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + maybeReadMore(stream, state); + } + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0); +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + state.awaitDrain = 0; + stream.emit('data', chunk); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + return er; +} +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + var decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8 + this._readableState.encoding = this._readableState.decoder.encoding; + + // Iterate over current buffer to convert already stored Buffers: + var p = this._readableState.buffer.head; + var content = ''; + while (p !== null) { + content += decoder.write(p.data); + p = p.next; + } + this._readableState.buffer.clear(); + if (content !== '') this._readableState.buffer.push(content); + this._readableState.length = content.length; + return this; +}; + +// Don't raise the hwm > 1GB +var MAX_HWM = 0x40000000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + state.awaitDrain = 0; + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null) this.emit('data', ret); + return ret; +}; +function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // if we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call + emitReadable(stream); + } else { + // emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + if (!state.emittedReadable) { + state.emittedReadable = true; + emitReadable_(stream); + } + } +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } +} +function emitReadable_(stream) { + var state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { + var len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); +}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest; +}; +function pipeOnDrain(src) { + return function pipeOnDrainFunctionResult() { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { + hasUnpiped: false + }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + for (var i = 0; i < len; i++) dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + dest.emit('unpipe', this, unpipeInfo); + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + var state = this._readableState; + if (ev === 'data') { + // update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; +Readable.prototype.removeListener = function (ev, fn) { + var res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +Readable.prototype.removeAllListeners = function (ev) { + var res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res; +}; +function updateReadableListening(self) { + var state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && !state.paused) { + // flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // crude way to check if we should resume + } else if (self.listenerCount('data') > 0) { + self.resume(); + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + // we flow only if there is no one listening + // for readable, but we still have to call + // resume() + state.flowing = !state.readableListening; + resume(this, state); + } + state.paused = false; + return this; +}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState.paused = true; + return this; +}; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; + var state = this._readableState; + var paused = false; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } + _this.push(null); + }); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function methodWrap(method) { + return function methodWrapReturnFunction() { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + return this; +}; +if (typeof Symbol === 'function') { + Readable.prototype[Symbol.asyncIterator] = function () { + if (createReadableStreamAsyncIterator === undefined) { + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); + } + return createReadableStreamAsyncIterator(this); + }; +} +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.highWaterMark; + } +}); +Object.defineProperty(Readable.prototype, 'readableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState && this._readableState.buffer; + } +}); +Object.defineProperty(Readable.prototype, 'readableFlowing', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.flowing; + }, + set: function set(state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } +}); + +// exposed for testing purposes only. +Readable._fromList = fromList; +Object.defineProperty(Readable.prototype, 'readableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._readableState.length; + } +}); + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = state.buffer.consume(n, state.decoder); + } + return ret; +} +function endReadable(stream) { + var state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well + var wState = stream._writableState; + if (!wState || wState.autoDestroy && wState.finished) { + stream.destroy(); + } + } + } +} +if (typeof Symbol === 'function') { + Readable.from = function (iterable, opts) { + if (from === undefined) { + from = require('./internal/streams/from'); + } + return from(Readable, iterable, opts); + }; +} +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000000000000000000000000000000000000..1ccb7157be8b8c35df891c2c0905685a144a2e9a --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,190 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; +var _require$codes = require('../errors').codes, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; +var Duplex = require('./_stream_duplex'); +require('inherits')(Transform, Duplex); +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; + var cb = ts.writecb; + if (cb === null) { + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); + } + ts.writechunk = null; + ts.writecb = null; + if (data != null) + // single equals check for both `null` and `undefined` + this.push(data); + cb(er); + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + Duplex.call(this, options); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} +function prefinish() { + var _this = this; + if (typeof this._flush === 'function' && !this._readableState.destroyed) { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); +}; +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + if (ts.writechunk !== null && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; +Transform.prototype._destroy = function (err, cb) { + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + }); +}; +function done(stream, er, data) { + if (er) return stream.emit('error', er); + if (data != null) + // single equals check for both `null` and `undefined` + stream.push(data); + + // TODO(BridgeAR): Write a test for these two error cases + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); + return stream.push(null); +} \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000000000000000000000000000000000000..292415e23a192be6b7a7f35db37befa489117552 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,641 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +var Buffer = require('buffer').Buffer; +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +var destroyImpl = require('./internal/streams/destroy'); +var _require = require('./internal/streams/state'), + getHighWaterMark = _require.getHighWaterMark; +var _require$codes = require('../errors').codes, + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; +var errorOrDestroy = destroyImpl.errorOrDestroy; +require('inherits')(Writable, Stream); +function nop() {} +function WritableState(options, stream, isDuplex) { + Duplex = Duplex || require('./_stream_duplex'); + options = options || {}; + + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end') + this.autoDestroy = !!options.autoDestroy; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function writableStateBufferGetter() { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function value(object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function realHasInstance(object) { + return object instanceof this; + }; +} +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5 + var isDuplex = this instanceof Duplex; + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); + this._writableState = new WritableState(options, this, isDuplex); + + // legacy. + this.writable = true; + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + } + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); +}; +function writeAfterEnd(stream, cb) { + var er = new ERR_STREAM_WRITE_AFTER_END(); + // TODO: defer error events consistently everywhere, not just the cb + errorOrDestroy(stream, er); + process.nextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var er; + if (chunk === null) { + er = new ERR_STREAM_NULL_VALUES(); + } else if (typeof chunk !== 'string' && !state.objectMode) { + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); + } + if (er) { + errorOrDestroy(stream, er); + process.nextTick(cb, er); + return false; + } + return true; +} +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb !== 'function') cb = nop; + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + return ret; +}; +Writable.prototype.cork = function () { + this._writableState.corked++; +}; +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; +Object.defineProperty(Writable.prototype, 'writableBuffer', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState && this._writableState.getBuffer(); + } +}); +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.highWaterMark; + } +}); + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + state.length += len; + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + return ret; +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + process.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + process.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + errorOrDestroy(stream, er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); + onwriteStateUpdate(state); + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state) || stream.destroyed; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + if (sync) { + process.nextTick(afterWrite, stream, state, finished, cb); + } else { + afterWrite(stream, state, finished, cb); + } + } +} +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); +}; +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); + return this; +}; +Object.defineProperty(Writable.prototype, 'writableLength', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + return this._writableState.length; + } +}); +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + errorOrDestroy(stream, err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.pendingcb++; + state.finalCalled = true; + process.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well + var rState = stream._readableState; + if (!rState || rState.autoDestroy && rState.endEmitted) { + stream.destroy(); + } + } + } + } + return need; +} +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) process.nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; +} +Object.defineProperty(Writable.prototype, 'destroyed', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function get() { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function set(value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + cb(err); +}; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/async_iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..742c5a4674794d9e7667c02dcbeb44bf8001b4d6 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/async_iterator.js @@ -0,0 +1,180 @@ +'use strict'; + +var _Object$setPrototypeO; +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var finished = require('./end-of-stream'); +var kLastResolve = Symbol('lastResolve'); +var kLastReject = Symbol('lastReject'); +var kError = Symbol('error'); +var kEnded = Symbol('ended'); +var kLastPromise = Symbol('lastPromise'); +var kHandlePromise = Symbol('handlePromise'); +var kStream = Symbol('stream'); +function createIterResult(value, done) { + return { + value: value, + done: done + }; +} +function readAndResolve(iter) { + var resolve = iter[kLastResolve]; + if (resolve !== null) { + var data = iter[kStream].read(); + // we defer if data is null + // we can be expecting either 'end' or + // 'error' + if (data !== null) { + iter[kLastPromise] = null; + iter[kLastResolve] = null; + iter[kLastReject] = null; + resolve(createIterResult(data, false)); + } + } +} +function onReadable(iter) { + // we wait for the next tick, because it might + // emit an error with process.nextTick + process.nextTick(readAndResolve, iter); +} +function wrapForNext(lastPromise, iter) { + return function (resolve, reject) { + lastPromise.then(function () { + if (iter[kEnded]) { + resolve(createIterResult(undefined, true)); + return; + } + iter[kHandlePromise](resolve, reject); + }, reject); + }; +} +var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); +var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { + get stream() { + return this[kStream]; + }, + next: function next() { + var _this = this; + // if we have detected an error in the meanwhile + // reject straight away + var error = this[kError]; + if (error !== null) { + return Promise.reject(error); + } + if (this[kEnded]) { + return Promise.resolve(createIterResult(undefined, true)); + } + if (this[kStream].destroyed) { + // We need to defer via nextTick because if .destroy(err) is + // called, the error will be emitted via nextTick, and + // we cannot guarantee that there is no error lingering around + // waiting to be emitted. + return new Promise(function (resolve, reject) { + process.nextTick(function () { + if (_this[kError]) { + reject(_this[kError]); + } else { + resolve(createIterResult(undefined, true)); + } + }); + }); + } + + // if we have multiple next() calls + // we will wait for the previous Promise to finish + // this logic is optimized to support for await loops, + // where next() is only called once at a time + var lastPromise = this[kLastPromise]; + var promise; + if (lastPromise) { + promise = new Promise(wrapForNext(lastPromise, this)); + } else { + // fast path needed to support multiple this.push() + // without triggering the next() queue + var data = this[kStream].read(); + if (data !== null) { + return Promise.resolve(createIterResult(data, false)); + } + promise = new Promise(this[kHandlePromise]); + } + this[kLastPromise] = promise; + return promise; + } +}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { + return this; +}), _defineProperty(_Object$setPrototypeO, "return", function _return() { + var _this2 = this; + // destroy(err, cb) is a private API + // we can guarantee we have that here, because we control the + // Readable class this is attached to + return new Promise(function (resolve, reject) { + _this2[kStream].destroy(null, function (err) { + if (err) { + reject(err); + return; + } + resolve(createIterResult(undefined, true)); + }); + }); +}), _Object$setPrototypeO), AsyncIteratorPrototype); +var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { + var _Object$create; + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { + value: stream, + writable: true + }), _defineProperty(_Object$create, kLastResolve, { + value: null, + writable: true + }), _defineProperty(_Object$create, kLastReject, { + value: null, + writable: true + }), _defineProperty(_Object$create, kError, { + value: null, + writable: true + }), _defineProperty(_Object$create, kEnded, { + value: stream._readableState.endEmitted, + writable: true + }), _defineProperty(_Object$create, kHandlePromise, { + value: function value(resolve, reject) { + var data = iterator[kStream].read(); + if (data) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(data, false)); + } else { + iterator[kLastResolve] = resolve; + iterator[kLastReject] = reject; + } + }, + writable: true + }), _Object$create)); + iterator[kLastPromise] = null; + finished(stream, function (err) { + if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + var reject = iterator[kLastReject]; + // reject if we are waiting for data in the Promise + // returned by next() and store the error + if (reject !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + reject(err); + } + iterator[kError] = err; + return; + } + var resolve = iterator[kLastResolve]; + if (resolve !== null) { + iterator[kLastPromise] = null; + iterator[kLastResolve] = null; + iterator[kLastReject] = null; + resolve(createIterResult(undefined, true)); + } + iterator[kEnded] = true; + }); + stream.on('readable', onReadable.bind(null, iterator)); + return iterator; +}; +module.exports = createReadableStreamAsyncIterator; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/buffer_list.js new file mode 100644 index 0000000000000000000000000000000000000000..69bda497d35f347f1a510eef0fe2408e8d31923c --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/buffer_list.js @@ -0,0 +1,183 @@ +'use strict'; + +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } +function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } +function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var _require = require('buffer'), + Buffer = _require.Buffer; +var _require2 = require('util'), + inspect = _require2.inspect; +var custom = inspect && inspect.custom || 'inspect'; +function copyBuffer(src, target, offset) { + Buffer.prototype.copy.call(src, target, offset); +} +module.exports = /*#__PURE__*/function () { + function BufferList() { + _classCallCheck(this, BufferList); + this.head = null; + this.tail = null; + this.length = 0; + } + _createClass(BufferList, [{ + key: "push", + value: function push(v) { + var entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + } + }, { + key: "unshift", + value: function unshift(v) { + var entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + }, { + key: "shift", + value: function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + } + }, { + key: "clear", + value: function clear() { + this.head = this.tail = null; + this.length = 0; + } + }, { + key: "join", + value: function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) ret += s + p.data; + return ret; + } + }, { + key: "concat", + value: function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + } + + // Consumes a specified amount of bytes or characters from the buffered data. + }, { + key: "consume", + value: function consume(n, hasStrings) { + var ret; + if (n < this.head.data.length) { + // `slice` is the same for buffers and strings. + ret = this.head.data.slice(0, n); + this.head.data = this.head.data.slice(n); + } else if (n === this.head.data.length) { + // First chunk is a perfect match. + ret = this.shift(); + } else { + // Result spans more than one buffer. + ret = hasStrings ? this._getString(n) : this._getBuffer(n); + } + return ret; + } + }, { + key: "first", + value: function first() { + return this.head.data; + } + + // Consumes a specified amount of characters from the buffered data. + }, { + key: "_getString", + value: function _getString(n) { + var p = this.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Consumes a specified amount of bytes from the buffered data. + }, { + key: "_getBuffer", + value: function _getBuffer(n) { + var ret = Buffer.allocUnsafe(n); + var p = this.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) this.head = p.next;else this.head = this.tail = null; + } else { + this.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + this.length -= c; + return ret; + } + + // Make sure the linked list only shows the minimal necessary information. + }, { + key: custom, + value: function value(_, options) { + return inspect(this, _objectSpread(_objectSpread({}, options), {}, { + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + })); + } + }]); + return BufferList; +}(); \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/destroy.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/destroy.js new file mode 100644 index 0000000000000000000000000000000000000000..31a17c4dc463880722098b62598fe21bc9672132 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/destroy.js @@ -0,0 +1,96 @@ +'use strict'; + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + process.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + process.nextTick(emitErrorNT, this, err); + } + } + return this; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + process.nextTick(emitErrorAndCloseNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + process.nextTick(emitErrorAndCloseNT, _this, err); + } else { + process.nextTick(emitCloseNT, _this); + } + } else if (cb) { + process.nextTick(emitCloseNT, _this); + cb(err); + } else { + process.nextTick(emitCloseNT, _this); + } + }); + return this; +} +function emitErrorAndCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); +} +function emitCloseNT(self) { + if (self._writableState && !self._writableState.emitClose) return; + if (self._readableState && !self._readableState.emitClose) return; + self.emit('close'); +} +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} +function emitErrorNT(self, err) { + self.emit('error', err); +} +function errorOrDestroy(stream, err) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + var rState = stream._readableState; + var wState = stream._writableState; + if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy, + errorOrDestroy: errorOrDestroy +}; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/end-of-stream.js new file mode 100644 index 0000000000000000000000000000000000000000..59c671b5af769bc5797843837056ae419ab22e80 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/end-of-stream.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + callback.apply(this, args); + }; +} +function noop() {} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function eos(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; + callback = once(callback || noop); + var readable = opts.readable || opts.readable !== false && stream.readable; + var writable = opts.writable || opts.writable !== false && stream.writable; + var onlegacyfinish = function onlegacyfinish() { + if (!stream.writable) onfinish(); + }; + var writableEnded = stream._writableState && stream._writableState.finished; + var onfinish = function onfinish() { + writable = false; + writableEnded = true; + if (!readable) callback.call(stream); + }; + var readableEnded = stream._readableState && stream._readableState.endEmitted; + var onend = function onend() { + readable = false; + readableEnded = true; + if (!writable) callback.call(stream); + }; + var onerror = function onerror(err) { + callback.call(stream, err); + }; + var onclose = function onclose() { + var err; + if (readable && !readableEnded) { + if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + if (writable && !writableEnded) { + if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); + return callback.call(stream, err); + } + }; + var onrequest = function onrequest() { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest();else stream.on('request', onrequest); + } else if (writable && !stream._writableState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', onerror); + stream.on('close', onclose); + return function () { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; +} +module.exports = eos; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from-browser.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..a4ce56f3c90f60d3416e8e0328375c4b20213872 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from-browser.js @@ -0,0 +1,3 @@ +module.exports = function () { + throw new Error('Readable.from is not available in the browser') +}; diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from.js new file mode 100644 index 0000000000000000000000000000000000000000..0a34ee92e3df85fd31734c3d95a43697df8fbbb9 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/from.js @@ -0,0 +1,52 @@ +'use strict'; + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } +function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } +function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } +function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } +var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; +function from(Readable, iterable, opts) { + var iterator; + if (iterable && typeof iterable.next === 'function') { + iterator = iterable; + } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); + var readable = new Readable(_objectSpread({ + objectMode: true + }, opts)); + // Reading boolean to protect against _read + // being called before last iteration completion. + var reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + function next() { + return _next2.apply(this, arguments); + } + function _next2() { + _next2 = _asyncToGenerator(function* () { + try { + var _yield$iterator$next = yield iterator.next(), + value = _yield$iterator$next.value, + done = _yield$iterator$next.done; + if (done) { + readable.push(null); + } else if (readable.push(yield value)) { + next(); + } else { + reading = false; + } + } catch (err) { + readable.destroy(err); + } + }); + return _next2.apply(this, arguments); + } + return readable; +} +module.exports = from; diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/pipeline.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/pipeline.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f39241f98dd890dda9d4dbea076540ed43cabc --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/pipeline.js @@ -0,0 +1,86 @@ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). + +'use strict'; + +var eos; +function once(callback) { + var called = false; + return function () { + if (called) return; + called = true; + callback.apply(void 0, arguments); + }; +} +var _require$codes = require('../../../errors').codes, + ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; +function noop(err) { + // Rethrow the error if it exists to avoid swallowing it + if (err) throw err; +} +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +} +function destroyer(stream, reading, writing, callback) { + callback = once(callback); + var closed = false; + stream.on('close', function () { + closed = true; + }); + if (eos === undefined) eos = require('./end-of-stream'); + eos(stream, { + readable: reading, + writable: writing + }, function (err) { + if (err) return callback(err); + closed = true; + callback(); + }); + var destroyed = false; + return function (err) { + if (closed) return; + if (destroyed) return; + destroyed = true; + + // request.destroy just do .end - .abort is what we want + if (isRequest(stream)) return stream.abort(); + if (typeof stream.destroy === 'function') return stream.destroy(); + callback(err || new ERR_STREAM_DESTROYED('pipe')); + }; +} +function call(fn) { + fn(); +} +function pipe(from, to) { + return from.pipe(to); +} +function popCallback(streams) { + if (!streams.length) return noop; + if (typeof streams[streams.length - 1] !== 'function') return noop; + return streams.pop(); +} +function pipeline() { + for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { + streams[_key] = arguments[_key]; + } + var callback = popCallback(streams); + if (Array.isArray(streams[0])) streams = streams[0]; + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams'); + } + var error; + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1; + var writing = i > 0; + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err; + if (err) destroys.forEach(call); + if (reading) return; + destroys.forEach(call); + callback(error); + }); + }); + return streams.reduce(pipe); +} +module.exports = pipeline; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/state.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/state.js new file mode 100644 index 0000000000000000000000000000000000000000..3fbf8927e00179deca5a8855b4b4c17da9450676 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/state.js @@ -0,0 +1,22 @@ +'use strict'; + +var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { + var name = isDuplex ? duplexKey : 'highWaterMark'; + throw new ERR_INVALID_OPT_VALUE(name, hwm); + } + return Math.floor(hwm); + } + + // Default value + return state.objectMode ? 16 : 16 * 1024; +} +module.exports = { + getHighWaterMark: getHighWaterMark +}; \ No newline at end of file diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..9332a3fdae7060505c0a081614e697fa6cb56dc0 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream-browser.js @@ -0,0 +1 @@ +module.exports = require('events').EventEmitter; diff --git a/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream.js b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream.js new file mode 100644 index 0000000000000000000000000000000000000000..ce2ad5b6ee57f4778a1f4838f7970093c7941c1c --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/lib/internal/streams/stream.js @@ -0,0 +1 @@ +module.exports = require('stream'); diff --git a/node_modules/stream-http/node_modules/readable-stream/package.json b/node_modules/stream-http/node_modules/readable-stream/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ade59e71aa0f170b4ec49a32cf0d04ab5f73ad86 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/package.json @@ -0,0 +1,68 @@ +{ + "name": "readable-stream", + "version": "3.6.2", + "description": "Streams3, a user-land copy of the stream library from Node.js", + "main": "readable.js", + "engines": { + "node": ">= 6" + }, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "devDependencies": { + "@babel/cli": "^7.2.0", + "@babel/core": "^7.2.0", + "@babel/polyfill": "^7.0.0", + "@babel/preset-env": "^7.2.0", + "airtap": "0.0.9", + "assert": "^1.4.0", + "bl": "^2.0.0", + "deep-strict-equal": "^0.2.0", + "events.once": "^2.0.2", + "glob": "^7.1.2", + "gunzip-maybe": "^1.4.1", + "hyperquest": "^2.1.3", + "lolex": "^2.6.0", + "nyc": "^11.0.0", + "pump": "^3.0.0", + "rimraf": "^2.6.2", + "tap": "^12.0.0", + "tape": "^4.9.0", + "tar-fs": "^1.16.2", + "util-promisify": "^2.1.0" + }, + "scripts": { + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js", + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js", + "test-browser-local": "airtap --open --local -- test/browser.js", + "cover": "nyc npm test", + "report": "nyc report --reporter=lcov", + "update-browser-errors": "babel -o errors-browser.js errors.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/readable-stream" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false, + "worker_threads": false, + "./errors": "./errors-browser.js", + "./readable.js": "./readable-browser.js", + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js", + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js" + }, + "nyc": { + "include": [ + "lib/**.js" + ] + }, + "license": "MIT" +} diff --git a/node_modules/stream-http/node_modules/readable-stream/readable-browser.js b/node_modules/stream-http/node_modules/readable-stream/readable-browser.js new file mode 100644 index 0000000000000000000000000000000000000000..adbf60de832f9d6e066625f09d708670291e1bfd --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/readable-browser.js @@ -0,0 +1,9 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); +exports.finished = require('./lib/internal/streams/end-of-stream.js'); +exports.pipeline = require('./lib/internal/streams/pipeline.js'); diff --git a/node_modules/stream-http/node_modules/readable-stream/readable.js b/node_modules/stream-http/node_modules/readable-stream/readable.js new file mode 100644 index 0000000000000000000000000000000000000000..9e0ca120ded827e5ba3343f826fa7462a841e092 --- /dev/null +++ b/node_modules/stream-http/node_modules/readable-stream/readable.js @@ -0,0 +1,16 @@ +var Stream = require('stream'); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream.Readable; + Object.assign(module.exports, Stream); + module.exports.Stream = Stream; +} else { + exports = module.exports = require('./lib/_stream_readable.js'); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = require('./lib/_stream_writable.js'); + exports.Duplex = require('./lib/_stream_duplex.js'); + exports.Transform = require('./lib/_stream_transform.js'); + exports.PassThrough = require('./lib/_stream_passthrough.js'); + exports.finished = require('./lib/internal/streams/end-of-stream.js'); + exports.pipeline = require('./lib/internal/streams/pipeline.js'); +} diff --git a/node_modules/stream-http/package.json b/node_modules/stream-http/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5097bb62a722a841b0b95e4e594b4f108ff3eec8 --- /dev/null +++ b/node_modules/stream-http/package.json @@ -0,0 +1,47 @@ +{ + "name": "stream-http", + "version": "3.2.0", + "description": "Streaming http in the browser", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/jhiesey/stream-http.git" + }, + "scripts": { + "test": "npm run test-node && ([ -n \"${TRAVIS_PULL_REQUEST}\" -a \"${TRAVIS_PULL_REQUEST}\" != 'false' ] || npm run test-browser)", + "test-node": "tape test/node/*.js", + "test-browser": "airtap --concurrency 1 -- test/browser/*.js", + "test-browser-local": "airtap --preset local -- test/browser/*.js" + }, + "author": "John Hiesey", + "license": "MIT", + "bugs": { + "url": "https://github.com/jhiesey/stream-http/issues" + }, + "homepage": "https://github.com/jhiesey/stream-http#readme", + "keywords": [ + "http", + "stream", + "streaming", + "xhr", + "http-browserify" + ], + "dependencies": { + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.4", + "readable-stream": "^3.6.0", + "xtend": "^4.0.2" + }, + "devDependencies": { + "airtap": "^4.0.3", + "airtap-manual": "^1.0.0", + "airtap-sauce": "^1.1.0", + "basic-auth": "^2.0.1", + "brfs": "^2.0.2", + "cookie-parser": "^1.4.5", + "express": "^4.17.1", + "tape": "^5.2.2", + "ua-parser-js": "^0.7.28", + "webworkify": "^1.5.0" + } +} diff --git a/node_modules/stream-parser/.npmignore b/node_modules/stream-parser/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..b4357974bd0b18e2fdfbb063cc8ebd1b21d6ec32 --- /dev/null +++ b/node_modules/stream-parser/.npmignore @@ -0,0 +1,2 @@ +/node_modules +?.js diff --git a/node_modules/stream-parser/.travis.yml b/node_modules/stream-parser/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..99cdc7439aacd1f32b4fd50f6f8a383984e133b2 --- /dev/null +++ b/node_modules/stream-parser/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.11" diff --git a/node_modules/stream-parser/History.md b/node_modules/stream-parser/History.md new file mode 100644 index 0000000000000000000000000000000000000000..75d954e92f1f74e1a4489d25de1efb88b1854c61 --- /dev/null +++ b/node_modules/stream-parser/History.md @@ -0,0 +1,67 @@ + +0.3.1 / 2015-06-04 +================== + + * package: allow any "debug" v2 + +0.3.0 / 2014-06-22 +================== + + * add a `_skipBytes()` function + * History: fix changelog output + +0.2.0 / 2014-06-21 +================== + + * index: emit an "error" event when data is written with no parsing function is in place + * package: fix "main" field + * rename "lib/parser.js" to "index.js" + * README: use svg for Travis badge + +0.1.2 / 2014-06-16 +================== + + * parser: use %o debug v1 formatting + +0.1.1 / 2014-06-16 +================== + + * package: pin "readable-stream" to v1.0 + * package: update "debug" to v1.0.0 + * travis: test node v0.11 + * travis: don't test node v0.9 + +0.1.0 / 2013-06-04 +================== + + * travis: test node v0.10 + * test: add test case from #3 + * parser: add jsdocs for the `process()` function + * parser: use a thunk-based "trampoline" technique to prevent stack overflows on synchronous parsers (fixes #3) + +0.0.5 / 2013-03-06 +================== + + * Update for node v0.9.12 streams2 API Writable/Transform API changes + +0.0.4 / 2013-02-23 +================== + + * Don't allow `_bytes(0)` + * Fix tests on node v0.8.x + +0.0.3 / 2013-02-10 +================== + + * Allow `_passthrough(Infinity)` + * Add MIT license file + +0.0.2 / 2013-02-08 +================== + + * Add support for asynchronous callback functions + +0.0.1 / 2013-02-05 +================== + + * Initial release diff --git a/node_modules/stream-parser/LICENSE b/node_modules/stream-parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2a54ccd2ebe03d96b1e1e40129130abdd9d0c199 --- /dev/null +++ b/node_modules/stream-parser/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/stream-parser/README.md b/node_modules/stream-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2975cc74afb6a7bea73b4ce3493819c7526bf68b --- /dev/null +++ b/node_modules/stream-parser/README.md @@ -0,0 +1,137 @@ +node-stream-parser +================== +### Generic interruptible "parser" mixin for Transform & Writable streams +[![Build Status](https://secure.travis-ci.org/TooTallNate/node-stream-parser.svg)](http://travis-ci.org/TooTallNate/node-stream-parser) + +This module offers the `stream-parser` mixin, which provides an easy-to-use API +for parsing bytes from `Writable` and/or `Transform` stream instances. This module +is great for implementing streaming parsers for standardized file formats. + +For `Writable` streams, the parser takes control over the `_write` callback +function. For `Transform` streams, the parser controls the `_transform` callback +function. + +Installation +------------ + +``` bash +$ npm install stream-parser +``` + + +Example +------- + +Let's create a quick `Transform` stream subclass that utilizes the parser's +`_bytes()` and `_passthrough()` functions to parse a theoretical file format that +has an 8-byte header we want to parse, and then pass through the rest of the data. + +``` javascript +var Parser = require('stream-parser'); +var inherits = require('util').inherits; +var Transform = require('stream').Transform; + +// create a Transform stream subclass +function MyParser () { + Transform.call(this); + + // buffer the first 8 bytes written + this._bytes(8, this.onheader); +} +inherits(MyParser, Transform); + +// mixin stream-parser into MyParser's `prototype` +Parser(MyParser.prototype); + +// invoked when the first 8 bytes have been received +MyParser.prototype.onheader = function (buffer, output) { + // parse the "buffer" into a useful "header" object + var header = {}; + header.type = buffer.readUInt32LE(0); + header.name = buffer.toString('utf8', 4); + this.emit('header', header); + + // it's usually a good idea to queue the next "piece" within the callback + this._passthrough(Infinity); +}; + + +// now we can *use* it! +var parser = new MyParser(); +parser.on('header', function (header) { + console.error('got "header"', header); +}); +process.stdin.pipe(parser).pipe(process.stdout); +``` + +Here's an example of manually creating a `Transform` stream and turning it into a +"pass through" stream equivalent to the one built into node core: + +``` javascript +var Parser = require('stream-parser'); +var Transform = require('stream').Transform; + +// create a Transform instance and extend it with "stream-parser" +var p = new Transform(); +Parser(p); + +// pass through `Infinity` bytes... forever... +p._passthrough(Infinity); + +// now `p` is equivalent to a stream.PassThrough instance +process.stdin.pipe(p).pipe(process.stdout); +``` + +See the `test` directory for some more example code in the test cases. + +A list of known concrete implementations is here (send pull requests for more!): + + * [node-icecast][] + * [node-throttle][] + * [node-flv][] + * [node-wav][] + +API +--- + + - [Parser()](#parser) + - [._bytes(n, cb)](#_bytesn-cb) + - [._skipBytes(n, cb)](#_skipbytesn-cb) + - [._passthrough(n, cb)](#_passthroughn-cb) + +## Parser() + + The `Parser` stream mixin works with either `Writable` or `Transform` stream + instances/subclasses. Provides a convenient generic "parsing" API: + +```js +_bytes(n, cb) - buffers "n" bytes and then calls "cb" with the "chunk" +_skipBytes(n, cb) - skips "n" bytes and then calls "cb" when done +``` + + If you extend a `Transform` stream, then the `_passthrough()` function is also + added: + +```js +_passthrough(n, cb) - passes through "n" bytes untouched and then calls "cb" +``` + +### ._bytes(n, cb) + + Buffers `n` bytes and then invokes `cb` once that amount has been collected. + +### ._skipBytes(n, cb) + + Skips over the next `n` bytes and then invokes `cb` once that amount has been + discarded. + +### ._passthrough(n, cb) + + Passes through `n` bytes to the readable side of this stream untouched, + then invokes `cb` once that amount has been passed through. This function is only defined + when stream-parser is extending a `Transform` stream. + +[node-icecast]: https://github.com/TooTallNate/node-icecast +[node-throttle]: https://github.com/TooTallNate/node-throttle +[node-flv]: https://github.com/TooTallNate/node-flv +[node-wav]: https://github.com/TooTallNate/node-wav diff --git a/node_modules/stream-parser/index.js b/node_modules/stream-parser/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9e4b7e61764afb0780d0a912e4fd5d2706cd9453 --- /dev/null +++ b/node_modules/stream-parser/index.js @@ -0,0 +1,299 @@ + +/** + * Module dependencies. + */ + +var assert = require('assert'); +var debug = require('debug')('stream-parser'); + +/** + * Module exports. + */ + +module.exports = Parser; + +/** + * Parser states. + */ + +var INIT = -1; +var BUFFERING = 0; +var SKIPPING = 1; +var PASSTHROUGH = 2; + +/** + * The `Parser` stream mixin works with either `Writable` or `Transform` stream + * instances/subclasses. Provides a convenient generic "parsing" API: + * + * _bytes(n, cb) - buffers "n" bytes and then calls "cb" with the "chunk" + * _skipBytes(n, cb) - skips "n" bytes and then calls "cb" when done + * + * If you extend a `Transform` stream, then the `_passthrough()` function is also + * added: + * + * _passthrough(n, cb) - passes through "n" bytes untouched and then calls "cb" + * + * @param {Stream} stream Transform or Writable stream instance to extend + * @api public + */ + +function Parser (stream) { + var isTransform = stream && 'function' == typeof stream._transform; + var isWritable = stream && 'function' == typeof stream._write; + + if (!isTransform && !isWritable) throw new Error('must pass a Writable or Transform stream in'); + debug('extending Parser into stream'); + + // Transform streams and Writable streams get `_bytes()` and `_skipBytes()` + stream._bytes = _bytes; + stream._skipBytes = _skipBytes; + + // only Transform streams get the `_passthrough()` function + if (isTransform) stream._passthrough = _passthrough; + + // take control of the streams2 callback functions for this stream + if (isTransform) { + stream._transform = transform; + } else { + stream._write = write; + } +} + +function init (stream) { + debug('initializing parser stream'); + + // number of bytes left to parser for the next "chunk" + stream._parserBytesLeft = 0; + + // array of Buffer instances that make up the next "chunk" + stream._parserBuffers = []; + + // number of bytes parsed so far for the next "chunk" + stream._parserBuffered = 0; + + // flag that keeps track of if what the parser should do with bytes received + stream._parserState = INIT; + + // the callback for the next "chunk" + stream._parserCallback = null; + + // XXX: backwards compat with the old Transform API... remove at some point.. + if ('function' == typeof stream.push) { + stream._parserOutput = stream.push.bind(stream); + } + + stream._parserInit = true; +} + +/** + * Buffers `n` bytes and then invokes `fn` once that amount has been collected. + * + * @param {Number} n the number of bytes to buffer + * @param {Function} fn callback function to invoke when `n` bytes are buffered + * @api public + */ + +function _bytes (n, fn) { + assert(!this._parserCallback, 'there is already a "callback" set!'); + assert(isFinite(n) && n > 0, 'can only buffer a finite number of bytes > 0, got "' + n + '"'); + if (!this._parserInit) init(this); + debug('buffering %o bytes', n); + this._parserBytesLeft = n; + this._parserCallback = fn; + this._parserState = BUFFERING; +} + +/** + * Skips over the next `n` bytes, then invokes `fn` once that amount has + * been discarded. + * + * @param {Number} n the number of bytes to discard + * @param {Function} fn callback function to invoke when `n` bytes have been skipped + * @api public + */ + +function _skipBytes (n, fn) { + assert(!this._parserCallback, 'there is already a "callback" set!'); + assert(n > 0, 'can only skip > 0 bytes, got "' + n + '"'); + if (!this._parserInit) init(this); + debug('skipping %o bytes', n); + this._parserBytesLeft = n; + this._parserCallback = fn; + this._parserState = SKIPPING; +} + +/** + * Passes through `n` bytes to the readable side of this stream untouched, + * then invokes `fn` once that amount has been passed through. + * + * @param {Number} n the number of bytes to pass through + * @param {Function} fn callback function to invoke when `n` bytes have passed through + * @api public + */ + +function _passthrough (n, fn) { + assert(!this._parserCallback, 'There is already a "callback" set!'); + assert(n > 0, 'can only pass through > 0 bytes, got "' + n + '"'); + if (!this._parserInit) init(this); + debug('passing through %o bytes', n); + this._parserBytesLeft = n; + this._parserCallback = fn; + this._parserState = PASSTHROUGH; +} + +/** + * The `_write()` callback function implementation. + * + * @api private + */ + +function write (chunk, encoding, fn) { + if (!this._parserInit) init(this); + debug('write(%o bytes)', chunk.length); + + // XXX: old Writable stream API compat... remove at some point... + if ('function' == typeof encoding) fn = encoding; + + data(this, chunk, null, fn); +} + +/** + * The `_transform()` callback function implementation. + * + * @api private + */ + + +function transform (chunk, output, fn) { + if (!this._parserInit) init(this); + debug('transform(%o bytes)', chunk.length); + + // XXX: old Transform stream API compat... remove at some point... + if ('function' != typeof output) { + output = this._parserOutput; + } + + data(this, chunk, output, fn); +} + +/** + * The internal buffering/passthrough logic... + * + * This `_data` function get's "trampolined" to prevent stack overflows for tight + * loops. This technique requires us to return a "thunk" function for any + * synchronous action. Async stuff breaks the trampoline, but that's ok since it's + * working with a new stack at that point anyway. + * + * @api private + */ + +function _data (stream, chunk, output, fn) { + if (stream._parserBytesLeft <= 0) { + return fn(new Error('got data but not currently parsing anything')); + } + + if (chunk.length <= stream._parserBytesLeft) { + // small buffer fits within the "_parserBytesLeft" window + return function () { + return process(stream, chunk, output, fn); + }; + } else { + // large buffer needs to be sliced on "_parserBytesLeft" and processed + return function () { + var b = chunk.slice(0, stream._parserBytesLeft); + return process(stream, b, output, function (err) { + if (err) return fn(err); + if (chunk.length > b.length) { + return function () { + return _data(stream, chunk.slice(b.length), output, fn); + }; + } + }); + }; + } +} + +/** + * The internal `process` function gets called by the `data` function when + * something "interesting" happens. This function takes care of buffering the + * bytes when buffering, passing through the bytes when doing that, and invoking + * the user callback when the number of bytes has been reached. + * + * @api private + */ + +function process (stream, chunk, output, fn) { + stream._parserBytesLeft -= chunk.length; + debug('%o bytes left for stream piece', stream._parserBytesLeft); + + if (stream._parserState === BUFFERING) { + // buffer + stream._parserBuffers.push(chunk); + stream._parserBuffered += chunk.length; + } else if (stream._parserState === PASSTHROUGH) { + // passthrough + output(chunk); + } + // don't need to do anything for the SKIPPING case + + if (0 === stream._parserBytesLeft) { + // done with stream "piece", invoke the callback + var cb = stream._parserCallback; + if (cb && stream._parserState === BUFFERING && stream._parserBuffers.length > 1) { + chunk = Buffer.concat(stream._parserBuffers, stream._parserBuffered); + } + if (stream._parserState !== BUFFERING) { + chunk = null; + } + stream._parserCallback = null; + stream._parserBuffered = 0; + stream._parserState = INIT; + stream._parserBuffers.splice(0); // empty + + if (cb) { + var args = []; + if (chunk) { + // buffered + args.push(chunk); + } else { + // passthrough + } + if (output) { + // on a Transform stream, has "output" function + args.push(output); + } + var async = cb.length > args.length; + if (async) { + args.push(trampoline(fn)); + } + // invoke cb + var rtn = cb.apply(stream, args); + if (!async || fn === rtn) return fn; + } + } else { + // need more bytes + return fn; + } +} + +var data = trampoline(_data); + +/** + * Generic thunk-based "trampoline" helper function. + * + * @param {Function} input function + * @return {Function} "trampolined" function + * @api private + */ + +function trampoline (fn) { + return function () { + var result = fn.apply(this, arguments); + + while ('function' == typeof result) { + result = result(); + } + + return result; + }; +} diff --git a/node_modules/stream-parser/node_modules/debug/.coveralls.yml b/node_modules/stream-parser/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000000000000000000000000000000000000..20a7068581791335487166ddc5001a2ca3a3b060 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/stream-parser/node_modules/debug/.eslintrc b/node_modules/stream-parser/node_modules/debug/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8a37ae2c2e5a35db74b4607b4c74e0f4fe39a3e4 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/node_modules/stream-parser/node_modules/debug/.npmignore b/node_modules/stream-parser/node_modules/debug/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..5f60eecc84e219e52554407ad38d04abd1cf2111 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/stream-parser/node_modules/debug/.travis.yml b/node_modules/stream-parser/node_modules/debug/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c6090c3b09f2e45d8c0a1dc77ff5f4a81e78a3c --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/node_modules/stream-parser/node_modules/debug/CHANGELOG.md b/node_modules/stream-parser/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..eadaa189517bbcfb2a6784a48ac8d05d2edafe7c --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/stream-parser/node_modules/debug/LICENSE b/node_modules/stream-parser/node_modules/debug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..658c933d28255e8c716899789e8c0f846e5dc125 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software +and associated documentation files (the 'Software'), to deal in the Software without restriction, +including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/node_modules/stream-parser/node_modules/debug/Makefile b/node_modules/stream-parser/node_modules/debug/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..584da8bf938e639ece3ba2bd4105c215c2b1ff51 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/node_modules/stream-parser/node_modules/debug/README.md b/node_modules/stream-parser/node_modules/debug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f67be6b317c19952bb506a9e15e797615eea4533 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + + ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) + + ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + + ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + + ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/stream-parser/node_modules/debug/component.json b/node_modules/stream-parser/node_modules/debug/component.json new file mode 100644 index 0000000000000000000000000000000000000000..9de26410f0d0bba2e48a07f094407d602eb5dd89 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/node_modules/stream-parser/node_modules/debug/karma.conf.js b/node_modules/stream-parser/node_modules/debug/karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..103a82d15bd72b3cdf9ba4108272985f7e0bfdb3 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/node_modules/stream-parser/node_modules/debug/node.js b/node_modules/stream-parser/node_modules/debug/node.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc36fe6dbecbfd41530c5a490cc738ec2968653 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/stream-parser/node_modules/debug/package.json b/node_modules/stream-parser/node_modules/debug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dc787ba76781de4c1d4721b69aa881a548365a90 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/package.json @@ -0,0 +1,49 @@ +{ + "name": "debug", + "version": "2.6.9", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "description": "small debugging utility", + "keywords": [ + "debug", + "log", + "debugger" + ], + "author": "TJ Holowaychuk ", + "contributors": [ + "Nathan Rajlich (http://n8.io)", + "Andrew Rhyne " + ], + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + }, + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "main": "./src/index.js", + "browser": "./src/browser.js", + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + } +} diff --git a/node_modules/stream-parser/node_modules/debug/src/browser.js b/node_modules/stream-parser/node_modules/debug/src/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..7106924934501fd4035efe78678281020328acc5 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/node_modules/stream-parser/node_modules/debug/src/debug.js b/node_modules/stream-parser/node_modules/debug/src/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..6a5e3fc94c3ab80e123c3056b6c5dbe056d21658 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/node_modules/stream-parser/node_modules/debug/src/index.js b/node_modules/stream-parser/node_modules/debug/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e12cf4d58c9f2d6d2d2e656f9cbb0f703cb5fa29 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/stream-parser/node_modules/debug/src/inspector-log.js b/node_modules/stream-parser/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000000000000000000000000000000000000..60ea6c04aafd41d0ea3bcd78f58312ecf0eda436 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/node_modules/stream-parser/node_modules/debug/src/node.js b/node_modules/stream-parser/node_modules/debug/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..b15109c905a45bcb5db701cf37cf4e19385c3167 --- /dev/null +++ b/node_modules/stream-parser/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/node_modules/stream-parser/node_modules/ms/index.js b/node_modules/stream-parser/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6a522b16b3a3bf5e93aa5b8bf485f866ff71c5c2 --- /dev/null +++ b/node_modules/stream-parser/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + 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; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/node_modules/stream-parser/node_modules/ms/license.md b/node_modules/stream-parser/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..69b61253a38926757b7de1d4df4880fc2105c2c9 --- /dev/null +++ b/node_modules/stream-parser/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/stream-parser/node_modules/ms/package.json b/node_modules/stream-parser/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6a31c81fac435ac31d4a802a275128f6a49c4c0c --- /dev/null +++ b/node_modules/stream-parser/node_modules/ms/package.json @@ -0,0 +1,37 @@ +{ + "name": "ms", + "version": "2.0.0", + "description": "Tiny milisecond conversion utility", + "repository": "zeit/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + } +} diff --git a/node_modules/stream-parser/node_modules/ms/readme.md b/node_modules/stream-parser/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..84a9974cccd81f9296b7d3c77f2b0d2765dfe181 --- /dev/null +++ b/node_modules/stream-parser/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms) +[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/stream-parser/package.json b/node_modules/stream-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..242b7b3f72b7d3c549fb325d2021ae33630e05d7 --- /dev/null +++ b/node_modules/stream-parser/package.json @@ -0,0 +1,22 @@ +{ + "name": "stream-parser", + "version": "0.3.1", + "description": "Generic interruptible \"parser\" mixin for Transform & Writable streams", + "main": "index.js", + "scripts": { + "test": "mocha --reporter spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-stream-parser.git" + }, + "author": "Nathan Rajlich (http://tootallnate.net)", + "license": "MIT", + "dependencies": { + "debug": "2" + }, + "devDependencies": { + "mocha": "*", + "readable-stream": "1.0" + } +} diff --git a/node_modules/stream-parser/test/transform.js b/node_modules/stream-parser/test/transform.js new file mode 100644 index 0000000000000000000000000000000000000000..ce233a9cc1cf01ee0314a223e9b64c5964f9ab40 --- /dev/null +++ b/node_modules/stream-parser/test/transform.js @@ -0,0 +1,205 @@ + +/** + * Module dependencies. + */ + +var assert = require('assert'); +var Parser = require('../'); +var Transform = require('stream').Transform; + +// for node v0.6.x-v0.8.x support +if (!Transform) Transform = require('readable-stream/transform'); + +describe('Transform stream', function () { + + it('should have the `_bytes()` function', function () { + var t = new Transform(); + Parser(t); + assert.equal('function', typeof t._bytes); + }); + + it('should have the `_skipBytes()` function', function () { + var t = new Transform(); + Parser(t); + assert.equal('function', typeof t._skipBytes); + }); + + it('should have the `_passthrough()` function', function () { + var t = new Transform(); + Parser(t); + assert.equal('function', typeof t._passthrough); + }); + + it('should read 2 bytes, pass through 2 bytes', function (done) { + var t = new Transform(); + Parser(t); + var gotBytes = false; + var gotPassthrough = false; + var gotData = false; + + // read 2 bytes + t._bytes(2, read); + function read (chunk, output) { + assert.equal(2, chunk.length); + assert.equal(0, chunk[0]); + assert.equal(1, chunk[1]); + gotBytes = true; + t._passthrough(2, passthrough); + } + function passthrough (output) { + gotPassthrough = true; + } + + t.on('data', function (data) { + assert.equal(2, data.length); + assert.equal(2, data[0]); + assert.equal(3, data[1]); + gotData = true; + }); + + t.on('end', function () { + assert(gotBytes); + assert(gotPassthrough); + assert(gotData); + done(); + }); + + t.end(new Buffer([ 0, 1, 2, 3 ])); + }); + + it('should allow you to pass through Infinity bytes', function (done) { + var t = new Transform(); + Parser(t); + t._passthrough(Infinity); + var out = []; + t.on('data', function (data) { + out.push(data); + }); + t.on('end', function () { + assert.equal('hello world', Buffer.concat(out).toString()); + done(); + }); + t.end('hello world'); + }); + + it('should *not* allow you to buffer Infinity bytes', function () { + // buffering to Infinity would just be silly... + var t = new Transform(); + Parser(t); + assert.throws(function () { + t._bytes(Infinity); + }); + }); + + it('should not cause stack overflow', function (done) { + // this one does an admirable amount of CPU work... + this.test.slow(500); + this.test.timeout(1000); + + var t = new Transform(); + Parser(t); + + var bytes = 65536; + t._bytes(1, read); + function read() { + // Any downstream pipe consumer (writable) which doesn't do any async actions. + // e.g. console.log, or simply capturing data into an in-memory data-structure. + if (--bytes) { + t._bytes(1, read); + } else { + done(); + } + } + + var b = new Buffer(bytes); + b.fill('h'); + t.end(b); + }); + + describe('async', function () { + + it('should accept a callback function for `_passthrough()`', function (done) { + var t = new Transform(); + var data = 'test', _data; + Parser(t); + t._passthrough(data.length, function (output, fn) { + setTimeout(fn, 25); + }); + + t.on('data', function (data) { + _data = data; + }); + t.on('end', function () { + assert.equal(data, _data); + done(); + }); + t.end(data); + t.resume(); + }); + + it('should accept a callback function for `_bytes()`', function (done) { + var t = new Transform(); + var data = 'test'; + Parser(t); + t._bytes(data.length, function (chunk, output, fn) { + setTimeout(fn, 25); + }); + + t.on('end', function () { + done(); + }); + t.end(data); + t.resume(); + }); + + it('should work switching between async and sync callbacks', function (done) { + var firstCalled, secondCalled, thirdCalled; + + // create a 6 byte Buffer. The first 4 will be the int + // `1337`. The last 2 will be whatever... + var val = 1337; + var buf = new Buffer(6); + buf.writeUInt32LE(val, 0); + + var t = new Transform(); + Parser(t); + + // first read 4 bytes, with an async callback + function first (chunk, output, fn) { + firstCalled = true; + assert.equal(chunk.length, 4); + assert.equal(val, chunk.readUInt32LE(0)); + + t._bytes(1, second); + setTimeout(fn, 10); + } + + // second read 1 byte, sync callback + function second (chunk) { + secondCalled = true; + assert.equal(chunk.length, 1); + t._bytes(1, third); + } + + // third read 1 byte, async callback + function third (chunk, output, fn) { + thirdCalled = true; + assert.equal(chunk.length, 1); + setTimeout(fn, 10); + } + + t.on('finish', function () { + assert(firstCalled); + assert(secondCalled); + assert(thirdCalled); + done(); + }); + + t._bytes(4, first); + t.write(buf); + t.end(); + }); + + }); + +}); diff --git a/node_modules/stream-parser/test/writable.js b/node_modules/stream-parser/test/writable.js new file mode 100644 index 0000000000000000000000000000000000000000..8e7e0043dfa2cd877b13ad66ba4c5842afbe718b --- /dev/null +++ b/node_modules/stream-parser/test/writable.js @@ -0,0 +1,235 @@ + +/** + * Module dependencies. + */ + +var Parser = require('../'); +var assert = require('assert'); +var inherits = require('util').inherits; +var Writable = require('stream').Writable; + +// for node v0.6.x-v0.8.x support +if (!Writable) Writable = require('readable-stream/writable'); + +describe('Writable streams', function () { + + var val = 1337; + var buf = new Buffer(4); + buf.writeUInt32LE(val, 0); + + it('should have the `_bytes()` function', function () { + var w = new Writable(); + Parser(w); + assert.equal('function', typeof w._bytes); + }); + + it('should have the `_skipBytes()` function', function () { + var w = new Writable(); + Parser(w); + assert.equal('function', typeof w._skipBytes); + }); + + it('should *not* have the `_passthrough()` function', function () { + var w = new Writable(); + Parser(w); + assert.notEqual('function', typeof w._passthrough); + }); + + it('should read 4 bytes in one chunk', function (done) { + var w = new Writable(); + Parser(w); + + // read 4 bytes + w._bytes(4, function (chunk) { + assert.equal(chunk.length, buf.length); + assert.equal(val, chunk.readUInt32LE(0)); + done(); + }); + + w.end(buf); + }); + + it('should read 4 bytes in multiple chunks', function (done) { + var w = new Writable(); + Parser(w); + + // read 4 bytes + w._bytes(4, function (chunk) { + assert.equal(chunk.length, buf.length); + assert.equal(val, chunk.readUInt32LE(0)); + done(); + }); + + for (var i = 0; i < buf.length; i++) { + w.write(new Buffer([ buf[i] ])); + } + w.end(); + }); + + it('should read 1 byte, 2 bytes, then 3 bytes', function (done) { + var w = new Writable(); + Parser(w); + + // read 1 byte + w._bytes(1, readone); + function readone (chunk) { + assert.equal(1, chunk.length); + assert.equal(0, chunk[0]); + w._bytes(2, readtwo); + } + function readtwo (chunk) { + assert.equal(2, chunk.length); + assert.equal(0, chunk[0]); + assert.equal(1, chunk[1]); + w._bytes(3, readthree); + } + function readthree (chunk) { + assert.equal(3, chunk.length); + assert.equal(0, chunk[0]); + assert.equal(1, chunk[1]); + assert.equal(2, chunk[2]); + done(); + } + + w.end(new Buffer([ 0, 0, 1, 0, 1, 2 ])); + }); + + it('should work when mixing in to a subclass\' `prototype`', function (done) { + function MyWritable () { + Writable.call(this); + this._bytes(2, this.onbytes); + } + inherits(MyWritable, Writable); + + // mixin to the `prototype` + Parser(MyWritable.prototype); + + var count = 2; + MyWritable.prototype.onbytes = function (buf) { + assert.equal(2, buf.length); + assert.equal(0, buf[0]); + assert.equal(1, buf[1]); + --count; + if (!count) done(); + }; + + var a = new MyWritable(); + var b = new MyWritable(); + + // interleave write()s + a.write(new Buffer([ 0 ])); + b.write(new Buffer([ 0 ])); + a.write(new Buffer([ 1 ])); + b.write(new Buffer([ 1 ])); + a.end(); + b.end(); + }); + + it('should *not* allow you to buffer Infinity bytes', function () { + // buffering to Infinity would just be silly... + var w = new Writable(); + Parser(w); + assert.throws(function () { + w._bytes(Infinity); + }); + }); + + it('should skip 3 bytes then buffer 3 bytes', function (done) { + var w = new Writable(); + Parser(w); + + w._skipBytes(3, function () { + assert.equal(arguments.length, 0); + w._bytes(3, function (data) { + assert.equal(arguments.length, 1); + assert.equal(data.toString('ascii'), 'lo\n'); + done(); + }); + }); + + w.end('hello\n'); + }); + + describe('async', function () { + + it('should accept a callback function for `_bytes()`', function (done) { + var w = new Writable(); + var data = 'test'; + Parser(w); + w._bytes(data.length, function (chunk, fn) { + setTimeout(fn, 25); + }); + w.on('finish', function () { + done(); + }); + w.end(data); + }); + + it('should emit an "error" event when data is written with no parsing function', function (done) { + var w = new Writable(); + Parser(w); + w.once('error', function (err) { + assert(err); + done(); + }); + w.write('a'); + }); + + }); + + describe('FrameParser', function () { + function FrameParser () { + Writable.call(this); + this._bytes(1, this.onsize); + } + inherits(FrameParser, Writable); + + // mixin to the `prototype` + Parser(FrameParser.prototype); + + FrameParser.prototype.onsize = function (buf) { + var size = buf.readUInt8(0); + this._bytes(size, this.onframe); + }; + + FrameParser.prototype.onframe = function (buf) { + this.emit('frame', buf.toString()); + + // begin parsing the next "frame" + this._bytes(1, this.onsize); + }; + + it('should emit 1 "frame" event', function (done) { + var p = new FrameParser(); + var s = 'a string'; + p.on('frame', function (frame) { + assert.equal(s, frame); + done(); + }); + p.write(new Buffer([ s.length ])); + p.write(new Buffer(s)); + p.end(); + }); + + it('should emit 2 "frame" events', function (done) { + var p = new FrameParser(); + var s = 'a string'; + var s2 = 'done'; + var count = 0; + p.on('frame', function (frame) { + count++; + if (s2 == frame) { + assert.equal(2, count); + done(); + } + }); + p.write(new Buffer([ s.length ])); + p.write(new Buffer(s)); + p.write(new Buffer([ s2.length ])); + p.write(new Buffer(s2)); + p.end(); + }); + + }); + +}); diff --git a/node_modules/stream-shift/.github/workflows/test.yml b/node_modules/stream-shift/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b94272e0cdc616d6de20c52e256de151963be20 --- /dev/null +++ b/node_modules/stream-shift/.github/workflows/test.yml @@ -0,0 +1,23 @@ +name: Build Status +on: + push: + branches: + - master + pull_request: + branches: + - master +jobs: + build: + strategy: + matrix: + node-version: [lts/*] + os: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v3 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v3 + with: + node-version: ${{ matrix.node-version }} + - run: npm install + - run: npm test diff --git a/node_modules/stream-shift/LICENSE b/node_modules/stream-shift/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bae9da7bfae2b5e22cfb0945b362b23ca822c8bb --- /dev/null +++ b/node_modules/stream-shift/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/stream-shift/README.md b/node_modules/stream-shift/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d9cc2d945fa16191a7fb4b589a67c59372fc9dcd --- /dev/null +++ b/node_modules/stream-shift/README.md @@ -0,0 +1,25 @@ +# stream-shift + +Returns the next buffer/object in a stream's readable queue + +``` +npm install stream-shift +``` + +[![build status](http://img.shields.io/travis/mafintosh/stream-shift.svg?style=flat)](http://travis-ci.org/mafintosh/stream-shift) + +## Usage + +``` js +var shift = require('stream-shift') + +console.log(shift(someStream)) // first item in its buffer +``` + +## Credit + +Thanks [@dignifiedquire](https://github.com/dignifiedquire) for making this work on node 6 + +## License + +MIT diff --git a/node_modules/stream-shift/index.js b/node_modules/stream-shift/index.js new file mode 100644 index 0000000000000000000000000000000000000000..566df8880177be36ea1e854169aa2a37c42d1f63 --- /dev/null +++ b/node_modules/stream-shift/index.js @@ -0,0 +1,21 @@ +module.exports = shift + +function shift (stream) { + var rs = stream._readableState + if (!rs) return null + return (rs.objectMode || typeof stream._duplexState === 'number') ? stream.read() : stream.read(getStateLength(rs)) +} + +function getStateLength (state) { + if (state.buffer.length) { + var idx = state.bufferIndex || 0 + // Since node 6.3.0 state.buffer is a BufferList not an array + if (state.buffer.head) { + return state.buffer.head.data.length + } else if (state.buffer.length - idx > 0 && state.buffer[idx]) { + return state.buffer[idx].length + } + } + + return state.length +} diff --git a/node_modules/stream-shift/package.json b/node_modules/stream-shift/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8fe3301178137819ed17164ac9ebcd7e55e0b4c9 --- /dev/null +++ b/node_modules/stream-shift/package.json @@ -0,0 +1,25 @@ +{ + "name": "stream-shift", + "version": "1.0.3", + "description": "Returns the next buffer/object in a stream's readable queue", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^7.1.2", + "tape": "^4.6.0", + "through2": "^2.0.1" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/stream-shift.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/stream-shift/issues" + }, + "homepage": "https://github.com/mafintosh/stream-shift" +} diff --git a/node_modules/stream-shift/test.js b/node_modules/stream-shift/test.js new file mode 100644 index 0000000000000000000000000000000000000000..bf4ed6681aa0c721f307099d5f5d85651e5e17e3 --- /dev/null +++ b/node_modules/stream-shift/test.js @@ -0,0 +1,48 @@ +var tape = require('tape') +var through = require('through2') +var stream = require('stream') +var shift = require('./') + +tape('shifts next', function (t) { + var passthrough = through() + + passthrough.write('hello') + passthrough.write('world') + + t.same(shift(passthrough), Buffer.from('hello')) + t.same(shift(passthrough), Buffer.from('world')) + t.end() +}) + +tape('shifts next with core', function (t) { + var passthrough = stream.PassThrough() + + passthrough.write('hello') + passthrough.write('world') + + t.same(shift(passthrough), Buffer.from('hello')) + t.same(shift(passthrough), Buffer.from('world')) + t.end() +}) + +tape('shifts next with object mode', function (t) { + var passthrough = through({objectMode: true}) + + passthrough.write({hello: 1}) + passthrough.write({world: 1}) + + t.same(shift(passthrough), {hello: 1}) + t.same(shift(passthrough), {world: 1}) + t.end() +}) + +tape('shifts next with object mode with core', function (t) { + var passthrough = stream.PassThrough({objectMode: true}) + + passthrough.write({hello: 1}) + passthrough.write({world: 1}) + + t.same(shift(passthrough), {hello: 1}) + t.same(shift(passthrough), {world: 1}) + t.end() +}) diff --git a/node_modules/string-split-by/.eslintrc.json b/node_modules/string-split-by/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..aaddba5b39068c80de411f77eb6cb292221d69c7 --- /dev/null +++ b/node_modules/string-split-by/.eslintrc.json @@ -0,0 +1,44 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-magic-numbers": ["warn", { "ignore": [1, 0, -1], "ignoreArrayIndexes": true}], + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/string-split-by/.travis.yml b/node_modules/string-split-by/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..c8cd2d2da23a6906ace23c3074a843962557033f --- /dev/null +++ b/node_modules/string-split-by/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - '6' + - '5' + - '4' diff --git a/node_modules/string-split-by/index.js b/node_modules/string-split-by/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f7fc8e6bec2f5ac8651e7d65a320527babfcd8d4 --- /dev/null +++ b/node_modules/string-split-by/index.js @@ -0,0 +1,56 @@ +'use strict' + +var paren = require('parenthesis') + +module.exports = function splitBy (string, separator, o) { + if (string == null) throw Error('First argument should be a string') + if (separator == null) throw Error('Separator should be a string or a RegExp') + + if (!o) o = {} + else if (typeof o === 'string' || Array.isArray(o)) { + o = {ignore: o} + } + + if (o.escape == null) o.escape = true + if (o.ignore == null) o.ignore = ['[]', '()', '{}', '<>', '""', "''", '``', '“”', '«»'] + else { + if (typeof o.ignore === 'string') {o.ignore = [o.ignore]} + + o.ignore = o.ignore.map(function (pair) { + // '"' → '""' + if (pair.length === 1) pair = pair + pair + return pair + }) + } + + var tokens = paren.parse(string, {flat: true, brackets: o.ignore}) + var str = tokens[0] + + var parts = str.split(separator) + + // join parts separated by escape + if (o.escape) { + var cleanParts = [] + for (var i = 0; i < parts.length; i++) { + var prev = parts[i] + var part = parts[i + 1] + + if (prev[prev.length - 1] === '\\' && prev[prev.length - 2] !== '\\') { + cleanParts.push(prev + separator + part) + i++ + } + else { + cleanParts.push(prev) + } + } + parts = cleanParts + } + + // open parens pack & apply unquotes, if any + for (var i = 0; i < parts.length; i++) { + tokens[0] = parts[i] + parts[i] = paren.stringify(tokens, {flat: true}) + } + + return parts +} diff --git a/node_modules/string-split-by/package.json b/node_modules/string-split-by/package.json new file mode 100644 index 0000000000000000000000000000000000000000..378596e9d9d56c1e8415dc02fb9917bc97cdacb6 --- /dev/null +++ b/node_modules/string-split-by/package.json @@ -0,0 +1,33 @@ +{ + "name": "string-split-by", + "version": "1.0.0", + "description": "Split string by any separator excluding brackets, quotes and escaped characters", + "main": "index.js", + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dy/string-split-by.git" + }, + "keywords": [ + "split-string", + "string-split", + "split-stirng-words", + "space", + "string", + "split" + ], + "author": "Dmitry Yv ", + "license": "MIT", + "bugs": { + "url": "https://github.com/dy/string-split-by/issues" + }, + "homepage": "https://github.com/dy/string-split-by#readme", + "dependencies": { + "parenthesis": "^3.1.5" + }, + "devDependencies": { + "tape": "^4.9.0" + } +} diff --git a/node_modules/string-split-by/readme.md b/node_modules/string-split-by/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..22dfbaf6fa12e854e2ef9e96d96154477af4efe7 --- /dev/null +++ b/node_modules/string-split-by/readme.md @@ -0,0 +1,38 @@ +# string-split-by [![unstable](https://img.shields.io/badge/stability-unstable-orange.svg)](http://github.com/badges/stability-badges) [![Build Status](https://img.shields.io/travis/dy/string-split-by.svg)](https://travis-ci.org/dy/string-split-by) + +Split string by a separator with respect to brackets, quotes and escape markers. Optimized version of [string-split](https://github.com/jonschlinkert/split-string). + +## Usage + +[![npm install string-split-by](https://nodei.co/npm/string-split-by.png?mini=true)](https://npmjs.org/package/string-split-by/) + + +```js +var split = require('string-split-by') + +split('a."b.c".d.{.e.f.g.}.h', '.') +// ['a', '"b.c"', 'd', '{.e.f.g.}', 'h'] + +split('a."b.c".d.{.e.f.g.}.h', '.', {ignore: '""'}) +// ['a', '"b.c"', 'd', '{', 'e', 'f', 'g', '}', 'h'] +``` + +## API + +### parts = splitBy(string, separator, options?) + +Return array with parts split from string by a separator, which can be whether _String_ or _RegExp_. Options can define: + +Option | Default | Meaning +---|---|--- +`ignore` | ``['"', "'", '`', '“”', '«»', '[]', '()', '{}']`` | Avoid splitting content enclosed in the character pairs. Can be a string or a list of strings. +`escape` | `true` | Avoid splitting at the escaped separator, eg. `\.` won't be separated by `'.'` separator. + + +## Related + +* [parenthesis](http://npmjs.org/package/parenthesis) + +## License + +© 2018 Dmitry Yv. MIT License diff --git a/node_modules/string-split-by/test.js b/node_modules/string-split-by/test.js new file mode 100644 index 0000000000000000000000000000000000000000..1a2baef6c6517eeaddc055a8876b6e994f07023f --- /dev/null +++ b/node_modules/string-split-by/test.js @@ -0,0 +1,175 @@ +'use strict'; + +var t = require('tape') +var split = require('.'); + +t('should throw an error when arguments are invalid', t => { + t.throws(() => split()); + t.end() +}); + +t('readme', t => { + + t.deepEqual( + split('a."b.c".d.{.e.f.g.}.h', '.'), + ['a', '"b.c"', 'd', '{.e.f.g.}', 'h'] + ) + + t.deepEqual( + split('a."b.c".d.{.e.f.g.}.h', '.', {ignore: '""'}), + ['a', '"b.c"', 'd', '{', 'e', 'f', 'g', '}', 'h'] + ) + t.end() +}) + +t('should not split on escaped dots:', t => { + t.deepEqual(split('a.b.c\\.d', '.'), ['a', 'b', 'c\\.d']); + t.deepEqual(split('a.b.c\\.d.e', '.'), ['a', 'b', 'c\\.d', 'e']); + t.end() +}); + +t('should keep escaping when followed by a backslash:', t => { + t.deepEqual(split('a.b.c\\\\.d', '.'), ['a', 'b', 'c\\\\', 'd']); + t.deepEqual(split('a.b.c\\\\d', '.'), ['a', 'b', 'c\\\\d']); + t.end() +}); + +t('should split a string on dots by default:', t => { + t.deepEqual(split('a.b.c', '.'), ['a', 'b', 'c']); + t.end() +}); + +t('should respect double-quoted strings', t => { + t.deepEqual(split('"b.c"', '.'), ['"b.c"']); + t.deepEqual(split('a."b.c"', '.'), ['a', '"b.c"']); + t.deepEqual(split('a".b.c"', '.'), ['a".b.c"']); + t.deepEqual(split('a."b.c".d', '.'), ['a', '"b.c"', 'd']); + t.deepEqual(split('a."b.c".d.".e.f.g.".h', '.'), ['a', '"b.c"', 'd', '".e.f.g."', 'h']); + t.end() +}); + +t('should respect singlequoted strings', t => { + t.deepEqual(split('\'b.c\'', '.'), ['\'b.c\'']); + t.deepEqual(split('a.\'b.c\'', '.'), ['a', '\'b.c\'']); + t.deepEqual(split('a.\'b.c\'.d', '.'), ['a', '\'b.c\'', 'd']); + t.deepEqual(split('a.\'b.c\'.d.\'.e.f.g.\'.h', '.'), ['a', '\'b.c\'', 'd', '\'.e.f.g.\'', 'h']); + t.end() +}); + +t('should respect strings in backticks', t => { + t.deepEqual(split('`b.c`', '.'), ['`b.c`']); + t.deepEqual(split('a.`b.c`', '.'), ['a', '`b.c`']); + t.deepEqual(split('a.`b.c`.d', '.'), ['a', '`b.c`', 'd']); + t.deepEqual(split('a.`b.c`.d.`.e.f.g.`.h', '.'), ['a', '`b.c`', 'd', '`.e.f.g.`', 'h']); + t.end() +}); + +t('should respect strings in double smart-quotes: “”', t => { + t.deepEqual(split('“b.c”', '.'), ['“b.c”']); + t.deepEqual(split('a.“b.c”', '.'), ['a', '“b.c”']); + t.deepEqual(split('a.“b.c”.d', '.'), ['a', '“b.c”', 'd']); + t.deepEqual(split('a.“b.c”.d.“.e.f.g.”.h', '.'), ['a', '“b.c”', 'd', '“.e.f.g.”', 'h']); + t.end() +}); + +t('should retain unclosed double quotes in the results', t => { + t.deepEqual(split('a."b.c', '.'), ['a', '"b', 'c']); + t.end() +}); + +t('should retain unclosed single quotes in the results', t => { + t.deepEqual(split('brian\'s', '.'), ['brian\'s']); + t.deepEqual(split('a.\'b.c', '.'), ['a', '\'b', 'c']); + t.end() +}); + + + +t('should split on a custom separator', t => { + t.deepEqual(split('a/b/c', '/'), ['a', 'b', 'c']); + t.deepEqual(split('a,b,c', ','), ['a', 'b', 'c']); + t.end() +}); + +t('should not split on an escaped custom separator:', t => { + t.deepEqual(split('a/b/c\\/d', '/'), ['a', 'b', 'c\\/d']); + t.end() +}); + +t('should disable quotes support', t => { + t.deepEqual(split('a.\'b.c\'."d"', '.', {ignore: '"'}), ['a', '\'b', 'c\'', '"d"']); + t.end() +}); + +t('should keep single quotes', t => { + t.deepEqual(split('a.\'b.c\'."d"', '.', {ignore: '\''}), ['a', '\'b.c\'', '"d"']); + t.end() +}); + +t('should keep double quotes', t => { + t.deepEqual(split('a."b.c".d', '.', '"'), ['a', '"b.c"', 'd']); + t.end() +}); + +t('should keep “” double quotes', t => { + t.deepEqual(split('a.“b.c”.d', '.', '“”'), ['a', '“b.c”', 'd']); + t.end() +}); + +t('should keep backticks', t => { + t.deepEqual(split('a.`b.c`.d', '.', {ignore: '`'}), ['a', '`b.c`', 'd']); + t.end() +}); + +t('should allow custom quotes object', t => { + t.deepEqual(split('a.^b.c$', '.', {ignore: '^$'}), ['a', '^b.c$']); + t.deepEqual(split('a.^b.c^', '.', {ignore: '^^'}), ['a', '^b.c^']); + t.deepEqual(split('a.~b.c~', '.', {ignore: '~~'}), ['a', '~b.c~']); + t.end() +}); + +t('should keep escape characters', t => { + t.deepEqual(split('a.b\\.c', '.', {escape: true}), ['a', 'b\\.c']); + t.end() +}); + +t.skip('should throw when brackets are unclosed', t => { + t.throws(function() { + }, /unclosed/); + t.end() +}); + +t('should not split inside brackets', t => { + t.deepEqual(split('a.(b.c).d', '.'), ['a', '(b.c)', 'd']); + t.deepEqual(split('a.[(b.c)].d', '.'), ['a', '[(b.c)]', 'd']); + t.deepEqual(split('a.[b.c].d', '.'), ['a', '[b.c]', 'd']); + t.deepEqual(split('a.{b.c}.d', '.'), ['a', '{b.c}', 'd']); + t.deepEqual(split('a..d', '.'), ['a', '', 'd']); + t.end() +}); + +t('should support nested brackets', t => { + t.deepEqual(split('a.{b.{c}.d}.e', '.'), ['a', '{b.{c}.d}', 'e']); + t.deepEqual(split('a.{b.{c.d}.e}.f', '.'), ['a', '{b.{c.d}.e}', 'f']); + t.deepEqual(split('a.{[b.{{c.d}}.e]}.f', '.'), ['a', '{[b.{{c.d}}.e]}', 'f']); + t.end() +}); + +t.skip('should support escaped brackets', t => { + t.deepEqual(split('a.\\{b.{c.c}.d}.e', '.'), ['a', '{b', '{c.c}', 'd}', 'e']); + t.deepEqual(split('a.{b.c}.\\{d.e}.f', '.'), ['a', '{b.c}', '{d', 'e}', 'f']); + t.end() +}); + +t('should support quoted brackets', t => { + t.deepEqual(split('a.{b.c}."{d.e}".f', '.'), ['a', '{b.c}', '"{d.e}"', 'f']); + t.deepEqual(split('a.{b.c}.{"d.e"}.f', '.'), ['a', '{b.c}', '{"d.e"}', 'f']); + t.end() +}); + +t('should ignore imbalanced brackets', t => { + t.deepEqual(split('a.{b.c', '.'), ['a', '{b', 'c']); + t.deepEqual(split('a.{a.{b.c}.d', '.'), ['a', '{a', '{b.c}', 'd']); + t.end() +}); + diff --git a/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..12b5309751dd50aeef72b96d10a9f81207d27066 --- /dev/null +++ b/node_modules/string-width/index.d.ts @@ -0,0 +1,29 @@ +declare const stringWidth: { + /** + Get the visual width of a string - the number of columns required to display it. + + Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + + @example + ``` + import stringWidth = require('string-width'); + + stringWidth('a'); + //=> 1 + + stringWidth('古'); + //=> 2 + + stringWidth('\u001B[1m古\u001B[22m'); + //=> 2 + ``` + */ + (string: string): number; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function stringWidth(string: string): number; + // export = stringWidth; + default: typeof stringWidth; +} + +export = stringWidth; diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f4d261a96a099ee6b9dcfbf7b050d6e2f42075a2 --- /dev/null +++ b/node_modules/string-width/index.js @@ -0,0 +1,47 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); +const emojiRegex = require('emoji-regex'); + +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports.default = stringWidth; diff --git a/node_modules/string-width/license b/node_modules/string-width/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/string-width/package.json b/node_modules/string-width/package.json new file mode 100644 index 0000000000000000000000000000000000000000..28ba7b4cae9bf9ec20d518c3f9b5ea99833aa94b --- /dev/null +++ b/node_modules/string-width/package.json @@ -0,0 +1,56 @@ +{ + "name": "string-width", + "version": "4.2.3", + "description": "Get the visual width of a string - the number of columns required to display it", + "license": "MIT", + "repository": "sindresorhus/string-width", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..bdd314129ca7471d65d942148049d0ccfdbc0cae --- /dev/null +++ b/node_modules/string-width/readme.md @@ -0,0 +1,50 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/string_decoder/.travis.yml b/node_modules/string_decoder/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..3347a7254650582da5339323466f84fe079fc270 --- /dev/null +++ b/node_modules/string_decoder/.travis.yml @@ -0,0 +1,50 @@ +sudo: false +language: node_js +before_install: + - npm install -g npm@2 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g +notifications: + email: false +matrix: + fast_finish: true + include: + - node_js: '0.8' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.10' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.11' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: '0.12' + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 1 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 2 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 3 + env: + - TASK=test + - NPM_LEGACY=true + - node_js: 4 + env: TASK=test + - node_js: 5 + env: TASK=test + - node_js: 6 + env: TASK=test + - node_js: 7 + env: TASK=test + - node_js: 8 + env: TASK=test + - node_js: 9 + env: TASK=test diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..778edb20730ef48c01002248f4d51e7752c13487 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5fd58315ed588027742dde690a31cd0a2610649d --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..2e89e63f7933e42b8ba543ede35d2a8fa3e4f100 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/node_modules/safe-buffer/LICENSE b/node_modules/string_decoder/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0c068ceecbd48fc4e8279e6451793fec2bf12178 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/string_decoder/node_modules/safe-buffer/README.md b/node_modules/string_decoder/node_modules/safe-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e9a81afd0406f030ba21169f0c7a1dba70b3a93b --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/README.md @@ -0,0 +1,584 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts b/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9fed809a5ab515658d6e71f7ba5f631be769be4 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/string_decoder/node_modules/safe-buffer/index.js b/node_modules/string_decoder/node_modules/safe-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..22438dabbbceef6954a1a7a68038f8c440a90c79 --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/index.js @@ -0,0 +1,62 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/string_decoder/node_modules/safe-buffer/package.json b/node_modules/string_decoder/node_modules/safe-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..623fbc3f6b0c480fb0b3257fc666b1db827378bf --- /dev/null +++ b/node_modules/string_decoder/node_modules/safe-buffer/package.json @@ -0,0 +1,37 @@ +{ + "name": "safe-buffer", + "description": "Safer Node.js Buffer API", + "version": "5.1.2", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + } +} diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000000000000000000000000000000000000..518c3eb9fb1ffbf72bfdf6fed252117b73164673 --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,31 @@ +{ + "name": "string_decoder", + "version": "1.1.1", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "dependencies": { + "safe-buffer": "~5.1.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..907fccc29269ebcd49141fa8a4513be3b6a8d270 --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,17 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +declare function stripAnsi(string: string): string; + +export = stripAnsi; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9a593dfcd1fd5c9e627d9ff2ed85a88df9a41a99 --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1a41108d42831c9c156fdcc4e6cd8c2539983ccd --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,54 @@ +{ + "name": "strip-ansi", + "version": "6.0.1", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..7c4b56d46ddc72a3a627a5fd8f3dfcad8c9b599e --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,46 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + diff --git a/node_modules/strongly-connected-components/.npmignore b/node_modules/strongly-connected-components/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc9ab330c2a9e77591abb3effd1b9ebf278a988 --- /dev/null +++ b/node_modules/strongly-connected-components/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules/* +*.DS_Store \ No newline at end of file diff --git a/node_modules/strongly-connected-components/LICENSE b/node_modules/strongly-connected-components/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8ce206a84544ae1623a4c94db88c18c2d9ed8009 --- /dev/null +++ b/node_modules/strongly-connected-components/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2013 Mikola Lysenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/strongly-connected-components/README.md b/node_modules/strongly-connected-components/README.md new file mode 100644 index 0000000000000000000000000000000000000000..38cbb76b30050f8dbc1b83442af4d8265cbf39ad --- /dev/null +++ b/node_modules/strongly-connected-components/README.md @@ -0,0 +1,41 @@ +strongly-connected-components +============================= +Given a directed graph, splits it into [strongly connected components](http://en.wikipedia.org/wiki/Strongly_connected_component). + +## Example + +```javascript +var scc = require("strongly-connected-components") + +var adjacencyList = [ + [4], // 0 + [0,2], // 1 + [1,3], // 2 + [2], // 3 + [1], // 4 + [4,6], // 5 + [5,2], // 6 + [7,6,3], // 7 +] + +console.log(scc(adjacencyList)) +``` + +## Install + + npm install strongly-connected-components + +## API + +### `require("strongly-connected-components")(adjacencyList)` +Computes the strongly connected components of a graph using Tarjan's algorithm. + +* `adjacencyList` is an array of lists representing the directed edges of the graph + +**Returns** An object containing: + +* `components`: an array of arrays representing the partitioning of the vertices in the graph into connected components. +* `adjacencyList`: an array lists representing the directed edges of the directed acyclic graph between the strongly connected components + +## Credits +(c) 2013 Mikola Lysenko. MIT License. Based on the [implementation of Tarjan's algorithm on Wikipedia.](http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm) diff --git a/node_modules/strongly-connected-components/package.json b/node_modules/strongly-connected-components/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2e54dbeb65cb20b00463947938a69c2e37be35a3 --- /dev/null +++ b/node_modules/strongly-connected-components/package.json @@ -0,0 +1,35 @@ +{ + "name": "strongly-connected-components", + "version": "1.0.1", + "description": "Computes strongly connected components of a directed graph", + "main": "scc.js", + "directories": { + "test": "test" + }, + "dependencies": { + }, + "devDependencies": { + "tape": "~2.1.0", + "tap": "~0.4.4" + }, + "scripts": { + "test": "tap test/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/mikolalysenko/strongly-connected-components.git" + }, + "keywords": [ + "strongly", + "connected", + "component", + "directed", + "graph", + "tarjan" + ], + "author": "Mikola Lysenko", + "license": "MIT", + "bugs": { + "url": "https://github.com/mikolalysenko/strongly-connected-components/issues" + } +} diff --git a/node_modules/strongly-connected-components/scc.js b/node_modules/strongly-connected-components/scc.js new file mode 100644 index 0000000000000000000000000000000000000000..4c1124ea6227fcb15076f2f7cae73e710267ea45 --- /dev/null +++ b/node_modules/strongly-connected-components/scc.js @@ -0,0 +1,114 @@ +"use strict" + +module.exports = stronglyConnectedComponents + +function stronglyConnectedComponents(adjList) { + var numVertices = adjList.length; + var index = new Array(numVertices) + var lowValue = new Array(numVertices) + var active = new Array(numVertices) + var child = new Array(numVertices) + var scc = new Array(numVertices) + var sccLinks = new Array(numVertices) + + //Initialize tables + for(var i=0; i 0) { + v = T[T.length-1] + var e = adjList[v] + if (child[v] < e.length) { // If we're not done iterating over the children, first try finishing that. + for(var i=child[v]; i= 0) { + // Node v is not yet assigned an scc, but once it is that scc can apparently reach scc[u]. + sccLinks[v].push(scc[u]) + } + } + child[v] = i // Remember where we left off. + } else { // If we're done iterating over the children, check whether we have an scc. + if(lowValue[v] === index[v]) { // TODO: It /might/ be true that T is always a prefix of S (at this point!!!), and if so, this could be used here. + var component = [] + var links = [], linkCount = 0 + for(var i=S.length-1; i>=0; --i) { + var w = S[i] + active[w] = false + component.push(w) + links.push(sccLinks[w]) + linkCount += sccLinks[w].length + scc[w] = components.length + if(w === v) { + S.length = i + break + } + } + components.push(component) + var allLinks = new Array(linkCount) + for(var i=0; i 4 -> 1 -> 0, 1 -> 2 -> 1, 2 -> 3 -> 2 + // B: 5 -> 6 -> 5 + // C: 7 -> 7 + // graph on SCCs: + // B -> A + // C -> A, B + + var sccRet = scc(g) + console.log(sccRet) + t.equal(sccRet.components.length, 3) + + t.end() +}) diff --git a/node_modules/supercluster/LICENSE b/node_modules/supercluster/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..631921c40afa67e575bfbdf0d812b54426946cec --- /dev/null +++ b/node_modules/supercluster/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2021, Mapbox + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/supercluster/README.md b/node_modules/supercluster/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df5dbb65e9f199fd5f1b4abe372c7694eef5dcc8 --- /dev/null +++ b/node_modules/supercluster/README.md @@ -0,0 +1,108 @@ +# supercluster [![Simply Awesome](https://img.shields.io/badge/simply-awesome-brightgreen.svg)](https://github.com/mourner/projects) [![Build Status](https://travis-ci.org/mapbox/supercluster.svg?branch=main)](https://travis-ci.org/mapbox/supercluster) + +A very fast JavaScript library for geospatial point clustering for browsers and Node. + +```html + +``` + +```js +const index = new Supercluster({ + radius: 40, + maxZoom: 16 +}); +index.load(points); +index.getClusters([-180, -85, 180, 85], 2); +``` + +Clustering 6 million points in Leaflet: + +![clusters2](https://cloud.githubusercontent.com/assets/25395/11857351/43407b46-a40c-11e5-8662-e99ab1cd2cb7.gif) + +## Install + +Install using NPM (`npm install supercluster`) or Yarn (`yarn add supercluster`), then: + +```js +// import as a ES module +import Supercluster from 'supercluster'; + +// or require in Node / Browserify +const Supercluster = require('supercluster'); +``` + +Or use a browser build directly: + +```html + +``` + +## Methods + +#### `load(points)` + +Loads an array of [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2) objects. Each feature's `geometry` must be a [GeoJSON Point](https://tools.ietf.org/html/rfc7946#section-3.1.2). Once loaded, index is immutable. + +#### `getClusters(bbox, zoom)` + +For the given `bbox` array (`[westLng, southLat, eastLng, northLat]`) and integer `zoom`, returns an array of clusters and points as [GeoJSON Feature](https://tools.ietf.org/html/rfc7946#section-3.2) objects. + +#### `getTile(z, x, y)` + +For a given zoom and x/y coordinates, returns a [geojson-vt](https://github.com/mapbox/geojson-vt)-compatible JSON tile object with cluster/point features. + +#### `getChildren(clusterId)` + +Returns the children of a cluster (on the next zoom level) given its id (`cluster_id` value from feature properties). + +#### `getLeaves(clusterId, limit = 10, offset = 0)` + +Returns all the points of a cluster (given its `cluster_id`), with pagination support: +`limit` is the number of points to return (set to `Infinity` for all points), +and `offset` is the amount of points to skip (for pagination). + +#### `getClusterExpansionZoom(clusterId)` + +Returns the zoom on which the cluster expands into several children (useful for "click to zoom" feature) given the cluster's `cluster_id`. + +## Options + +| Option | Default | Description | +|------------|---------|-------------------------------------------------------------------| +| minZoom | 0 | Minimum zoom level at which clusters are generated. | +| maxZoom | 16 | Maximum zoom level at which clusters are generated. | +| minPoints | 2 | Minimum number of points to form a cluster. | +| radius | 40 | Cluster radius, in pixels. | +| extent | 512 | (Tiles) Tile extent. Radius is calculated relative to this value. | +| nodeSize | 64 | Size of the KD-tree leaf node. Affects performance. | +| log | false | Whether timing info should be logged. | +| generateId | false | Whether to generate ids for input features in vector tiles. | + +### Property map/reduce options + +In addition to the options above, Supercluster supports property aggregation with the following two options: + +- `map`: a function that returns cluster properties corresponding to a single point. +- `reduce`: a reduce function that merges properties of two clusters into one. + +Example of setting up a `sum` cluster property that accumulates the sum of `myValue` property values: + +```js +const index = new Supercluster({ + map: (props) => ({sum: props.myValue}), + reduce: (accumulated, props) => { accumulated.sum += props.sum; } +}); +``` + +The `map`/`reduce` options must satisfy these conditions to work correctly: + +- `map` must return a new object, not existing `properties` of a point, otherwise it will get overwritten. +- `reduce` must not mutate the second argument (`props`). + +## Developing Supercluster + +``` +npm install # install dependencies +npm run build # generate dist/supercluster.js and dist/supercluster.min.js +npm test # run tests +``` diff --git a/node_modules/supercluster/dist/supercluster.js b/node_modules/supercluster/dist/supercluster.js new file mode 100644 index 0000000000000000000000000000000000000000..30357ce9078c408ffb86c1819f51719afce4a8c6 --- /dev/null +++ b/node_modules/supercluster/dist/supercluster.js @@ -0,0 +1,635 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Supercluster = factory()); +})(this, (function () { 'use strict'; + +function sortKD(ids, coords, nodeSize, left, right, depth) { + if (right - left <= nodeSize) { return; } + + var m = (left + right) >> 1; + + select(ids, coords, m, left, right, depth % 2); + + sortKD(ids, coords, nodeSize, left, m - 1, depth + 1); + sortKD(ids, coords, nodeSize, m + 1, right, depth + 1); +} + +function select(ids, coords, k, left, right, inc) { + + while (right > left) { + if (right - left > 600) { + var n = right - left + 1; + var m = k - left + 1; + var z = Math.log(n); + var s = 0.5 * Math.exp(2 * z / 3); + var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1); + var newLeft = Math.max(left, Math.floor(k - m * s / n + sd)); + var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd)); + select(ids, coords, k, newLeft, newRight, inc); + } + + var t = coords[2 * k + inc]; + var i = left; + var j = right; + + swapItem(ids, coords, left, k); + if (coords[2 * right + inc] > t) { swapItem(ids, coords, left, right); } + + while (i < j) { + swapItem(ids, coords, i, j); + i++; + j--; + while (coords[2 * i + inc] < t) { i++; } + while (coords[2 * j + inc] > t) { j--; } + } + + if (coords[2 * left + inc] === t) { swapItem(ids, coords, left, j); } + else { + j++; + swapItem(ids, coords, j, right); + } + + if (j <= k) { left = j + 1; } + if (k <= j) { right = j - 1; } + } +} + +function swapItem(ids, coords, i, j) { + swap(ids, i, j); + swap(coords, 2 * i, 2 * j); + swap(coords, 2 * i + 1, 2 * j + 1); +} + +function swap(arr, i, j) { + var tmp = arr[i]; + arr[i] = arr[j]; + arr[j] = tmp; +} + +function range(ids, coords, minX, minY, maxX, maxY, nodeSize) { + var stack = [0, ids.length - 1, 0]; + var result = []; + var x, y; + + while (stack.length) { + var axis = stack.pop(); + var right = stack.pop(); + var left = stack.pop(); + + if (right - left <= nodeSize) { + for (var i = left; i <= right; i++) { + x = coords[2 * i]; + y = coords[2 * i + 1]; + if (x >= minX && x <= maxX && y >= minY && y <= maxY) { result.push(ids[i]); } + } + continue; + } + + var m = Math.floor((left + right) / 2); + + x = coords[2 * m]; + y = coords[2 * m + 1]; + + if (x >= minX && x <= maxX && y >= minY && y <= maxY) { result.push(ids[m]); } + + var nextAxis = (axis + 1) % 2; + + if (axis === 0 ? minX <= x : minY <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(nextAxis); + } + if (axis === 0 ? maxX >= x : maxY >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(nextAxis); + } + } + + return result; +} + +function within(ids, coords, qx, qy, r, nodeSize) { + var stack = [0, ids.length - 1, 0]; + var result = []; + var r2 = r * r; + + while (stack.length) { + var axis = stack.pop(); + var right = stack.pop(); + var left = stack.pop(); + + if (right - left <= nodeSize) { + for (var i = left; i <= right; i++) { + if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) { result.push(ids[i]); } + } + continue; + } + + var m = Math.floor((left + right) / 2); + + var x = coords[2 * m]; + var y = coords[2 * m + 1]; + + if (sqDist(x, y, qx, qy) <= r2) { result.push(ids[m]); } + + var nextAxis = (axis + 1) % 2; + + if (axis === 0 ? qx - r <= x : qy - r <= y) { + stack.push(left); + stack.push(m - 1); + stack.push(nextAxis); + } + if (axis === 0 ? qx + r >= x : qy + r >= y) { + stack.push(m + 1); + stack.push(right); + stack.push(nextAxis); + } + } + + return result; +} + +function sqDist(ax, ay, bx, by) { + var dx = ax - bx; + var dy = ay - by; + return dx * dx + dy * dy; +} + +var defaultGetX = function (p) { return p[0]; }; +var defaultGetY = function (p) { return p[1]; }; + +var KDBush = function KDBush(points, getX, getY, nodeSize, ArrayType) { + if ( getX === void 0 ) getX = defaultGetX; + if ( getY === void 0 ) getY = defaultGetY; + if ( nodeSize === void 0 ) nodeSize = 64; + if ( ArrayType === void 0 ) ArrayType = Float64Array; + + this.nodeSize = nodeSize; + this.points = points; + + var IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array; + + var ids = this.ids = new IndexArrayType(points.length); + var coords = this.coords = new ArrayType(points.length * 2); + + for (var i = 0; i < points.length; i++) { + ids[i] = i; + coords[2 * i] = getX(points[i]); + coords[2 * i + 1] = getY(points[i]); + } + + sortKD(ids, coords, nodeSize, 0, ids.length - 1, 0); +}; + +KDBush.prototype.range = function range$1 (minX, minY, maxX, maxY) { + return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize); +}; + +KDBush.prototype.within = function within$1 (x, y, r) { + return within(this.ids, this.coords, x, y, r, this.nodeSize); +}; + +var defaultOptions = { + minZoom: 0, // min zoom to generate clusters on + maxZoom: 16, // max zoom level to cluster the points on + minPoints: 2, // minimum points to form a cluster + radius: 40, // cluster radius in pixels + extent: 512, // tile extent (radius is calculated relative to it) + nodeSize: 64, // size of the KD-tree leaf node, affects performance + log: false, // whether to log timing info + + // whether to generate numeric ids for input features (in vector tiles) + generateId: false, + + // a reduce function for calculating custom cluster properties + reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; } + + // properties to use for individual points when running the reducer + map: function (props) { return props; } // props => ({sum: props.my_value}) +}; + +var fround = Math.fround || (function (tmp) { return (function (x) { tmp[0] = +x; return tmp[0]; }); })(new Float32Array(1)); + +var Supercluster = function Supercluster(options) { + this.options = extend(Object.create(defaultOptions), options); + this.trees = new Array(this.options.maxZoom + 1); +}; + +Supercluster.prototype.load = function load (points) { + var ref = this.options; + var log = ref.log; + var minZoom = ref.minZoom; + var maxZoom = ref.maxZoom; + var nodeSize = ref.nodeSize; + + if (log) { console.time('total time'); } + + var timerId = "prepare " + (points.length) + " points"; + if (log) { console.time(timerId); } + + this.points = points; + + // generate a cluster object for each point and index input points into a KD-tree + var clusters = []; + for (var i = 0; i < points.length; i++) { + if (!points[i].geometry) { continue; } + clusters.push(createPointCluster(points[i], i)); + } + this.trees[maxZoom + 1] = new KDBush(clusters, getX, getY, nodeSize, Float32Array); + + if (log) { console.timeEnd(timerId); } + + // cluster points on max zoom, then cluster the results on previous zoom, etc.; + // results in a cluster hierarchy across zoom levels + for (var z = maxZoom; z >= minZoom; z--) { + var now = +Date.now(); + + // create a new set of clusters for the zoom and index them with a KD-tree + clusters = this._cluster(clusters, z); + this.trees[z] = new KDBush(clusters, getX, getY, nodeSize, Float32Array); + + if (log) { console.log('z%d: %d clusters in %dms', z, clusters.length, +Date.now() - now); } + } + + if (log) { console.timeEnd('total time'); } + + return this; +}; + +Supercluster.prototype.getClusters = function getClusters (bbox, zoom) { + var minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; + var minLat = Math.max(-90, Math.min(90, bbox[1])); + var maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; + var maxLat = Math.max(-90, Math.min(90, bbox[3])); + + if (bbox[2] - bbox[0] >= 360) { + minLng = -180; + maxLng = 180; + } else if (minLng > maxLng) { + var easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom); + var westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom); + return easternHem.concat(westernHem); + } + + var tree = this.trees[this._limitZoom(zoom)]; + var ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat)); + var clusters = []; + for (var i = 0, list = ids; i < list.length; i += 1) { + var id = list[i]; + + var c = tree.points[id]; + clusters.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]); + } + return clusters; +}; + +Supercluster.prototype.getChildren = function getChildren (clusterId) { + var originId = this._getOriginId(clusterId); + var originZoom = this._getOriginZoom(clusterId); + var errorMsg = 'No cluster with the specified id.'; + + var index = this.trees[originZoom]; + if (!index) { throw new Error(errorMsg); } + + var origin = index.points[originId]; + if (!origin) { throw new Error(errorMsg); } + + var r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); + var ids = index.within(origin.x, origin.y, r); + var children = []; + for (var i = 0, list = ids; i < list.length; i += 1) { + var id = list[i]; + + var c = index.points[id]; + if (c.parentId === clusterId) { + children.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]); + } + } + + if (children.length === 0) { throw new Error(errorMsg); } + + return children; +}; + +Supercluster.prototype.getLeaves = function getLeaves (clusterId, limit, offset) { + limit = limit || 10; + offset = offset || 0; + + var leaves = []; + this._appendLeaves(leaves, clusterId, limit, offset, 0); + + return leaves; +}; + +Supercluster.prototype.getTile = function getTile (z, x, y) { + var tree = this.trees[this._limitZoom(z)]; + var z2 = Math.pow(2, z); + var ref = this.options; + var extent = ref.extent; + var radius = ref.radius; + var p = radius / extent; + var top = (y - p) / z2; + var bottom = (y + 1 + p) / z2; + + var tile = { + features: [] + }; + + this._addTileFeatures( + tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), + tree.points, x, y, z2, tile); + + if (x === 0) { + this._addTileFeatures( + tree.range(1 - p / z2, top, 1, bottom), + tree.points, z2, y, z2, tile); + } + if (x === z2 - 1) { + this._addTileFeatures( + tree.range(0, top, p / z2, bottom), + tree.points, -1, y, z2, tile); + } + + return tile.features.length ? tile : null; +}; + +Supercluster.prototype.getClusterExpansionZoom = function getClusterExpansionZoom (clusterId) { + var expansionZoom = this._getOriginZoom(clusterId) - 1; + while (expansionZoom <= this.options.maxZoom) { + var children = this.getChildren(clusterId); + expansionZoom++; + if (children.length !== 1) { break; } + clusterId = children[0].properties.cluster_id; + } + return expansionZoom; +}; + +Supercluster.prototype._appendLeaves = function _appendLeaves (result, clusterId, limit, offset, skipped) { + var children = this.getChildren(clusterId); + + for (var i = 0, list = children; i < list.length; i += 1) { + var child = list[i]; + + var props = child.properties; + + if (props && props.cluster) { + if (skipped + props.point_count <= offset) { + // skip the whole cluster + skipped += props.point_count; + } else { + // enter the cluster + skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped); + // exit the cluster + } + } else if (skipped < offset) { + // skip a single point + skipped++; + } else { + // add a single point + result.push(child); + } + if (result.length === limit) { break; } + } + + return skipped; +}; + +Supercluster.prototype._addTileFeatures = function _addTileFeatures (ids, points, x, y, z2, tile) { + for (var i$1 = 0, list = ids; i$1 < list.length; i$1 += 1) { + var i = list[i$1]; + + var c = points[i]; + var isCluster = c.numPoints; + + var tags = (void 0), px = (void 0), py = (void 0); + if (isCluster) { + tags = getClusterProperties(c); + px = c.x; + py = c.y; + } else { + var p = this.points[c.index]; + tags = p.properties; + px = lngX(p.geometry.coordinates[0]); + py = latY(p.geometry.coordinates[1]); + } + + var f = { + type: 1, + geometry: [[ + Math.round(this.options.extent * (px * z2 - x)), + Math.round(this.options.extent * (py * z2 - y)) + ]], + tags: tags + }; + + // assign id + var id = (void 0); + if (isCluster) { + id = c.id; + } else if (this.options.generateId) { + // optionally generate id + id = c.index; + } else if (this.points[c.index].id) { + // keep id if already assigned + id = this.points[c.index].id; + } + + if (id !== undefined) { f.id = id; } + + tile.features.push(f); + } +}; + +Supercluster.prototype._limitZoom = function _limitZoom (z) { + return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); +}; + +Supercluster.prototype._cluster = function _cluster (points, zoom) { + var clusters = []; + var ref = this.options; + var radius = ref.radius; + var extent = ref.extent; + var reduce = ref.reduce; + var minPoints = ref.minPoints; + var r = radius / (extent * Math.pow(2, zoom)); + + // loop through each point + for (var i = 0; i < points.length; i++) { + var p = points[i]; + // if we've already visited the point at this zoom level, skip it + if (p.zoom <= zoom) { continue; } + p.zoom = zoom; + + // find all nearby points + var tree = this.trees[zoom + 1]; + var neighborIds = tree.within(p.x, p.y, r); + + var numPointsOrigin = p.numPoints || 1; + var numPoints = numPointsOrigin; + + // count the number of points in a potential cluster + for (var i$1 = 0, list = neighborIds; i$1 < list.length; i$1 += 1) { + var neighborId = list[i$1]; + + var b = tree.points[neighborId]; + // filter out neighbors that are already processed + if (b.zoom > zoom) { numPoints += b.numPoints || 1; } + } + + // if there were neighbors to merge, and there are enough points to form a cluster + if (numPoints > numPointsOrigin && numPoints >= minPoints) { + var wx = p.x * numPointsOrigin; + var wy = p.y * numPointsOrigin; + + var clusterProperties = reduce && numPointsOrigin > 1 ? this._map(p, true) : null; + + // encode both zoom and point index on which the cluster originated -- offset by total length of features + var id = (i << 5) + (zoom + 1) + this.points.length; + + for (var i$2 = 0, list$1 = neighborIds; i$2 < list$1.length; i$2 += 1) { + var neighborId$1 = list$1[i$2]; + + var b$1 = tree.points[neighborId$1]; + + if (b$1.zoom <= zoom) { continue; } + b$1.zoom = zoom; // save the zoom (so it doesn't get processed twice) + + var numPoints2 = b$1.numPoints || 1; + wx += b$1.x * numPoints2; // accumulate coordinates for calculating weighted center + wy += b$1.y * numPoints2; + + b$1.parentId = id; + + if (reduce) { + if (!clusterProperties) { clusterProperties = this._map(p, true); } + reduce(clusterProperties, this._map(b$1)); + } + } + + p.parentId = id; + clusters.push(createCluster(wx / numPoints, wy / numPoints, id, numPoints, clusterProperties)); + + } else { // left points as unclustered + clusters.push(p); + + if (numPoints > 1) { + for (var i$3 = 0, list$2 = neighborIds; i$3 < list$2.length; i$3 += 1) { + var neighborId$2 = list$2[i$3]; + + var b$2 = tree.points[neighborId$2]; + if (b$2.zoom <= zoom) { continue; } + b$2.zoom = zoom; + clusters.push(b$2); + } + } + } + } + + return clusters; +}; + +// get index of the point from which the cluster originated +Supercluster.prototype._getOriginId = function _getOriginId (clusterId) { + return (clusterId - this.points.length) >> 5; +}; + +// get zoom of the point from which the cluster originated +Supercluster.prototype._getOriginZoom = function _getOriginZoom (clusterId) { + return (clusterId - this.points.length) % 32; +}; + +Supercluster.prototype._map = function _map (point, clone) { + if (point.numPoints) { + return clone ? extend({}, point.properties) : point.properties; + } + var original = this.points[point.index].properties; + var result = this.options.map(original); + return clone && result === original ? extend({}, result) : result; +}; + +function createCluster(x, y, id, numPoints, properties) { + return { + x: fround(x), // weighted cluster center; round for consistency with Float32Array index + y: fround(y), + zoom: Infinity, // the last zoom the cluster was processed at + id: id, // encodes index of the first child of the cluster and its zoom level + parentId: -1, // parent cluster id + numPoints: numPoints, + properties: properties + }; +} + +function createPointCluster(p, id) { + var ref = p.geometry.coordinates; + var x = ref[0]; + var y = ref[1]; + return { + x: fround(lngX(x)), // projected point coordinates + y: fround(latY(y)), + zoom: Infinity, // the last zoom the point was processed at + index: id, // index of the source feature in the original input array, + parentId: -1 // parent cluster id + }; +} + +function getClusterJSON(cluster) { + return { + type: 'Feature', + id: cluster.id, + properties: getClusterProperties(cluster), + geometry: { + type: 'Point', + coordinates: [xLng(cluster.x), yLat(cluster.y)] + } + }; +} + +function getClusterProperties(cluster) { + var count = cluster.numPoints; + var abbrev = + count >= 10000 ? ((Math.round(count / 1000)) + "k") : + count >= 1000 ? ((Math.round(count / 100) / 10) + "k") : count; + return extend(extend({}, cluster.properties), { + cluster: true, + cluster_id: cluster.id, + point_count: count, + point_count_abbreviated: abbrev + }); +} + +// longitude/latitude to spherical mercator in [0..1] range +function lngX(lng) { + return lng / 360 + 0.5; +} +function latY(lat) { + var sin = Math.sin(lat * Math.PI / 180); + var y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); + return y < 0 ? 0 : y > 1 ? 1 : y; +} + +// spherical mercator to longitude/latitude +function xLng(x) { + return (x - 0.5) * 360; +} +function yLat(y) { + var y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; +} + +function extend(dest, src) { + for (var id in src) { dest[id] = src[id]; } + return dest; +} + +function getX(p) { + return p.x; +} +function getY(p) { + return p.y; +} + +return Supercluster; + +})); diff --git a/node_modules/supercluster/dist/supercluster.min.js b/node_modules/supercluster/dist/supercluster.min.js new file mode 100644 index 0000000000000000000000000000000000000000..c664984df048d1697a28e1de01244dc6cfb96735 --- /dev/null +++ b/node_modules/supercluster/dist/supercluster.min.js @@ -0,0 +1 @@ +!function(t,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o():"function"==typeof define&&define.amd?define(o):(t="undefined"!=typeof globalThis?globalThis:t||self).Supercluster=o()}(this,(function(){"use strict";function t(e,n,r,i,s,a){if(!(s-i<=r)){var p=i+s>>1;o(e,n,p,i,s,a%2),t(e,n,r,i,p-1,a+1),t(e,n,r,p+1,s,a+1)}}function o(t,n,r,i,s,a){for(;s>i;){if(s-i>600){var p=s-i+1,h=r-i+1,u=Math.log(p),f=.5*Math.exp(2*u/3),d=.5*Math.sqrt(u*f*(p-f)/p)*(h-p/2<0?-1:1);o(t,n,r,Math.max(i,Math.floor(r-h*f/p+d)),Math.min(s,Math.floor(r+(p-h)*f/p+d)),a)}var l=n[2*r+a],m=i,c=s;for(e(t,n,i,r),n[2*s+a]>l&&e(t,n,i,s);ml;)c--}n[2*i+a]===l?e(t,n,i,c):e(t,n,++c,s),c<=r&&(i=c+1),r<=c&&(s=c-1)}}function e(t,o,e,r){n(t,e,r),n(o,2*e,2*r),n(o,2*e+1,2*r+1)}function n(t,o,e){var n=t[o];t[o]=t[e],t[e]=n}function r(t,o,e,n){var r=t-e,i=o-n;return r*r+i*i}var i=function(t){return t[0]},s=function(t){return t[1]},a=function(o,e,n,r,a){void 0===e&&(e=i),void 0===n&&(n=s),void 0===r&&(r=64),void 0===a&&(a=Float64Array),this.nodeSize=r,this.points=o;for(var p=o.length<65536?Uint16Array:Uint32Array,h=this.ids=new p(o.length),u=this.coords=new a(2*o.length),f=0;f=e&&a<=r&&p>=n&&p<=i&&u.push(t[m]);else{var c=Math.floor((l+d)/2);a=o[2*c],p=o[2*c+1],a>=e&&a<=r&&p>=n&&p<=i&&u.push(t[c]);var v=(f+1)%2;(0===f?e<=a:n<=p)&&(h.push(l),h.push(c-1),h.push(v)),(0===f?r>=a:i>=p)&&(h.push(c+1),h.push(d),h.push(v))}}return u}(this.ids,this.coords,t,o,e,n,this.nodeSize)},a.prototype.within=function(t,o,e){return function(t,o,e,n,i,s){for(var a=[0,t.length-1,0],p=[],h=i*i;a.length;){var u=a.pop(),f=a.pop(),d=a.pop();if(f-d<=s)for(var l=d;l<=f;l++)r(o[2*l],o[2*l+1],e,n)<=h&&p.push(t[l]);else{var m=Math.floor((d+f)/2),c=o[2*m],v=o[2*m+1];r(c,v,e,n)<=h&&p.push(t[m]);var g=(u+1)%2;(0===u?e-i<=c:n-i<=v)&&(a.push(d),a.push(m-1),a.push(g)),(0===u?e+i>=c:n+i>=v)&&(a.push(m+1),a.push(f),a.push(g))}}return p}(this.ids,this.coords,t,o,e,this.nodeSize)};var p,h={minZoom:0,maxZoom:16,minPoints:2,radius:40,extent:512,nodeSize:64,log:!1,generateId:!1,reduce:null,map:function(t){return t}},u=Math.fround||(p=new Float32Array(1),function(t){return p[0]=+t,p[0]}),f=function(t){this.options=y(Object.create(h),t),this.trees=new Array(this.options.maxZoom+1)};function d(t,o,e,n,r){return{x:u(t),y:u(o),zoom:1/0,id:e,parentId:-1,numPoints:n,properties:r}}function l(t,o){var e=t.geometry.coordinates,n=e[0],r=e[1];return{x:u(v(n)),y:u(g(r)),zoom:1/0,index:o,parentId:-1}}function m(t){return{type:"Feature",id:t.id,properties:c(t),geometry:{type:"Point",coordinates:[(n=t.x,360*(n-.5)),(o=t.y,e=(180-360*o)*Math.PI/180,360*Math.atan(Math.exp(e))/Math.PI-90)]}};var o,e,n}function c(t){var o=t.numPoints,e=o>=1e4?Math.round(o/1e3)+"k":o>=1e3?Math.round(o/100)/10+"k":o;return y(y({},t.properties),{cluster:!0,cluster_id:t.id,point_count:o,point_count_abbreviated:e})}function v(t){return t/360+.5}function g(t){var o=Math.sin(t*Math.PI/180),e=.5-.25*Math.log((1+o)/(1-o))/Math.PI;return e<0?0:e>1?1:e}function y(t,o){for(var e in o)t[e]=o[e];return t}function x(t){return t.x}function M(t){return t.y}return f.prototype.load=function(t){var o=this.options,e=o.log,n=o.minZoom,r=o.maxZoom,i=o.nodeSize;e&&console.time("total time");var s="prepare "+t.length+" points";e&&console.time(s),this.points=t;for(var p=[],h=0;h=n;u--){var f=+Date.now();p=this._cluster(p,u),this.trees[u]=new a(p,x,M,i,Float32Array),e&&console.log("z%d: %d clusters in %dms",u,p.length,+Date.now()-f)}return e&&console.timeEnd("total time"),this},f.prototype.getClusters=function(t,o){var e=((t[0]+180)%360+360)%360-180,n=Math.max(-90,Math.min(90,t[1])),r=180===t[2]?180:((t[2]+180)%360+360)%360-180,i=Math.max(-90,Math.min(90,t[3]));if(t[2]-t[0]>=360)e=-180,r=180;else if(e>r){var s=this.getClusters([e,n,180,i],o),a=this.getClusters([-180,n,r,i],o);return s.concat(a)}for(var p=this.trees[this._limitZoom(o)],h=[],u=0,f=p.range(v(e),g(i),v(r),g(n));uo&&(c+=x.numPoints||1)}if(c>m&&c>=a){for(var M=u.x*m,_=u.y*m,w=s&&m>1?this._map(u,!0):null,P=(h<<5)+(o+1)+this.points.length,z=0,Z=l;z1)for(var A=0,C=l;A>5},f.prototype._getOriginZoom=function(t){return(t-this.points.length)%32},f.prototype._map=function(t,o){if(t.numPoints)return o?y({},t.properties):t.properties;var e=this.points[t.index].properties,n=this.options.map(e);return o&&n===e?y({},n):n},f})); diff --git a/node_modules/supercluster/index.js b/node_modules/supercluster/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dc2601ba936d9a9948c236305eee346508f82a71 --- /dev/null +++ b/node_modules/supercluster/index.js @@ -0,0 +1,417 @@ + +import KDBush from 'kdbush'; + +const defaultOptions = { + minZoom: 0, // min zoom to generate clusters on + maxZoom: 16, // max zoom level to cluster the points on + minPoints: 2, // minimum points to form a cluster + radius: 40, // cluster radius in pixels + extent: 512, // tile extent (radius is calculated relative to it) + nodeSize: 64, // size of the KD-tree leaf node, affects performance + log: false, // whether to log timing info + + // whether to generate numeric ids for input features (in vector tiles) + generateId: false, + + // a reduce function for calculating custom cluster properties + reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; } + + // properties to use for individual points when running the reducer + map: props => props // props => ({sum: props.my_value}) +}; + +const fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1)); + +export default class Supercluster { + constructor(options) { + this.options = extend(Object.create(defaultOptions), options); + this.trees = new Array(this.options.maxZoom + 1); + } + + load(points) { + const {log, minZoom, maxZoom, nodeSize} = this.options; + + if (log) console.time('total time'); + + const timerId = `prepare ${ points.length } points`; + if (log) console.time(timerId); + + this.points = points; + + // generate a cluster object for each point and index input points into a KD-tree + let clusters = []; + for (let i = 0; i < points.length; i++) { + if (!points[i].geometry) continue; + clusters.push(createPointCluster(points[i], i)); + } + this.trees[maxZoom + 1] = new KDBush(clusters, getX, getY, nodeSize, Float32Array); + + if (log) console.timeEnd(timerId); + + // cluster points on max zoom, then cluster the results on previous zoom, etc.; + // results in a cluster hierarchy across zoom levels + for (let z = maxZoom; z >= minZoom; z--) { + const now = +Date.now(); + + // create a new set of clusters for the zoom and index them with a KD-tree + clusters = this._cluster(clusters, z); + this.trees[z] = new KDBush(clusters, getX, getY, nodeSize, Float32Array); + + if (log) console.log('z%d: %d clusters in %dms', z, clusters.length, +Date.now() - now); + } + + if (log) console.timeEnd('total time'); + + return this; + } + + getClusters(bbox, zoom) { + let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180; + const minLat = Math.max(-90, Math.min(90, bbox[1])); + let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180; + const maxLat = Math.max(-90, Math.min(90, bbox[3])); + + if (bbox[2] - bbox[0] >= 360) { + minLng = -180; + maxLng = 180; + } else if (minLng > maxLng) { + const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom); + const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom); + return easternHem.concat(westernHem); + } + + const tree = this.trees[this._limitZoom(zoom)]; + const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat)); + const clusters = []; + for (const id of ids) { + const c = tree.points[id]; + clusters.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]); + } + return clusters; + } + + getChildren(clusterId) { + const originId = this._getOriginId(clusterId); + const originZoom = this._getOriginZoom(clusterId); + const errorMsg = 'No cluster with the specified id.'; + + const index = this.trees[originZoom]; + if (!index) throw new Error(errorMsg); + + const origin = index.points[originId]; + if (!origin) throw new Error(errorMsg); + + const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1)); + const ids = index.within(origin.x, origin.y, r); + const children = []; + for (const id of ids) { + const c = index.points[id]; + if (c.parentId === clusterId) { + children.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]); + } + } + + if (children.length === 0) throw new Error(errorMsg); + + return children; + } + + getLeaves(clusterId, limit, offset) { + limit = limit || 10; + offset = offset || 0; + + const leaves = []; + this._appendLeaves(leaves, clusterId, limit, offset, 0); + + return leaves; + } + + getTile(z, x, y) { + const tree = this.trees[this._limitZoom(z)]; + const z2 = Math.pow(2, z); + const {extent, radius} = this.options; + const p = radius / extent; + const top = (y - p) / z2; + const bottom = (y + 1 + p) / z2; + + const tile = { + features: [] + }; + + this._addTileFeatures( + tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom), + tree.points, x, y, z2, tile); + + if (x === 0) { + this._addTileFeatures( + tree.range(1 - p / z2, top, 1, bottom), + tree.points, z2, y, z2, tile); + } + if (x === z2 - 1) { + this._addTileFeatures( + tree.range(0, top, p / z2, bottom), + tree.points, -1, y, z2, tile); + } + + return tile.features.length ? tile : null; + } + + getClusterExpansionZoom(clusterId) { + let expansionZoom = this._getOriginZoom(clusterId) - 1; + while (expansionZoom <= this.options.maxZoom) { + const children = this.getChildren(clusterId); + expansionZoom++; + if (children.length !== 1) break; + clusterId = children[0].properties.cluster_id; + } + return expansionZoom; + } + + _appendLeaves(result, clusterId, limit, offset, skipped) { + const children = this.getChildren(clusterId); + + for (const child of children) { + const props = child.properties; + + if (props && props.cluster) { + if (skipped + props.point_count <= offset) { + // skip the whole cluster + skipped += props.point_count; + } else { + // enter the cluster + skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped); + // exit the cluster + } + } else if (skipped < offset) { + // skip a single point + skipped++; + } else { + // add a single point + result.push(child); + } + if (result.length === limit) break; + } + + return skipped; + } + + _addTileFeatures(ids, points, x, y, z2, tile) { + for (const i of ids) { + const c = points[i]; + const isCluster = c.numPoints; + + let tags, px, py; + if (isCluster) { + tags = getClusterProperties(c); + px = c.x; + py = c.y; + } else { + const p = this.points[c.index]; + tags = p.properties; + px = lngX(p.geometry.coordinates[0]); + py = latY(p.geometry.coordinates[1]); + } + + const f = { + type: 1, + geometry: [[ + Math.round(this.options.extent * (px * z2 - x)), + Math.round(this.options.extent * (py * z2 - y)) + ]], + tags + }; + + // assign id + let id; + if (isCluster) { + id = c.id; + } else if (this.options.generateId) { + // optionally generate id + id = c.index; + } else if (this.points[c.index].id) { + // keep id if already assigned + id = this.points[c.index].id; + } + + if (id !== undefined) f.id = id; + + tile.features.push(f); + } + } + + _limitZoom(z) { + return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1)); + } + + _cluster(points, zoom) { + const clusters = []; + const {radius, extent, reduce, minPoints} = this.options; + const r = radius / (extent * Math.pow(2, zoom)); + + // loop through each point + for (let i = 0; i < points.length; i++) { + const p = points[i]; + // if we've already visited the point at this zoom level, skip it + if (p.zoom <= zoom) continue; + p.zoom = zoom; + + // find all nearby points + const tree = this.trees[zoom + 1]; + const neighborIds = tree.within(p.x, p.y, r); + + const numPointsOrigin = p.numPoints || 1; + let numPoints = numPointsOrigin; + + // count the number of points in a potential cluster + for (const neighborId of neighborIds) { + const b = tree.points[neighborId]; + // filter out neighbors that are already processed + if (b.zoom > zoom) numPoints += b.numPoints || 1; + } + + // if there were neighbors to merge, and there are enough points to form a cluster + if (numPoints > numPointsOrigin && numPoints >= minPoints) { + let wx = p.x * numPointsOrigin; + let wy = p.y * numPointsOrigin; + + let clusterProperties = reduce && numPointsOrigin > 1 ? this._map(p, true) : null; + + // encode both zoom and point index on which the cluster originated -- offset by total length of features + const id = (i << 5) + (zoom + 1) + this.points.length; + + for (const neighborId of neighborIds) { + const b = tree.points[neighborId]; + + if (b.zoom <= zoom) continue; + b.zoom = zoom; // save the zoom (so it doesn't get processed twice) + + const numPoints2 = b.numPoints || 1; + wx += b.x * numPoints2; // accumulate coordinates for calculating weighted center + wy += b.y * numPoints2; + + b.parentId = id; + + if (reduce) { + if (!clusterProperties) clusterProperties = this._map(p, true); + reduce(clusterProperties, this._map(b)); + } + } + + p.parentId = id; + clusters.push(createCluster(wx / numPoints, wy / numPoints, id, numPoints, clusterProperties)); + + } else { // left points as unclustered + clusters.push(p); + + if (numPoints > 1) { + for (const neighborId of neighborIds) { + const b = tree.points[neighborId]; + if (b.zoom <= zoom) continue; + b.zoom = zoom; + clusters.push(b); + } + } + } + } + + return clusters; + } + + // get index of the point from which the cluster originated + _getOriginId(clusterId) { + return (clusterId - this.points.length) >> 5; + } + + // get zoom of the point from which the cluster originated + _getOriginZoom(clusterId) { + return (clusterId - this.points.length) % 32; + } + + _map(point, clone) { + if (point.numPoints) { + return clone ? extend({}, point.properties) : point.properties; + } + const original = this.points[point.index].properties; + const result = this.options.map(original); + return clone && result === original ? extend({}, result) : result; + } +} + +function createCluster(x, y, id, numPoints, properties) { + return { + x: fround(x), // weighted cluster center; round for consistency with Float32Array index + y: fround(y), + zoom: Infinity, // the last zoom the cluster was processed at + id, // encodes index of the first child of the cluster and its zoom level + parentId: -1, // parent cluster id + numPoints, + properties + }; +} + +function createPointCluster(p, id) { + const [x, y] = p.geometry.coordinates; + return { + x: fround(lngX(x)), // projected point coordinates + y: fround(latY(y)), + zoom: Infinity, // the last zoom the point was processed at + index: id, // index of the source feature in the original input array, + parentId: -1 // parent cluster id + }; +} + +function getClusterJSON(cluster) { + return { + type: 'Feature', + id: cluster.id, + properties: getClusterProperties(cluster), + geometry: { + type: 'Point', + coordinates: [xLng(cluster.x), yLat(cluster.y)] + } + }; +} + +function getClusterProperties(cluster) { + const count = cluster.numPoints; + const abbrev = + count >= 10000 ? `${Math.round(count / 1000) }k` : + count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count; + return extend(extend({}, cluster.properties), { + cluster: true, + cluster_id: cluster.id, + point_count: count, + point_count_abbreviated: abbrev + }); +} + +// longitude/latitude to spherical mercator in [0..1] range +function lngX(lng) { + return lng / 360 + 0.5; +} +function latY(lat) { + const sin = Math.sin(lat * Math.PI / 180); + const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI); + return y < 0 ? 0 : y > 1 ? 1 : y; +} + +// spherical mercator to longitude/latitude +function xLng(x) { + return (x - 0.5) * 360; +} +function yLat(y) { + const y2 = (180 - y * 360) * Math.PI / 180; + return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90; +} + +function extend(dest, src) { + for (const id in src) dest[id] = src[id]; + return dest; +} + +function getX(p) { + return p.x; +} +function getY(p) { + return p.y; +} diff --git a/node_modules/supercluster/package.json b/node_modules/supercluster/package.json new file mode 100644 index 0000000000000000000000000000000000000000..48fe15c67fff93efb1e6a9a74760dc7e36e5f334 --- /dev/null +++ b/node_modules/supercluster/package.json @@ -0,0 +1,54 @@ +{ + "name": "supercluster", + "version": "7.1.5", + "description": "A very fast geospatial point clustering library.", + "main": "dist/supercluster.js", + "module": "index.js", + "jsdelivr": "dist/supercluster.min.js", + "unpkg": "dist/supercluster.min.js", + "scripts": { + "pretest": "eslint index.js bench.js test/test.js demo/index.js demo/worker.js", + "test": "tape -r esm test/test.js", + "cov": "c8 npm run test", + "bench": "node --expose-gc -r esm bench.js", + "build": "mkdirp dist && rollup -c", + "prepublishOnly": "npm run test && npm run build" + }, + "files": [ + "index.js", + "dist/supercluster.js", + "dist/supercluster.min.js" + ], + "repository": { + "type": "git", + "url": "git://github.com/mapbox/supercluster.git" + }, + "keywords": [ + "clustering", + "geospatial", + "markers" + ], + "author": "Vladimir Agafonkin", + "license": "ISC", + "dependencies": { + "kdbush": "^3.0.0" + }, + "devDependencies": { + "@rollup/plugin-buble": "^0.21.3", + "@rollup/plugin-node-resolve": "^13.1.3", + "c8": "^7.11.0", + "eslint": "^8.12.0", + "eslint-config-mourner": "^3.0.0", + "esm": "^3.2.25", + "mkdirp": "^1.0.4", + "rollup": "^2.70.1", + "rollup-plugin-terser": "^7.0.2", + "tape": "^5.5.2" + }, + "eslintConfig": { + "extends": "mourner", + "rules": { + "camelcase": 0 + } + } +} diff --git a/node_modules/superscript-text/.npmignore b/node_modules/superscript-text/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..ddc9ab330c2a9e77591abb3effd1b9ebf278a988 --- /dev/null +++ b/node_modules/superscript-text/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz + +pids +logs +results + +npm-debug.log +node_modules/* +*.DS_Store \ No newline at end of file diff --git a/node_modules/superscript-text/LICENSE b/node_modules/superscript-text/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1815ddd61d61d007ca9c832c7d69ffc8a4f9f86a --- /dev/null +++ b/node_modules/superscript-text/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2015 Mikola Lysenko + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/superscript-text/README.md b/node_modules/superscript-text/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e05764e46d8a162a9f63f0b495e132fb63985b63 --- /dev/null +++ b/node_modules/superscript-text/README.md @@ -0,0 +1,35 @@ +superscript-text +================ +Converts text into super script unicode characters. + +# Example + +```javascript +var raise = require('superscript-text') + +console.log(raise('hello world')) +``` + +Output: + +``` +ʰᵉˡˡᵒ ʷᵒʳˡᵈ +``` + +# Install + +``` +npm i superscript-text +``` + +# API + +#### `require('superscript-text')(str)` +Converts `str` into unicode super script + +* `str` is a string containing english chracters and numbers + +**Returns** A super script version of `str` + +# License +(c) 2015 Mikola Lysenko. MIT License diff --git a/node_modules/superscript-text/package.json b/node_modules/superscript-text/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fb7e0f8ff04a4992653ea0feb0f0158d871629fe --- /dev/null +++ b/node_modules/superscript-text/package.json @@ -0,0 +1,26 @@ +{ + "name": "superscript-text", + "version": "1.0.0", + "description": "Converts text to superscript unicode", + "main": "superscript.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/mikolalysenko/superscript-text.git" + }, + "keywords": [ + "superscript", + "super", + "sup", + "unicode", + "ascii" + ], + "author": "Mikola Lysenko", + "license": "MIT", + "bugs": { + "url": "https://github.com/mikolalysenko/superscript-text/issues" + }, + "homepage": "https://github.com/mikolalysenko/superscript-text" +} diff --git a/node_modules/superscript-text/superscript.js b/node_modules/superscript-text/superscript.js new file mode 100644 index 0000000000000000000000000000000000000000..b794fe998331268020af9abb633a91bf942c6218 --- /dev/null +++ b/node_modules/superscript-text/superscript.js @@ -0,0 +1,53 @@ +'use strict' + +module.exports = toSuperScript + +var SUPERSCRIPTS = { + ' ': ' ', + '0': '⁰', + '1': '¹', + '2': '²', + '3': '³', + '4': '⁴', + '5': '⁵', + '6': '⁶', + '7': '⁷', + '8': '⁸', + '9': '⁹', + '+': '⁺', + '-': '⁻', + 'a': 'ᵃ', + 'b': 'ᵇ', + 'c': 'ᶜ', + 'd': 'ᵈ', + 'e': 'ᵉ', + 'f': 'ᶠ', + 'g': 'ᵍ', + 'h': 'ʰ', + 'i': 'ⁱ', + 'j': 'ʲ', + 'k': 'ᵏ', + 'l': 'ˡ', + 'm': 'ᵐ', + 'n': 'ⁿ', + 'o': 'ᵒ', + 'p': 'ᵖ', + 'r': 'ʳ', + 's': 'ˢ', + 't': 'ᵗ', + 'u': 'ᵘ', + 'v': 'ᵛ', + 'w': 'ʷ', + 'x': 'ˣ', + 'y': 'ʸ', + 'z': 'ᶻ' +} + +function toSuperScript(x) { + return x.split('').map(function(c) { + if(c in SUPERSCRIPTS) { + return SUPERSCRIPTS[c] + } + return '' + }).join('') +} diff --git a/node_modules/supports-preserve-symlinks-flag/.eslintrc b/node_modules/supports-preserve-symlinks-flag/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..346ffeca87d3784723773d39f9e52b8c6d12f8c3 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "env": { + "browser": true, + "node": true, + }, + + "rules": { + "id-length": "off", + }, +} diff --git a/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml b/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..e8d64f37e5fc43885727dc3d086050af7dcc4bb1 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/supports-preserve-symlink-flag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/supports-preserve-symlinks-flag/.nycrc b/node_modules/supports-preserve-symlinks-flag/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md b/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..61f607f4894beba4e0693c72a6446bf3497bb318 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2022-01-02 + +### Commits + +- Tests [`e2f59ad`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/e2f59ad74e2ae0f5f4899fcde6a6f693ab7cc074) +- Initial commit [`dc222aa`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/dc222aad3c0b940d8d3af1ca9937d108bd2dc4b9) +- [meta] do not publish workflow files [`5ef77f7`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/5ef77f7cb6946d16ee38672be9ec0f1bbdf63262) +- npm init [`992b068`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/992b068503a461f7e8676f40ca2aab255fd8d6ff) +- read me [`6c9afa9`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c9afa9fabc8eaf0814aaed6dd01e6df0931b76d) +- Initial implementation [`2f98925`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2f9892546396d4ab0ad9f1ff83e76c3f01234ae8) +- [meta] add `auto-changelog` [`6c476ae`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/6c476ae1ed7ce68b0480344f090ac2844f35509d) +- [Dev Deps] add `eslint`, `@ljharb/eslint-config` [`d0fffc8`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/d0fffc886d25fba119355520750a909d64da0087) +- Only apps should have lockfiles [`ab318ed`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/ab318ed7ae62f6c2c0e80a50398d40912afd8f69) +- [meta] add `safe-publish-latest` [`2bb23b3`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/2bb23b3ebab02dc4135c4cdf0217db82835b9fca) +- [meta] add `sideEffects` flag [`600223b`](https://github.com/inspect-js/node-supports-preserve-symlinks-flag/commit/600223ba24f30779f209d9097721eff35ed62741) diff --git a/node_modules/supports-preserve-symlinks-flag/LICENSE b/node_modules/supports-preserve-symlinks-flag/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2e7b9a3eacf263cb418f4c16b087290ef78c39b2 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/supports-preserve-symlinks-flag/README.md b/node_modules/supports-preserve-symlinks-flag/README.md new file mode 100644 index 0000000000000000000000000000000000000000..eb05b124ca68ba0312c98834f282a2cd6ce568b5 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/README.md @@ -0,0 +1,42 @@ +# node-supports-preserve-symlinks-flag [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Determine if the current node version supports the `--preserve-symlinks` flag. + +## Example + +```js +var supportsPreserveSymlinks = require('node-supports-preserve-symlinks-flag'); +var assert = require('assert'); + +assert.equal(supportsPreserveSymlinks, null); // in a browser +assert.equal(supportsPreserveSymlinks, false); // in node < v6.2 +assert.equal(supportsPreserveSymlinks, true); // in node v6.2+ +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/node-supports-preserve-symlinks-flag +[npm-version-svg]: https://versionbadg.es/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag.svg +[deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag +[dev-deps-svg]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/node-supports-preserve-symlinks-flag#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/node-supports-preserve-symlinks-flag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/node-supports-preserve-symlinks-flag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/node-supports-preserve-symlinks-flag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=node-supports-preserve-symlinks-flag +[codecov-image]: https://codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/node-supports-preserve-symlinks-flag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/node-supports-preserve-symlinks-flag +[actions-url]: https://github.com/inspect-js/node-supports-preserve-symlinks-flag/actions diff --git a/node_modules/supports-preserve-symlinks-flag/browser.js b/node_modules/supports-preserve-symlinks-flag/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..087be1fe9fda8930ca66a68204bd0112b9d8710b --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/browser.js @@ -0,0 +1,3 @@ +'use strict'; + +module.exports = null; diff --git a/node_modules/supports-preserve-symlinks-flag/index.js b/node_modules/supports-preserve-symlinks-flag/index.js new file mode 100644 index 0000000000000000000000000000000000000000..86fd5d331c4a4d44e9a92d46fbb637165cea78d5 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/index.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = ( +// node 12+ + process.allowedNodeEnvironmentFlags && process.allowedNodeEnvironmentFlags.has('--preserve-symlinks') +) || ( +// node v6.2 - v11 + String(module.constructor._findPath).indexOf('preserveSymlinks') >= 0 // eslint-disable-line no-underscore-dangle +); diff --git a/node_modules/supports-preserve-symlinks-flag/package.json b/node_modules/supports-preserve-symlinks-flag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..56edadcaad850fa1f348aeb0988e98d16eb14a84 --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/package.json @@ -0,0 +1,70 @@ +{ + "name": "supports-preserve-symlinks-flag", + "version": "1.0.0", + "description": "Determine if the current node version supports the `--preserve-symlinks` flag.", + "main": "./index.js", + "browser": "./browser.js", + "exports": { + ".": [ + { + "browser": "./browser.js", + "default": "./index.js" + }, + "./index.js" + ], + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/node-supports-preserve-symlinks-flag.git" + }, + "keywords": [ + "node", + "flag", + "symlink", + "symlinks", + "preserve-symlinks" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag/issues" + }, + "homepage": "https://github.com/inspect-js/node-supports-preserve-symlinks-flag#readme", + "devDependencies": { + "@ljharb/eslint-config": "^20.1.0", + "aud": "^1.1.5", + "auto-changelog": "^2.3.0", + "eslint": "^8.6.0", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "semver": "^6.3.0", + "tape": "^5.4.0" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/supports-preserve-symlinks-flag/test/index.js b/node_modules/supports-preserve-symlinks-flag/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..9938d671691790a75bacefc6100b39d6e4ab937a --- /dev/null +++ b/node_modules/supports-preserve-symlinks-flag/test/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); +var semver = require('semver'); + +var supportsPreserveSymlinks = require('../'); +var browser = require('../browser'); + +test('supportsPreserveSymlinks', function (t) { + t.equal(typeof supportsPreserveSymlinks, 'boolean', 'is a boolean'); + + t.equal(browser, null, 'browser file is `null`'); + t.equal( + supportsPreserveSymlinks, + null, + 'in a browser, is null', + { skip: typeof window === 'undefined' } + ); + + var expected = semver.satisfies(process.version, '>= 6.2'); + t.equal( + supportsPreserveSymlinks, + expected, + 'is true in node v6.2+, false otherwise (actual: ' + supportsPreserveSymlinks + ', expected ' + expected + ')', + { skip: typeof window !== 'undefined' } + ); + + t.end(); +}); diff --git a/node_modules/svg-arc-to-cubic-bezier/LICENSE.md b/node_modules/svg-arc-to-cubic-bezier/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..6e59fa5a817cc1ae3e3aff73b2cc63fdb8175905 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/LICENSE.md @@ -0,0 +1,16 @@ +Internet Systems Consortium license +=================================== + +Copyright (c) `2017`, `Colin Meinke` + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/svg-arc-to-cubic-bezier/README.md b/node_modules/svg-arc-to-cubic-bezier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f4d8f8192d17bce665d547a9ae6ac498b22b30d1 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/README.md @@ -0,0 +1,75 @@ +# SVG arc to cubic bezier + +A function that takes an SVG arc curve as input, and maps it to +one or more cubic bezier curves. + +I extracted the `a2c` function from +[SVG path](https://github.com/fontello/svgpath), as I wanted to use it on its own. + +All credit, thanks and respect goes to: + +- Sergey Batishchev – [@snb2013](https://github.com/snb2013) +- Vitaly Puzrin – [@puzrin](https://github.com/puzrin) +- Alex Kocharin – [@rlidwka](https://github.com/rlidwka) + +It blew my mind. Thank you! + +## Installation + +``` +npm install svg-arc-to-cubic-bezier +``` + +## Usage + +```js +import arcToBezier from 'svg-arc-to-cubic-bezier'; + +const previousPoint = { x: 100, y: 100 } + +const currentPoint = { + x: 700, + y: 100, + curve: { + type: 'arc', + rx: 300, + ry: 200, + largeArcFlag: 30, + sweepFlag: 0, + xAxisRotation: 0, + }, +}; + +const curves = arcToBezier({ + px: previousPoint.x, + py: previousPoint.y, + cx: currentPoint.x, + cy: currentPoint.y, + rx: currentPoint.curve.rx, + ry: currentPoint.curve.ry, + xAxisRotation: currentPoint.curve.xAxisRotation, + largeArcFlag: currentPoint.curve.largeArcFlag, + sweepFlag: currentPoint.curve.sweepFlag, +}); + +curves.forEach( c => console.log( c )); + +// [ +// { +// x1: 159.7865795437111, +// y1: 244.97474575043722, +// x2: 342.5677510865157, +// y2: 362.49999701503634, +// x: 508.253174689854, +// y: 362.4999967447917, +// }, +// { +// x1: 673.9385982931924, +// y1: 362.49999647454695, +// x2: 759.7865756485664, +// y2: 244.97474477179443, +// x: 699.9999995964145, +// y: 99.99999902135724, +// }, +// ] +``` diff --git a/node_modules/svg-arc-to-cubic-bezier/cjs/index.js b/node_modules/svg-arc-to-cubic-bezier/cjs/index.js new file mode 100644 index 0000000000000000000000000000000000000000..11bcabc67c03cca97f9c8f108d9d6ed0bf6e0f13 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/cjs/index.js @@ -0,0 +1,190 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + +var TAU = Math.PI * 2; + +var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) { + var x = _ref.x, + y = _ref.y; + + x *= rx; + y *= ry; + + var xp = cosphi * x - sinphi * y; + var yp = sinphi * x + cosphi * y; + + return { + x: xp + centerx, + y: yp + centery + }; +}; + +var approxUnitArc = function approxUnitArc(ang1, ang2) { + // If 90 degree circular arc, use a constant + // as derived from http://spencermortensen.com/articles/bezier-circle + var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); + + var x1 = Math.cos(ang1); + var y1 = Math.sin(ang1); + var x2 = Math.cos(ang1 + ang2); + var y2 = Math.sin(ang1 + ang2); + + return [{ + x: x1 - y1 * a, + y: y1 + x1 * a + }, { + x: x2 + y2 * a, + y: y2 - x2 * a + }, { + x: x2, + y: y2 + }]; +}; + +var vectorAngle = function vectorAngle(ux, uy, vx, vy) { + var sign = ux * vy - uy * vx < 0 ? -1 : 1; + + var dot = ux * vx + uy * vy; + + if (dot > 1) { + dot = 1; + } + + if (dot < -1) { + dot = -1; + } + + return sign * Math.acos(dot); +}; + +var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { + var rxsq = Math.pow(rx, 2); + var rysq = Math.pow(ry, 2); + var pxpsq = Math.pow(pxp, 2); + var pypsq = Math.pow(pyp, 2); + + var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; + + if (radicant < 0) { + radicant = 0; + } + + radicant /= rxsq * pypsq + rysq * pxpsq; + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + + var centerxp = radicant * rx / ry * pyp; + var centeryp = radicant * -ry / rx * pxp; + + var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; + var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + + var vx1 = (pxp - centerxp) / rx; + var vy1 = (pyp - centeryp) / ry; + var vx2 = (-pxp - centerxp) / rx; + var vy2 = (-pyp - centeryp) / ry; + + var ang1 = vectorAngle(1, 0, vx1, vy1); + var ang2 = vectorAngle(vx1, vy1, vx2, vy2); + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU; + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU; + } + + return [centerx, centery, ang1, ang2]; +}; + +var arcToBezier = function arcToBezier(_ref2) { + var px = _ref2.px, + py = _ref2.py, + cx = _ref2.cx, + cy = _ref2.cy, + rx = _ref2.rx, + ry = _ref2.ry, + _ref2$xAxisRotation = _ref2.xAxisRotation, + xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation, + _ref2$largeArcFlag = _ref2.largeArcFlag, + largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag, + _ref2$sweepFlag = _ref2.sweepFlag, + sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag; + + var curves = []; + + if (rx === 0 || ry === 0) { + return []; + } + + var sinphi = Math.sin(xAxisRotation * TAU / 360); + var cosphi = Math.cos(xAxisRotation * TAU / 360); + + var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2; + var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2; + + if (pxp === 0 && pyp === 0) { + return []; + } + + rx = Math.abs(rx); + ry = Math.abs(ry); + + var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + + var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), + _getArcCenter2 = _slicedToArray(_getArcCenter, 4), + centerx = _getArcCenter2[0], + centery = _getArcCenter2[1], + ang1 = _getArcCenter2[2], + ang2 = _getArcCenter2[3]; + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + + + var ratio = Math.abs(ang2) / (TAU / 4); + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0; + } + + var segments = Math.max(Math.ceil(ratio), 1); + + ang2 /= segments; + + for (var i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)); + ang1 += ang2; + } + + return curves.map(function (curve) { + var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), + x1 = _mapToEllipse.x, + y1 = _mapToEllipse.y; + + var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), + x2 = _mapToEllipse2.x, + y2 = _mapToEllipse2.y; + + var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), + x = _mapToEllipse3.x, + y = _mapToEllipse3.y; + + return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; + }); +}; + +exports.default = arcToBezier; +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/svg-arc-to-cubic-bezier/dist/svg-points-to-cubic-bezier.js b/node_modules/svg-arc-to-cubic-bezier/dist/svg-points-to-cubic-bezier.js new file mode 100644 index 0000000000000000000000000000000000000000..84da0686a1f305d93919a8aa13ee01f7583e4856 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/dist/svg-points-to-cubic-bezier.js @@ -0,0 +1,191 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = global || self, global.SVGArcToCubicBezier = factory()); +}(this, function () { 'use strict'; + + var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); + + var TAU = Math.PI * 2; + + var mapToEllipse = function mapToEllipse(_ref, rx, ry, cosphi, sinphi, centerx, centery) { + var x = _ref.x, + y = _ref.y; + + x *= rx; + y *= ry; + + var xp = cosphi * x - sinphi * y; + var yp = sinphi * x + cosphi * y; + + return { + x: xp + centerx, + y: yp + centery + }; + }; + + var approxUnitArc = function approxUnitArc(ang1, ang2) { + // If 90 degree circular arc, use a constant + // as derived from http://spencermortensen.com/articles/bezier-circle + var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); + + var x1 = Math.cos(ang1); + var y1 = Math.sin(ang1); + var x2 = Math.cos(ang1 + ang2); + var y2 = Math.sin(ang1 + ang2); + + return [{ + x: x1 - y1 * a, + y: y1 + x1 * a + }, { + x: x2 + y2 * a, + y: y2 - x2 * a + }, { + x: x2, + y: y2 + }]; + }; + + var vectorAngle = function vectorAngle(ux, uy, vx, vy) { + var sign = ux * vy - uy * vx < 0 ? -1 : 1; + + var dot = ux * vx + uy * vy; + + if (dot > 1) { + dot = 1; + } + + if (dot < -1) { + dot = -1; + } + + return sign * Math.acos(dot); + }; + + var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { + var rxsq = Math.pow(rx, 2); + var rysq = Math.pow(ry, 2); + var pxpsq = Math.pow(pxp, 2); + var pypsq = Math.pow(pyp, 2); + + var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; + + if (radicant < 0) { + radicant = 0; + } + + radicant /= rxsq * pypsq + rysq * pxpsq; + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + + var centerxp = radicant * rx / ry * pyp; + var centeryp = radicant * -ry / rx * pxp; + + var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; + var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + + var vx1 = (pxp - centerxp) / rx; + var vy1 = (pyp - centeryp) / ry; + var vx2 = (-pxp - centerxp) / rx; + var vy2 = (-pyp - centeryp) / ry; + + var ang1 = vectorAngle(1, 0, vx1, vy1); + var ang2 = vectorAngle(vx1, vy1, vx2, vy2); + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU; + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU; + } + + return [centerx, centery, ang1, ang2]; + }; + + var arcToBezier = function arcToBezier(_ref2) { + var px = _ref2.px, + py = _ref2.py, + cx = _ref2.cx, + cy = _ref2.cy, + rx = _ref2.rx, + ry = _ref2.ry, + _ref2$xAxisRotation = _ref2.xAxisRotation, + xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation, + _ref2$largeArcFlag = _ref2.largeArcFlag, + largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag, + _ref2$sweepFlag = _ref2.sweepFlag, + sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag; + + var curves = []; + + if (rx === 0 || ry === 0) { + return []; + } + + var sinphi = Math.sin(xAxisRotation * TAU / 360); + var cosphi = Math.cos(xAxisRotation * TAU / 360); + + var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2; + var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2; + + if (pxp === 0 && pyp === 0) { + return []; + } + + rx = Math.abs(rx); + ry = Math.abs(ry); + + var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + + var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), + _getArcCenter2 = _slicedToArray(_getArcCenter, 4), + centerx = _getArcCenter2[0], + centery = _getArcCenter2[1], + ang1 = _getArcCenter2[2], + ang2 = _getArcCenter2[3]; + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + + + var ratio = Math.abs(ang2) / (TAU / 4); + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0; + } + + var segments = Math.max(Math.ceil(ratio), 1); + + ang2 /= segments; + + for (var i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)); + ang1 += ang2; + } + + return curves.map(function (curve) { + var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), + x1 = _mapToEllipse.x, + y1 = _mapToEllipse.y; + + var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), + x2 = _mapToEllipse2.x, + y2 = _mapToEllipse2.y; + + var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), + x = _mapToEllipse3.x, + y = _mapToEllipse3.y; + + return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; + }); + }; + + return arcToBezier; + +})); diff --git a/node_modules/svg-arc-to-cubic-bezier/dist/svg-points-to-cubic-bezier.min.js b/node_modules/svg-arc-to-cubic-bezier/dist/svg-points-to-cubic-bezier.min.js new file mode 100644 index 0000000000000000000000000000000000000000..2f2b289b44138b9f5c503d4deec3d6b04aa5b5d6 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/dist/svg-points-to-cubic-bezier.min.js @@ -0,0 +1 @@ +!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(t=t||self).SVGArcToCubicBezier=r()}(this,function(){"use strict";function O(t,r,a,n,e,o,i){var h=t.x,u=t.y;return{x:n*(h*=r)-e*(u*=a)+o,y:e*h+n*u+i}}function P(t,r,a,n){var e=t*a+r*n;return 1 1) { + dot = 1; + } + + if (dot < -1) { + dot = -1; + } + + return sign * Math.acos(dot); +}; + +var getArcCenter = function getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { + var rxsq = Math.pow(rx, 2); + var rysq = Math.pow(ry, 2); + var pxpsq = Math.pow(pxp, 2); + var pypsq = Math.pow(pyp, 2); + + var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; + + if (radicant < 0) { + radicant = 0; + } + + radicant /= rxsq * pypsq + rysq * pxpsq; + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + + var centerxp = radicant * rx / ry * pyp; + var centeryp = radicant * -ry / rx * pxp; + + var centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2; + var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + + var vx1 = (pxp - centerxp) / rx; + var vy1 = (pyp - centeryp) / ry; + var vx2 = (-pxp - centerxp) / rx; + var vy2 = (-pyp - centeryp) / ry; + + var ang1 = vectorAngle(1, 0, vx1, vy1); + var ang2 = vectorAngle(vx1, vy1, vx2, vy2); + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU; + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU; + } + + return [centerx, centery, ang1, ang2]; +}; + +var arcToBezier = function arcToBezier(_ref2) { + var px = _ref2.px, + py = _ref2.py, + cx = _ref2.cx, + cy = _ref2.cy, + rx = _ref2.rx, + ry = _ref2.ry, + _ref2$xAxisRotation = _ref2.xAxisRotation, + xAxisRotation = _ref2$xAxisRotation === undefined ? 0 : _ref2$xAxisRotation, + _ref2$largeArcFlag = _ref2.largeArcFlag, + largeArcFlag = _ref2$largeArcFlag === undefined ? 0 : _ref2$largeArcFlag, + _ref2$sweepFlag = _ref2.sweepFlag, + sweepFlag = _ref2$sweepFlag === undefined ? 0 : _ref2$sweepFlag; + + var curves = []; + + if (rx === 0 || ry === 0) { + return []; + } + + var sinphi = Math.sin(xAxisRotation * TAU / 360); + var cosphi = Math.cos(xAxisRotation * TAU / 360); + + var pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2; + var pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2; + + if (pxp === 0 && pyp === 0) { + return []; + } + + rx = Math.abs(rx); + ry = Math.abs(ry); + + var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + + var _getArcCenter = getArcCenter(px, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), + _getArcCenter2 = _slicedToArray(_getArcCenter, 4), + centerx = _getArcCenter2[0], + centery = _getArcCenter2[1], + ang1 = _getArcCenter2[2], + ang2 = _getArcCenter2[3]; + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + + + var ratio = Math.abs(ang2) / (TAU / 4); + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0; + } + + var segments = Math.max(Math.ceil(ratio), 1); + + ang2 /= segments; + + for (var i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)); + ang1 += ang2; + } + + return curves.map(function (curve) { + var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), + x1 = _mapToEllipse.x, + y1 = _mapToEllipse.y; + + var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), + x2 = _mapToEllipse2.x, + y2 = _mapToEllipse2.y; + + var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), + x = _mapToEllipse3.x, + y = _mapToEllipse3.y; + + return { x1: x1, y1: y1, x2: x2, y2: y2, x: x, y: y }; + }); +}; + +export default arcToBezier; \ No newline at end of file diff --git a/node_modules/svg-arc-to-cubic-bezier/package.json b/node_modules/svg-arc-to-cubic-bezier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..dfe75de54df748d5422645f087d6a5171f8c62b4 --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/package.json @@ -0,0 +1,106 @@ +{ + "author": { + "name": "Colin Meinke", + "email": "hello@colinmeinke.com", + "url": "https://colinmeinke.com" + }, + "babel": { + "env": { + "cjs": { + "plugins": [ + "transform-object-rest-spread", + "add-module-exports" + ], + "presets": [ + "es2015" + ] + }, + "modules": { + "plugins": [ + "transform-object-rest-spread" + ], + "presets": [ + [ + "es2015", + { + "modules": false + } + ] + ] + }, + "umd": { + "plugins": [ + "transform-object-rest-spread" + ], + "presets": [ + [ + "es2015", + { + "modules": false + } + ] + ] + } + } + }, + "bugs": { + "url": "https://github.com/colinmeinke/svg-arc-to-cubic-bezier/issues" + }, + "config": { + "commitizen": { + "path": "node_modules/cz-conventional-changelog" + } + }, + "description": "A function that takes an SVG arc curve as input, and maps it to one or more cubic bezier curves", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-core": "^6.26.3", + "babel-plugin-add-module-exports": "^0.3.3", + "babel-plugin-transform-object-rest-spread": "^6.26.0", + "babel-preset-es2015": "^6.24.1", + "commitizen": "^3.1.1", + "cz-conventional-changelog": "^2.1.0", + "rimraf": "^2.6.3", + "rollup": "^1.16.6", + "rollup-plugin-babel": "^3.0.7", + "rollup-plugin-commonjs": "^10.0.1", + "rollup-plugin-uglify": "^6.0.2", + "snazzy": "^8.0.0", + "standard": "^12.0.1", + "travis-deploy-once": "^5.0.11", + "semantic-release": "^15.13.18" + }, + "keywords": [ + "arc", + "bezier", + "convert", + "cubic", + "curve", + "path", + "svg" + ], + "license": "ISC", + "main": "cjs/index.js", + "module": "modules/index.js", + "name": "svg-arc-to-cubic-bezier", + "repository": { + "type": "git", + "url": "https://github.com/colinmeinke/svg-arc-to-cubic-bezier" + }, + "scripts": { + "build": "npm run build:modules && npm run build:cjs && npm run build:umd", + "build:cjs": "BABEL_ENV=cjs babel src --out-dir cjs", + "build:modules": "BABEL_ENV=modules babel src --out-dir modules", + "build:umd": "npm run build:umd:dev && npm run build:umd:pro", + "build:umd:dev": "BABEL_ENV=umd rollup -c", + "build:umd:pro": "NODE_ENV=production BABEL_ENV=umd rollup -c", + "commit": "git-cz", + "fix": "standard --fix", + "lint": "standard --verbose | snazzy", + "prepublish": "npm run tidy && npm run build", + "semantic-release": "semantic-release", + "tidy": "rimraf modules cjs dist", + "travis-deploy-once": "travis-deploy-once" + }, + "version": "3.2.0" +} diff --git a/node_modules/svg-arc-to-cubic-bezier/src/index.js b/node_modules/svg-arc-to-cubic-bezier/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fb3219838ecf0ad211a2dde8b1ced51a165e83fa --- /dev/null +++ b/node_modules/svg-arc-to-cubic-bezier/src/index.js @@ -0,0 +1,196 @@ +const TAU = Math.PI * 2 + +const mapToEllipse = ({ x, y }, rx, ry, cosphi, sinphi, centerx, centery) => { + x *= rx + y *= ry + + const xp = cosphi * x - sinphi * y + const yp = sinphi * x + cosphi * y + + return { + x: xp + centerx, + y: yp + centery + } +} + +const approxUnitArc = (ang1, ang2) => { + // If 90 degree circular arc, use a constant + // as derived from http://spencermortensen.com/articles/bezier-circle + const a = ang2 === 1.5707963267948966 + ? 0.551915024494 + : ang2 === -1.5707963267948966 + ? -0.551915024494 + : 4 / 3 * Math.tan(ang2 / 4) + + const x1 = Math.cos(ang1) + const y1 = Math.sin(ang1) + const x2 = Math.cos(ang1 + ang2) + const y2 = Math.sin(ang1 + ang2) + + return [ + { + x: x1 - y1 * a, + y: y1 + x1 * a + }, + { + x: x2 + y2 * a, + y: y2 - x2 * a + }, + { + x: x2, + y: y2 + } + ] +} + +const vectorAngle = (ux, uy, vx, vy) => { + const sign = (ux * vy - uy * vx < 0) ? -1 : 1 + + let dot = ux * vx + uy * vy + + if (dot > 1) { + dot = 1 + } + + if (dot < -1) { + dot = -1 + } + + return sign * Math.acos(dot) +} + +const getArcCenter = ( + px, + py, + cx, + cy, + rx, + ry, + largeArcFlag, + sweepFlag, + sinphi, + cosphi, + pxp, + pyp +) => { + const rxsq = Math.pow(rx, 2) + const rysq = Math.pow(ry, 2) + const pxpsq = Math.pow(pxp, 2) + const pypsq = Math.pow(pyp, 2) + + let radicant = (rxsq * rysq) - (rxsq * pypsq) - (rysq * pxpsq) + + if (radicant < 0) { + radicant = 0 + } + + radicant /= (rxsq * pypsq) + (rysq * pxpsq) + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1) + + const centerxp = radicant * rx / ry * pyp + const centeryp = radicant * -ry / rx * pxp + + const centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2 + const centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2 + + const vx1 = (pxp - centerxp) / rx + const vy1 = (pyp - centeryp) / ry + const vx2 = (-pxp - centerxp) / rx + const vy2 = (-pyp - centeryp) / ry + + let ang1 = vectorAngle(1, 0, vx1, vy1) + let ang2 = vectorAngle(vx1, vy1, vx2, vy2) + + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU + } + + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU + } + + return [ centerx, centery, ang1, ang2 ] +} + +const arcToBezier = ({ + px, + py, + cx, + cy, + rx, + ry, + xAxisRotation = 0, + largeArcFlag = 0, + sweepFlag = 0 +}) => { + const curves = [] + + if (rx === 0 || ry === 0) { + return [] + } + + const sinphi = Math.sin(xAxisRotation * TAU / 360) + const cosphi = Math.cos(xAxisRotation * TAU / 360) + + const pxp = cosphi * (px - cx) / 2 + sinphi * (py - cy) / 2 + const pyp = -sinphi * (px - cx) / 2 + cosphi * (py - cy) / 2 + + if (pxp === 0 && pyp === 0) { + return [] + } + + rx = Math.abs(rx) + ry = Math.abs(ry) + + const lambda = + Math.pow(pxp, 2) / Math.pow(rx, 2) + + Math.pow(pyp, 2) / Math.pow(ry, 2) + + if (lambda > 1) { + rx *= Math.sqrt(lambda) + ry *= Math.sqrt(lambda) + } + + let [ centerx, centery, ang1, ang2 ] = getArcCenter( + px, + py, + cx, + cy, + rx, + ry, + largeArcFlag, + sweepFlag, + sinphi, + cosphi, + pxp, + pyp + ) + + // If 'ang2' == 90.0000000001, then `ratio` will evaluate to + // 1.0000000001. This causes `segments` to be greater than one, which is an + // unecessary split, and adds extra points to the bezier curve. To alleviate + // this issue, we round to 1.0 when the ratio is close to 1.0. + let ratio = Math.abs(ang2) / (TAU / 4) + if (Math.abs(1.0 - ratio) < 0.0000001) { + ratio = 1.0 + } + + const segments = Math.max(Math.ceil(ratio), 1) + + ang2 /= segments + + for (let i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)) + ang1 += ang2 + } + + return curves.map(curve => { + const { x: x1, y: y1 } = mapToEllipse(curve[ 0 ], rx, ry, cosphi, sinphi, centerx, centery) + const { x: x2, y: y2 } = mapToEllipse(curve[ 1 ], rx, ry, cosphi, sinphi, centerx, centery) + const { x, y } = mapToEllipse(curve[ 2 ], rx, ry, cosphi, sinphi, centerx, centery) + + return { x1, y1, x2, y2, x, y } + }) +} + +export default arcToBezier diff --git a/node_modules/svg-path-bounds/.eslintrc.json b/node_modules/svg-path-bounds/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..ab87b064922bb21099f463bcafc37585340c3b2b --- /dev/null +++ b/node_modules/svg-path-bounds/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/svg-path-bounds/.travis.yml b/node_modules/svg-path-bounds/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..5c9d7639deea633616d4153ec32190d5c542308b --- /dev/null +++ b/node_modules/svg-path-bounds/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "6" diff --git a/node_modules/svg-path-bounds/index.js b/node_modules/svg-path-bounds/index.js new file mode 100644 index 0000000000000000000000000000000000000000..93843e721485a4df5b57b664ccc54ea964e3ee30 --- /dev/null +++ b/node_modules/svg-path-bounds/index.js @@ -0,0 +1,42 @@ +'use strict' + +var parse = require('parse-svg-path') +var abs = require('abs-svg-path') +var normalize = require('normalize-svg-path') +var isSvgPath = require('is-svg-path') + +module.exports = pathBounds + + +function pathBounds(path) { + // ES6 string tpl call + if (Array.isArray(path) && path.length === 1 && typeof path[0] === 'string') path = path[0] + + // svg path string + if (typeof path === 'string') { + if (!isSvgPath(path)) throw Error('String is not an SVG path.') + path = parse(path) + } + + if (!Array.isArray(path)) throw Error('Argument should be a string or an array of path segments.') + + path = abs(path) + path = normalize(path) + + if (!path.length) return [0, 0, 0, 0] + + var bounds = [Infinity, Infinity, -Infinity, -Infinity] + + for (var i = 0, l = path.length; i < l; i++) { + var points = path[i].slice(1) + + for (var j = 0; j < points.length; j += 2) { + if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0] + if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1] + if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0] + if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1] + } + } + + return bounds +} diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/.eslintrc.json b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..ab87b064922bb21099f463bcafc37585340c3b2b --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/.travis.yml b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..a756a652361a41d0d5adbcfabca45066a78065e5 --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "stable" diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/Readme.md b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..b67cd77188dbe37aa8ff62d211e239b32d768ee4 --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/Readme.md @@ -0,0 +1,26 @@ +# normalize-svg-path [![build](https://travis-ci.org/jkroso/normalize-svg-path.svg?branch=master)](https://travis-ci.org/jkroso/normalize-svg-path) + + + Convert all segments in a path to curves. Usefull if you intend to animate one shape to another. By defining all segments with curves instead of a mix of lines, arcs, and curves tweening becomes much simpler. It could also help you rewrite your SVG code according to the principles of [narcissistic design](//vimeo.com/77199361). + +## Usage + +[![npm install normalize-svg-path](https://nodei.co/npm/normalize-svg-path.png?mini=true)](https://npmjs.org/package/normalize-svg-path/) + +```js +var parse = require('parse-svg-path') +var abs = require('abs-svg-path') +var normalize = require('normalize-svg-path') + +var segments = normalize(abs(parse('M0 0L10 10A10 10 0 0 0 20 20Z'))) +``` + +## API + +### normalize(path) + + Translate each segment in `path` to an equivalent cubic bézier curve. The input `path` must be [absolute](//github.com/jkroso/abs-svg-path). + +```js +normalize([['L',1,2]]) // => [['C',0,0,1,2,1,2]] +``` diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.js b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ed286c9d9fe9ca95837333e2040a1287a15466f1 --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.js @@ -0,0 +1,122 @@ +'use strict' + +module.exports = normalize + +var arcToCurve = require('svg-arc-to-cubic-bezier') + +function normalize(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 + + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] + + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + var curves = arcToCurve({ + px: x, + py: y, + cx: seg[6], + cy: seg[7], + rx: seg[1], + ry: seg[2], + xAxisRotation: seg[3], + largeArcFlag: seg[4], + sweepFlag: seg[5] + }) + + // null-curves + if (!curves.length) continue + + for (var j = 0, c; j < curves.length; j++) { + c = curves[j] + seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y] + if (j < curves.length - 1) result.push(seg) + } + + break + case 'S': + // default control point + var cx = x + var cy = y + if (prev == 'C' || prev == 'S') { + cx += cx - bezierX // reflect the previous command's control + cy += cy - bezierY // point relative to the current point + } + seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]] + break + case 'T': + if (prev == 'Q' || prev == 'T') { + quadX = x * 2 - quadX // as with 'S' reflect previous control point + quadY = y * 2 - quadY + } else { + quadX = x + quadY = y + } + seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]) + break + case 'Q': + quadX = seg[1] + quadY = seg[2] + seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]) + break + case 'L': + seg = line(x, y, seg[1], seg[2]) + break + case 'H': + seg = line(x, y, seg[1], y) + break + case 'V': + seg = line(x, y, x, seg[1]) + break + case 'Z': + seg = line(x, y, startX, startY) + break + } + + // update state + prev = command + x = seg[seg.length - 2] + y = seg[seg.length - 1] + if (seg.length > 4) { + bezierX = seg[seg.length - 4] + bezierY = seg[seg.length - 3] + } else { + bezierX = x + bezierY = y + } + result.push(seg) + } + + return result +} + +function line(x1, y1, x2, y2){ + return ['C', x1, y1, x2, y2, x2, y2] +} + +function quadratic(x1, y1, cx, cy, x2, y2){ + return [ + 'C', + x1/3 + (2/3) * cx, + y1/3 + (2/3) * cy, + x2/3 + (2/3) * cx, + y2/3 + (2/3) * cy, + x2, + y2 + ] +} diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.mjs b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1cc05572ec9262be8688941126f064b319fc9afc --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/index.mjs @@ -0,0 +1,118 @@ +import arcToCurve from 'svg-arc-to-cubic-bezier' + +export default function normalize(path){ + // init state + var prev + var result = [] + var bezierX = 0 + var bezierY = 0 + var startX = 0 + var startY = 0 + var quadX = null + var quadY = null + var x = 0 + var y = 0 + + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i] + var command = seg[0] + + switch (command) { + case 'M': + startX = seg[1] + startY = seg[2] + break + case 'A': + var curves = arcToCurve({ + px: x, + py: y, + cx: seg[6], + cy: seg[7], + rx: seg[1], + ry: seg[2], + xAxisRotation: seg[3], + largeArcFlag: seg[4], + sweepFlag: seg[5] + }) + + // null-curves + if (!curves.length) continue + + for (var j = 0, c; j < curves.length; j++) { + c = curves[j] + seg = ['C', c.x1, c.y1, c.x2, c.y2, c.x, c.y] + if (j < curves.length - 1) result.push(seg) + } + + break + case 'S': + // default control point + var cx = x + var cy = y + if (prev == 'C' || prev == 'S') { + cx += cx - bezierX // reflect the previous command's control + cy += cy - bezierY // point relative to the current point + } + seg = ['C', cx, cy, seg[1], seg[2], seg[3], seg[4]] + break + case 'T': + if (prev == 'Q' || prev == 'T') { + quadX = x * 2 - quadX // as with 'S' reflect previous control point + quadY = y * 2 - quadY + } else { + quadX = x + quadY = y + } + seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]) + break + case 'Q': + quadX = seg[1] + quadY = seg[2] + seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]) + break + case 'L': + seg = line(x, y, seg[1], seg[2]) + break + case 'H': + seg = line(x, y, seg[1], y) + break + case 'V': + seg = line(x, y, x, seg[1]) + break + case 'Z': + seg = line(x, y, startX, startY) + break + } + + // update state + prev = command + x = seg[seg.length - 2] + y = seg[seg.length - 1] + if (seg.length > 4) { + bezierX = seg[seg.length - 4] + bezierY = seg[seg.length - 3] + } else { + bezierX = x + bezierY = y + } + result.push(seg) + } + + return result +} + +function line(x1, y1, x2, y2){ + return ['C', x1, y1, x2, y2, x2, y2] +} + +function quadratic(x1, y1, cx, cy, x2, y2){ + return [ + 'C', + x1/3 + (2/3) * cx, + y1/3 + (2/3) * cy, + x2/3 + (2/3) * cx, + y2/3 + (2/3) * cy, + x2, + y2 + ] +} diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/license.md b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/license.md new file mode 100644 index 0000000000000000000000000000000000000000..ea89a3fe185be3e7ee258390197cec1651971fc6 --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/license.md @@ -0,0 +1,25 @@ + +The MIT License + +Copyright © 2008-2013 Dmitry Baranovskiy (http://raphaeljs.com) +Copyright © 2008-2013 Sencha Labs (http://sencha.com) +Copyright © 2013 Jake Rosoman + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/package.json b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a4ee350f94987ade5352c69533ba53bf662f51b5 --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/package.json @@ -0,0 +1,30 @@ +{ + "name": "normalize-svg-path", + "version": "1.1.0", + "description": "Convert all segments in a path to curves", + "keywords": [ + "svg", + "path", + "normalize" + ], + "module": "./index.mjs", + "main": "./index.js", + "exports": { + "require": "./index.js", + "import": "./index.mjs" + }, + "dependencies": { + "svg-arc-to-cubic-bezier": "^3.0.0" + }, + "devDependencies": { + "parse-svg-path": "^0.1.2", + "tape": "^4.7.0" + }, + "scripts": { + "test": "node test.mjs" + }, + "repository": "git://github.com/jkroso/normalize-svg-path.git", + "bugs": "https://github.com/jkroso/normalize-svg-path/issues", + "author": "Jake Rosoman", + "license": "MIT" +} diff --git a/node_modules/svg-path-bounds/node_modules/normalize-svg-path/test.mjs b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e9f862414d35743394be349e52ce1c7e6a2012b6 --- /dev/null +++ b/node_modules/svg-path-bounds/node_modules/normalize-svg-path/test.mjs @@ -0,0 +1,131 @@ +import t from 'tape' +import normalize from './index.mjs' +import parse from 'parse-svg-path' + + +t('line-to', t => { + t.deepEqual( + normalize(parse('L100 100')), + parse('C0,0 100,100 100,100') + ) + + t.deepEqual( + normalize(parse('L50 50 100 0')), + parse('C0,0 50,50 50,50 C50,50 100,0 100,0') + ) + + t.deepEqual( + normalize(parse('H50 100')), + parse('C0,0 50,0 50,0 C50,0 100,0 100,0') + ) + + t.deepEqual( + normalize(parse('V50 100')), + parse('C0,0 0,50 0,50 C0,50 0,100 0,100') + ) + + t.end() +}) + +t('curve-to', t => { + t.deepEqual( + normalize(parse('M10 150 C10 10 150 10 150 150')), + parse('M10,150C10,10,150,10,150,150') + ) + + t.deepEqual( + normalize(parse('M0 120 Q60 0 120 120')), + parse('M0,120C40,40,80,40,120,120') + ) + + t.deepEqual( + normalize(parse('M10 80 C10 10 75 10 75 80 S150 150 150 80')), + parse('M10,80C10,10,75,10,75,80C75,150,150,150,150,80') + ) + + t.deepEqual( + normalize(parse('M0 60 Q30 0 60 60 T120 60')), + parse('M0,60C20,20,40,20,60,60C80,100,100,100,120,60') + ) + + t.deepEqual( + normalize(parse('M30 30 Q50 50 84 50 S124 73 107 92 T127 122')), + parse('M30,30C43.33333333333333,43.33333333333333,61.33333333333333,50,84,50C84,50,124,73,107,92C107,92,113.66666666666666,102,127,122') + ) + + t.end() +}) + +t('close-path', t => { + t.deepEqual( + normalize(parse('L100 0 100 100Z')), + parse('C0,0,100,0,100,0C100,0,100,100,100,100C100,100,0,0,0,0') + ) + + t.end() +}) + + + + +t('arc-to', t => { + t.deepEqual( + r(normalize(parse('M10 80 A150 150 0 0 0 150 80'))), + r(parse('M 10 80C 53.80473794537901 103.1133445143787 106.19526205462094 103.1133445143787 149.99999999999997 80.00000000000003')) + ) + + // half circle clockwise + t.deepEqual( + r(normalize(parse('M10 80 A50 50 0 0 1 150 80'))), + r(parse('M 10 80C 10 41.340067511844474 41.34006751184445 10.000000000000014 79.99999999999999 10C 118.65993248815552 10 150 41.34006751184445 150 79.99999999999999')) + ) + + // half circle anticlockwise + t.deepEqual( + r(normalize(parse('M10 80 A50 50 0 1 0 150 80'))), + r(parse('M 10 80C 10.000000000000014 118.65993248815553 41.340067511844474 150 80 150C 118.65993248815553 150 150 118.65993248815553 150 80')) + ) + + // circle + t.deepEqual( + r(normalize(parse('M10 80 A50 50 0 0 1 150 80 A50 50 0 0 1 10 80'))), + r(parse('M 10 80C 10 41.340067511844474 41.34006751184445 10.000000000000014 79.99999999999999 10C 118.65993248815552 10 150 41.34006751184445 150 79.99999999999999C 150 118.65993248815553 118.65993248815553 150 80 150C 41.340067511844474 150 10.000000000000014 118.65993248815553 10 80.00000000000001')) + ) + + t.deepEqual( + normalize(parse('M10 80 A150 75 30 0 0 150 80')), + parse('M 10 80C 72.04149682761658 108.21761044823509 129.85079028483736 108.21761044823509 150 79.99999999999999') + ) + + // the null curve + t.deepEqual( + normalize(parse('M10 80 A50 50 0 0 1 10 80')), + parse('M10,80') + ) + + t.end() +}) + +function r(arr) { return arr.map(function (arr) { return [arr[0]].concat(arr.slice(1).map(round)) }) } +function round(v) { return Math.round(v) } + +//show parsed curve in the doc +function show(src) { + let path = src.map(seg => seg.join(' ')).join('') + + let el = document.body.appendChild(document.createElement('div')) + let svgNS = 'http://www.w3.org/2000/svg' + + el.innerHTML = `` + + let svg = el.firstChild + + let pathEl = svg.appendChild(document.createElementNS(svgNS, 'path')) + pathEl.setAttribute('d', path) + + pathEl.style.strokeWidth = '2px'; + pathEl.style.stroke = 'black'; + pathEl.style.fill = 'transparent'; + + return src +} diff --git a/node_modules/svg-path-bounds/package.json b/node_modules/svg-path-bounds/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7c90e64cb1e5f74e9fcdf5c472bdb5f4d3ae454a --- /dev/null +++ b/node_modules/svg-path-bounds/package.json @@ -0,0 +1,39 @@ +{ + "name": "svg-path-bounds", + "version": "1.0.2", + "description": "Get bounding box of an svg path data", + "main": "index.js", + "scripts": { + "test": "node test" + }, + "keywords": [ + "svg", + "boundaries", + "normalize", + "coordinate", + "range", + "clip", + "mask", + "svg path", + "path" + ], + "author": "Dima Yv ", + "license": "MIT", + "dependencies": { + "abs-svg-path": "^0.1.1", + "is-svg-path": "^1.0.1", + "normalize-svg-path": "^1.0.0", + "parse-svg-path": "^0.1.2" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dfcreative/svg-path-bounds.git" + }, + "bugs": { + "url": "https://github.com/dfcreative/svg-path-bounds/issues" + }, + "homepage": "https://github.com/dfcreative/svg-path-bounds#readme", + "devDependencies": { + "tape": "^4.7.0" + } +} diff --git a/node_modules/svg-path-bounds/readme.md b/node_modules/svg-path-bounds/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..2a99f9f125d80f34d753c5eaeabfee3e0183550d --- /dev/null +++ b/node_modules/svg-path-bounds/readme.md @@ -0,0 +1,37 @@ +# svg-path-bounds [![Build Status](https://travis-ci.org/dfcreative/svg-path-bounds.svg?branch=master)](https://travis-ci.org/dy/svg-path-bounds) + +Retrieve bounding box from svg path data. + +## Usage + +[![npm install svg-path-bounds](https://nodei.co/npm/svg-path-bounds.png?mini=true)](https://npmjs.org/package/svg-path-bounds/) + +```js +const getBounds = require('svg-path-bounds') + +let [left, top, right, bottom] = getBounds('M0 0L10 10 20 0Z') // [0, 0, 20, 10] +``` + +## API + +### bounds = getBounds(path|segments) + +Calculate bounding box for [svg path data](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d) string or [parsed path segments](https://www.npmjs.com/package/parse-svg-path) array. The box is detected by controlling points, not the real path. + +## Related + +* [parse-svg-path](https://npmjs.org/parse-svg-path) - return svg path data segments +* [abs-svg-path](https://npmjs.org/abs-svg-path) - convert svg path to absolute values +* [rel-svg-path](https://npmjs.org/abs-svg-path) - convert svg path to relative values +* [normalize-svg-path](https://npmjs.org/normalize-svg-path) - make path consist of only bezier curve segments +* [draw-svg-path](https://npmjs.org/draw-svg-path) - create canvas shape based on svg path data +* [normalize-svg-coords](https://npmjs.org/normalize-svg-coords) - bring svg path coordinates to any linear range + +## Similar + +* [svg-boundings](https://www.npmjs.com/package/svg-boundings) +* [svg-path-bounding-box](https://github.com/icons8/svg-path-bounding-box) + +## License + +MIT © Dima Yv diff --git a/node_modules/svg-path-bounds/test.js b/node_modules/svg-path-bounds/test.js new file mode 100644 index 0000000000000000000000000000000000000000..6a90332519533b06cdced9429c48ac4d3d545664 --- /dev/null +++ b/node_modules/svg-path-bounds/test.js @@ -0,0 +1,22 @@ +'use strict' + +const b = require('./') +const t = require('tape') + +t('a', t => { + t.deepEqual(b`M300,200 h-150 a150,150 0 1,0 150,-150 z`, [150, 50, 450, 350]) + + t.deepEqual(new Float32Array(b`M600,350 l 50,-25 a25,25 -30 0,1 50,-25 l 50,-25 a25,50 -30 0,1 50,-25 l 50,-25 a25,75 -30 0,1 50,-25 l 50,-25 a25,100 -30 0,1 50,-25 l 50,-25 + `), new Float32Array([600, 58.73647175569799, 1050, 350])) + + t.deepEqual(b`M100,200 C100,100 250,100 250,200 S400,300 400,200`, [100, 100, 400, 300]) + + t.deepEqual(b`M0 1665q0 38 29 64 27 27 65 27h627q41 0 72.5 30t31.5 73-31.5 74-72.5 31-73-32q-29-26-65-26-38 0-64 25.5t-26 63.5 26 64q85 85 202 85 118 0 201-83.5t83-201.5-83-202-201-84H94q-38 0-66 27.5T0 1665zm0-321q0 35 29 61 27 27 65 27h1170q118 0 201.5-83.5T1549 1147t-83-200-202-82q-121 0-201 81-25 26-25 65t24.5 63.5 63.5 24.5q38 0 66-25 30-30 72-30t72.5 30 30.5 73-30.5 74-72.5 31H94q-38 0-66 27.5T0 1344zm283-251q0 13 18 13h153q11 0 21-15 36-87 111.5-143.5T757 884l56-8q20 0 20-18l7-55q17-173 146-289t304-116q176 0 305.5 115.5T1743 803l7 62q0 19 19 19h174q144 0 245.5 100.5T2290 1227q0 143-101.5 244.5T1943 1573h-736q-20 0-20 19v146q0 18 20 18h736q143 0 264.5-71t192-193 70.5-265q0-118-45-216 121-159 121-353 0-150-75.5-279T2266 174.5 1987 99q-247 0-412 185-128-65-285-65-225 0-398 139.5T672 715q-136 32-240.5 131T286 1080v4q-3 5-3 9zM1155-83q0 37 29 64l65 69q26 26 65 26 40 0 65.5-24.5T1405-13q0-38-24-64l-70-69q-25-28-63-28t-65.5 27-27.5 64zm568 470q115-109 264-109 155 0 267.5 112T2367 658q0 104-55 195-153-153-369-153h-36q-38-173-184-313zm173-559q0 37 26.5 62.5T1987-84t65-25.5 27-62.5v-218q0-38-27-65t-65-27-64.5 27-26.5 65v218zm592 242q0 39 24 64 27 27 65 27.5t61-27.5l156-153q27-27 27-65 0-37-27-64t-65-27-64 26L2512 8q-24 25-24 62zm82 1262q0 37 27 64l68 69q32 26 66 26 31 0 63-26 27-27 27-64 0-35-27-65l-68-69q-26-26-62-26-40 0-67 26.5t-27 64.5zm161-674q0 38 27 63 24 28 61 28h216q38 0 65-27t27-64-27.5-64.5T3035 566h-216q-38 0-63 27t-25 65z`, [0, -482, 3127, 2144]) + + t.deepEqual(b`M0 753q0-150 96.5-267T343 334q36-178 181.5-293.5T857-75q180 0 320.5 110.5T1361 324h30q121 0 226 52t167.5 142.5T1847 715q0 180-138 305 0 56-34.5 128.5T1582 1280t-117 72q-20 99-92 167t-174 91q48 48 48 113 0 79-56 134.5t-135 55.5q-78 0-134-55.5T866 1723q0-9 4.5-28t4.5-29h-9q-94 0-161-67.5T638 1437q0-37 39-113-78-41-125-134H419q-175-15-297-138.5T0 753z`, [0, -75, 1847, 1913]) + + t.deepEqual(b`M0 1226q0 178 106 318t273 187l-68 179q-8 23 15 23h226l-111 447h30l423-600q6-7 1.5-15t-15.5-8H648l264-492q11-23-15-23H583q-14 0-24 15l-114 306q-114-28-188.5-122T182 1226q0-133 89.5-230.5T495 882l57-4q19 0 19-19l8-57q11-113 74-206.5T815.5 449t214.5-53q173 0 303 117t148 289l8 60q0 20 18 20h173q142 0 245.5 102t103.5 242q0 138-96 239.5T1701 1574q-21 0-21 19v143q0 18 21 18 139-4 256-76.5t184-192.5 67-259q0-117-45-214 125-148 125-353 0-113-44.5-216T2124 265t-178-119.5-216-44.5q-247 0-412 185-129-69-288-69-225 0-400 139.5T406 714q-176 41-291 184.5T0 1226zm846 1054q0 26 15.5 49t48.5 33q3 0 8.5 1t10 1.5 8.5.5q67 0 85-64l259-948q10-37-7-68.5t-52-42.5q-37-11-69.5 6.5T1110 1302l-261 949q-3 27-3 29zm442-324q0 64 66 85 27 3 28 3 18 0 37-8 32-14 45-59l175-624q10-37-8-68.5t-54-42.5q-37-11-69 6.5t-42 53.5l-173 628q-5 23-5 26zm178-1568q108-102 264-102 155 0 265 109t110 264q0 101-54 197-154-154-371-154h-34q-45-183-180-314z`, [0, 101, 2288, 2380]) + + t.end() +}) + diff --git a/node_modules/svg-path-sdf/.eslintrc.json b/node_modules/svg-path-sdf/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..c50c250446ee6d06a87a590ecbf3905696b0871d --- /dev/null +++ b/node_modules/svg-path-sdf/.eslintrc.json @@ -0,0 +1,43 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/svg-path-sdf/index.js b/node_modules/svg-path-sdf/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5a1a641786b3f92f417fd8bbab7f363b5ef33c16 --- /dev/null +++ b/node_modules/svg-path-sdf/index.js @@ -0,0 +1,101 @@ +'use strict' + +var pathBounds = require('svg-path-bounds') +var parsePath = require('parse-svg-path') +var drawPath = require('draw-svg-path') +var isSvgPath = require('is-svg-path') +var bitmapSdf = require('bitmap-sdf') + +var canvas = document.createElement('canvas') +var ctx = canvas.getContext('2d') + + +module.exports = pathSdf + + +function pathSdf (path, options) { + if (!isSvgPath(path)) throw Error('Argument should be valid svg path string') + + if (!options) options = {} + + var w, h + if (options.shape) { + w = options.shape[0] + h = options.shape[1] + } + else { + w = canvas.width = options.w || options.width || 200 + h = canvas.height = options.h || options.height || 200 + } + var size = Math.min(w, h) + + var stroke = options.stroke || 0 + + var viewbox = options.viewbox || options.viewBox || pathBounds(path) + var scale = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])] + var maxScale = Math.min(scale[0] || 0, scale[1] || 0) / 2 + + //clear ctx + ctx.fillStyle = 'black' + ctx.fillRect(0, 0, w, h) + + ctx.fillStyle = 'white' + + if (stroke) { + if (typeof stroke != 'number') stroke = 1 + if (stroke > 0) { + ctx.strokeStyle = 'white' + } + else { + ctx.strokeStyle = 'black' + } + + ctx.lineWidth = Math.abs(stroke) + } + + ctx.translate(w * .5, h * .5) + ctx.scale(maxScale, maxScale) + + //if canvas svg paths api is available + if (isPath2DSupported()) { + var path2d = new Path2D(path) + ctx.fill(path2d) + stroke && ctx.stroke(path2d) + } + //fallback to bezier-curves + else { + var segments = parsePath(path) + drawPath(ctx, segments) + ctx.fill() + stroke && ctx.stroke() + } + + ctx.setTransform(1, 0, 0, 1, 0, 0); + + var data = bitmapSdf(ctx, { + cutoff: options.cutoff != null ? options.cutoff : .5, + radius: options.radius != null ? options.radius : size * .5 + }) + + return data +} + +var path2DSupported + +function isPath2DSupported () { + if (path2DSupported != null) return path2DSupported + + var ctx = document.createElement('canvas').getContext('2d') + ctx.canvas.width = ctx.canvas.height = 1 + + if (!window.Path2D) return path2DSupported = false + + var path = new Path2D('M0,0h1v1h-1v-1Z') + + ctx.fillStyle = 'black' + ctx.fill(path) + + var idata = ctx.getImageData(0,0,1,1) + + return path2DSupported = idata && idata.data && idata.data[3] === 255 +} diff --git a/node_modules/svg-path-sdf/package.json b/node_modules/svg-path-sdf/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e644e305cac307c19a3eaf53b352875598ca1105 --- /dev/null +++ b/node_modules/svg-path-sdf/package.json @@ -0,0 +1,42 @@ +{ + "name": "svg-path-sdf", + "version": "1.1.3", + "description": "Get signed distance field for a svg path", + "main": "index.js", + "scripts": { + "test": "budo test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dy/svg-path-sdf.git" + }, + "keywords": [ + "sdf", + "svg", + "path", + "signed", + "distance", + "webgl", + "gl", + "stackgl" + ], + "author": "Dima Yv ", + "license": "MIT", + "bugs": { + "url": "https://github.com/dy/svg-path-sdf/issues" + }, + "homepage": "https://github.com/dy/svg-path-sdf#readme", + "dependencies": { + "bitmap-sdf": "^1.0.0", + "draw-svg-path": "^1.0.0", + "is-svg-path": "^1.0.1", + "parse-svg-path": "^0.1.2", + "svg-path-bounds": "^1.0.1" + }, + "devDependencies": { + "bubleify": "^1.2.0", + "enable-mobile": "^1.0.7", + "insert-styles": "^1.2.1", + "round-to": "^2.0.0" + } +} diff --git a/node_modules/svg-path-sdf/readme.md b/node_modules/svg-path-sdf/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..5ef007b6a6d872174a2cd92ab9c8639a40a2ddb0 --- /dev/null +++ b/node_modules/svg-path-sdf/readme.md @@ -0,0 +1,35 @@ +# svg-path-sdf [![experimental](https://img.shields.io/badge/stability-unstable-green.svg)](http://github.com/badges/stability-badges) + +Create signed distance field for an svg path data. + +![svg-path-sdf](https://github.com/dy/svg-path-sdf/blob/master/preview.png?raw=true) + +## Usage + +[![npm install svg-path-sdf](https://nodei.co/npm/svg-path-sdf.png?mini=true)](https://npmjs.org/package/svg-path-sdf/) + +```js +let pathSdf = require('svg-path-sdf') + +let arr = pathSdf('M40,0A40,40 0 1,1 0,-40A40,40 0 0,1 40,0Z', { + width: 200, + height: 200 +}) +``` + +`arr` has `200×200` elements with value from `0..1` range, corresponding to distance. The path is drawn at the center of the sdf fitting to the minimum side. + +## distances = pathSdf(path, options|shape?) + +Option | Meaning +---|--- +`width`,`w`, `height`,`h` or `shape` | Output sdf size in px, defaults to `200×200`. +`cutoff`, `radius` | SDF parameters for [bitmap-sdf](https://github.com/dy/bitmap-sdf), by default detected from shape to fit min side. +`viewBox` | View box for the path data. If not defined, it is detected as path bounds via [svg-path-bounds](https://github.com/dy/svg-path-bounds). +`stroke` | Whether to stroke shape. Positive number will stroke outside the amount of pixels, negative number will stroke inside, `0`-ish will disable stroke. + +## License + +(c) 2017 Dima Yv. MIT License + +Development supported by plot.ly. diff --git a/node_modules/svg-path-sdf/test.js b/node_modules/svg-path-sdf/test.js new file mode 100644 index 0000000000000000000000000000000000000000..7cccd6f001e34697043692ee23ef4ad5724ec093 --- /dev/null +++ b/node_modules/svg-path-sdf/test.js @@ -0,0 +1,407 @@ +'use strict' + +require('enable-mobile') +require('insert-styles')(` + canvas { + display: block; + float: left; + } +`) +let sdf = require('./') + +// polyfills +Number.isInteger = Number.isInteger || function(value) { + return typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value; +} +Math.sign = Math.sign || function(x) { +return ((x > 0) - (x < 0)) || +x; +} + +let roundn = require('round-to') + + +let shapes = { + circle: function(r) { + var rs = roundn(r, 2); + return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; + }, + + square: function(r) { + var rs = roundn(r, 2); + return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; + }, + + diamond: function(r) { + var rd = roundn(r * 1.3, 2); + return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z'; + }, + + cross: function(r) { + var rc = roundn(r * 0.4, 2), + rc2 = roundn(r * 1.2, 2); + return 'M' + rc2 + ',' + rc + 'H' + rc + 'V' + rc2 + 'H-' + rc + + 'V' + rc + 'H-' + rc2 + 'V-' + rc + 'H-' + rc + 'V-' + rc2 + + 'H' + rc + 'V-' + rc + 'H' + rc2 + 'Z'; + }, + + x: function(r) { + var rx = roundn(r * 0.8 / Math.sqrt(2), 2), + ne = 'l' + rx + ',' + rx, + se = 'l' + rx + ',-' + rx, + sw = 'l-' + rx + ',-' + rx, + nw = 'l-' + rx + ',' + rx; + return 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z'; + }, + + 'triangle-up': function(r) { + var rt = roundn(r * 2 / Math.sqrt(3), 2), + r2 = roundn(r / 2, 2), + rs = roundn(r, 2); + return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z'; + }, + + 'triangle-down': function(r) { + var rt = roundn(r * 2 / Math.sqrt(3), 2), + r2 = roundn(r / 2, 2), + rs = roundn(r, 2); + return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z'; + }, + + 'triangle-left': function(r) { + var rt = roundn(r * 2 / Math.sqrt(3), 2), + r2 = roundn(r / 2, 2), + rs = roundn(r, 2); + return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z'; + }, + + 'triangle-right': function(r) { + var rt = roundn(r * 2 / Math.sqrt(3), 2), + r2 = roundn(r / 2, 2), + rs = roundn(r, 2); + return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z'; + }, + + 'triangle-ne': function(r) { + var r1 = roundn(r * 0.6, 2), + r2 = roundn(r * 1.2, 2); + return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z'; + }, + + 'triangle-se': function(r) { + var r1 = roundn(r * 0.6, 2), + r2 = roundn(r * 1.2, 2); + return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z'; + }, + + 'triangle-sw': function(r) { + var r1 = roundn(r * 0.6, 2), + r2 = roundn(r * 1.2, 2); + return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z'; + }, + + 'triangle-nw': function(r) { + var r1 = roundn(r * 0.6, 2), + r2 = roundn(r * 1.2, 2); + return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z'; + }, + + pentagon: function(r) { + var x1 = roundn(r * 0.951, 2), + x2 = roundn(r * 0.588, 2), + y0 = roundn(-r, 2), + y1 = roundn(r * -0.309, 2), + y2 = roundn(r * 0.809, 2); + return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 + + 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z'; + }, + + hexagon: function(r) { + var y0 = roundn(r, 2), + y1 = roundn(r / 2, 2), + x = roundn(r * Math.sqrt(3) / 2, 2); + return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 + + 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z'; + }, + + hexagon2: function(r) { + var x0 = roundn(r, 2), + x1 = roundn(r / 2, 2), + y = roundn(r * Math.sqrt(3) / 2, 2); + return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 + + ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z'; + }, + + octagon: function(r) { + var a = roundn(r * 0.924, 2), + b = roundn(r * 0.383, 2); + return 'M-' + b + ',-' + a + 'H' + b + 'L' + a + ',-' + b + 'V' + b + + 'L' + b + ',' + a + 'H-' + b + 'L-' + a + ',' + b + 'V-' + b + 'Z'; + }, + + star: function(r) { + var rs = r * 1.4, + x1 = roundn(rs * 0.225, 2), + x2 = roundn(rs * 0.951, 2), + x3 = roundn(rs * 0.363, 2), + x4 = roundn(rs * 0.588, 2), + y0 = roundn(-rs, 2), + y1 = roundn(rs * -0.309, 2), + y3 = roundn(rs * 0.118, 2), + y4 = roundn(rs * 0.809, 2), + y5 = roundn(rs * 0.382, 2); + return 'M' + x1 + ',' + y1 + 'H' + x2 + 'L' + x3 + ',' + y3 + + 'L' + x4 + ',' + y4 + 'L0,' + y5 + 'L-' + x4 + ',' + y4 + + 'L-' + x3 + ',' + y3 + 'L-' + x2 + ',' + y1 + 'H-' + x1 + + 'L0,' + y0 + 'Z'; + }, + + hexagram: function(r) { + var y = roundn(r * 0.66, 2), + x1 = roundn(r * 0.38, 2), + x2 = roundn(r * 0.76, 2); + return 'M-' + x2 + ',0l-' + x1 + ',-' + y + 'h' + x2 + + 'l' + x1 + ',-' + y + 'l' + x1 + ',' + y + 'h' + x2 + + 'l-' + x1 + ',' + y + 'l' + x1 + ',' + y + 'h-' + x2 + + 'l-' + x1 + ',' + y + 'l-' + x1 + ',-' + y + 'h-' + x2 + 'Z'; + }, + + 'star-triangle-up': function(r) { + var x = roundn(r * Math.sqrt(3) * 0.8, 2), + y1 = roundn(r * 0.8, 2), + y2 = roundn(r * 1.6, 2), + rc = roundn(r * 4, 2), + aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; + return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 + + aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z'; + }, + + 'star-triangle-down': function(r) { + var x = roundn(r * Math.sqrt(3) * 0.8, 2), + y1 = roundn(r * 0.8, 2), + y2 = roundn(r * 1.6, 2), + rc = roundn(r * 4, 2), + aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; + return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 + + aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z'; + }, + + 'star-square': function(r) { + var rp = roundn(r * 1.1, 2), + rc = roundn(r * 2, 2), + aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; + return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp + + aPart + rp + ',' + rp + aPart + rp + ',-' + rp + + aPart + '-' + rp + ',-' + rp + 'Z'; + }, + + 'star-diamond': function(r) { + var rp = roundn(r * 1.4, 2), + rc = roundn(r * 1.9, 2), + aPart = 'A ' + rc + ',' + rc + ' 0 0 1 '; + return 'M-' + rp + ',0' + aPart + '0,' + rp + + aPart + rp + ',0' + aPart + '0,-' + rp + + aPart + '-' + rp + ',0' + 'Z'; + }, + + 'diamond-tall': function(r) { + var x = roundn(r * 0.7, 2), + y = roundn(r * 1.4, 2); + return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; + }, + + 'diamond-wide': function(r) { + var x = roundn(r * 1.4, 2), + y = roundn(r * 0.7, 2); + return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z'; + }, + + hourglass: function(r) { + var rs = roundn(r, 2); + return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z'; + }, + + bowtie: function(r) { + var rs = roundn(r, 2); + return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z'; + }, + + 'circle-cross': function(r) { + var rs = roundn(r, 2); + return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + + 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; + }, + + 'circle-x': function(r) { + var rs = roundn(r, 2), + rc = roundn(r / Math.sqrt(2), 2); + return 'M' + rc + ',' + rc + 'L-' + rc + ',-' + rc + + 'M' + rc + ',-' + rc + 'L-' + rc + ',' + rc + + 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs + + 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z'; + }, + + 'square-cross': function(r) { + var rs = roundn(r, 2); + return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs + + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; + }, + + 'square-x': function(r) { + var rs = roundn(r, 2); + return 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs + + 'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs + + 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z'; + }, + + 'diamond-cross': function(r) { + var rd = roundn(r * 1.3, 2); + return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + + 'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd; + }, + + 'diamond-x': function(r) { + var rd = roundn(r * 1.3, 2), + r2 = roundn(r * 0.65, 2); + return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' + + 'M-' + r2 + ',-' + r2 + 'L' + r2 + ',' + r2 + + 'M-' + r2 + ',' + r2 + 'L' + r2 + ',-' + r2; + }, + + 'cross-thin': function(r) { + var rc = roundn(r * 1.4, 2); + return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc; + }, + + 'x-thin': function(r) { + var rx = roundn(r, 2); + return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx + + 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; + }, + + asterisk: function(r) { + var rc = roundn(r * 1.2, 2); + var rs = roundn(r * 0.85, 2); + return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc + + 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs + + 'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs; + }, + + hash: function(r) { + var r1 = roundn(r / 2, 2), + r2 = roundn(r, 2); + return 'M' + r1 + ',' + r2 + 'V-' + r2 + + 'm-' + r2 + ',0V' + r2 + + 'M' + r2 + ',' + r1 + 'H-' + r2 + + 'm0,-' + r2 + 'H' + r2; + }, + + 'y-up': function(r) { + var x = roundn(r * 1.2, 2), + y0 = roundn(r * 1.6, 2), + y1 = roundn(r * 0.8, 2); + return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0'; + }, + + 'y-down': function(r) { + var x = roundn(r * 1.2, 2), + y0 = roundn(r * 1.6, 2), + y1 = roundn(r * 0.8, 2); + return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0'; + }, + + 'y-left': function(r) { + var y = roundn(r * 1.2, 2), + x0 = roundn(r * 1.6, 2), + x1 = roundn(r * 0.8, 2); + return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0'; + }, + + 'y-right': function(r) { + var y = roundn(r * 1.2, 2), + x0 = roundn(r * 1.6, 2), + x1 = roundn(r * 0.8, 2); + return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0'; + }, + + 'line-ew': function(r) { + var rc = roundn(r * 1.4, 2); + return 'M' + rc + ',0H-' + rc; + }, + + 'line-ns': function(r) { + var rc = roundn(r * 1.4, 2); + return 'M0,' + rc + 'V-' + rc; + }, + + 'line-ne': function(r) { + var rx = roundn(r, 2); + return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx; + }, + + 'line-nw': function(r) { + var rx = roundn(r, 2); + return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx; + }, +}; + + +for (let name in shapes) { + let path = shapes[name](10) + shapes.circle(1) + // if (name != 'triangle-left') continue + + showPath(path) + showSdf(sdf(path, {w: 77, h: 77, viewBox: [-10, -10, 10, 10], stroke: -2})) +} + + +function showPath (path) { + let cnv = document.body.appendChild(document.createElement('canvas')) + let ctx = cnv.getContext('2d') + let w = cnv.width = 77 + let h = cnv.height = 77 + + ctx.fillStyle = 'black' + ctx.fillRect(0,0,w,h) + + ctx.fillStyle = 'rgb(0,100,100)' + ctx.strokeStyle = 'white' + ctx.lineWidth = 2 + + ctx.translate(77/2, 77/2) + + // IE fix + if (!window.Path2D) return; + + let path2d = new Path2D(path) + // ctx.fill(path2d) + ctx.stroke(path2d) + + ctx.setTransform(1, 0, 0, 1, 0, 0); +} + + + +function showSdf (arr) { + let dim = Math.sqrt(arr.length) + let cnv = document.body.appendChild(document.createElement('canvas')) + let ctx = cnv.getContext('2d') + let w = cnv.width = dim + let h = cnv.height = dim + let iData = ctx.createImageData(w, h) //new ImageData(w, h) + let data = iData.data + + for (let i = 0; i < w; i++) { + for (let j = 0; j < h; j++) { + data[i*w*4 + j*4 + 0] = arr[i*w + j] * 255 + data[i*w*4 + j*4 + 1] = arr[i*w + j] * 255 + data[i*w*4 + j*4 + 2] = arr[i*w + j] * 255 + data[i*w*4 + j*4 + 3] = 255 + } + } + + ctx.putImageData(iData, 0, 0) +} diff --git a/node_modules/through2/LICENSE.md b/node_modules/through2/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..a2429b6385be26e4b2e4048c6359865d7429918a --- /dev/null +++ b/node_modules/through2/LICENSE.md @@ -0,0 +1,9 @@ +# The MIT License (MIT) + +**Copyright (c) Rod Vagg (the "Original Author") and additional contributors** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/through2/README.md b/node_modules/through2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b5e44c7b178a8a075dd7bc7355efb2727bd6639b --- /dev/null +++ b/node_modules/through2/README.md @@ -0,0 +1,134 @@ +# through2 + +[![NPM](https://nodei.co/npm/through2.png?downloads&downloadRank)](https://nodei.co/npm/through2/) + +**A tiny wrapper around Node streams.Transform (Streams2/3) to avoid explicit subclassing noise** + +Inspired by [Dominic Tarr](https://github.com/dominictarr)'s [through](https://github.com/dominictarr/through) in that it's so much easier to make a stream out of a function than it is to set up the prototype chain properly: `through(function (chunk) { ... })`. + +Note: As 2.x.x this module starts using **Streams3** instead of Stream2. To continue using a Streams2 version use `npm install through2@0` to fetch the latest version of 0.x.x. More information about Streams2 vs Streams3 and recommendations see the article **[Why I don't use Node's core 'stream' module](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html)**. + +```js +fs.createReadStream('ex.txt') + .pipe(through2(function (chunk, enc, callback) { + for (var i = 0; i < chunk.length; i++) + if (chunk[i] == 97) + chunk[i] = 122 // swap 'a' for 'z' + + this.push(chunk) + + callback() + })) + .pipe(fs.createWriteStream('out.txt')) + .on('finish', () => doSomethingSpecial()) +``` + +Or object streams: + +```js +var all = [] + +fs.createReadStream('data.csv') + .pipe(csv2()) + .pipe(through2.obj(function (chunk, enc, callback) { + var data = { + name : chunk[0] + , address : chunk[3] + , phone : chunk[10] + } + this.push(data) + + callback() + })) + .on('data', (data) => { + all.push(data) + }) + .on('end', () => { + doSomethingSpecial(all) + }) +``` + +Note that `through2.obj(fn)` is a convenience wrapper around `through2({ objectMode: true }, fn)`. + +## API + +through2([ options, ] [ transformFunction ] [, flushFunction ]) + +Consult the **[stream.Transform](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_transform)** documentation for the exact rules of the `transformFunction` (i.e. `this._transform`) and the optional `flushFunction` (i.e. `this._flush`). + +### options + +The options argument is optional and is passed straight through to `stream.Transform`. So you can use `objectMode:true` if you are processing non-binary streams (or just use `through2.obj()`). + +The `options` argument is first, unlike standard convention, because if I'm passing in an anonymous function then I'd prefer for the options argument to not get lost at the end of the call: + +```js +fs.createReadStream('/tmp/important.dat') + .pipe(through2({ objectMode: true, allowHalfOpen: false }, + (chunk, enc, cb) => { + cb(null, 'wut?') // note we can use the second argument on the callback + // to provide data as an alternative to this.push('wut?') + } + ) + .pipe(fs.createWriteStream('/tmp/wut.txt')) +``` + +### transformFunction + +The `transformFunction` must have the following signature: `function (chunk, encoding, callback) {}`. A minimal implementation should call the `callback` function to indicate that the transformation is done, even if that transformation means discarding the chunk. + +To queue a new chunk, call `this.push(chunk)`—this can be called as many times as required before the `callback()` if you have multiple pieces to send on. + +Alternatively, you may use `callback(err, chunk)` as shorthand for emitting a single chunk or an error. + +If you **do not provide a `transformFunction`** then you will get a simple pass-through stream. + +### flushFunction + +The optional `flushFunction` is provided as the last argument (2nd or 3rd, depending on whether you've supplied options) is called just prior to the stream ending. Can be used to finish up any processing that may be in progress. + +```js +fs.createReadStream('/tmp/important.dat') + .pipe(through2( + (chunk, enc, cb) => cb(null, chunk), // transform is a noop + function (cb) { // flush function + this.push('tacking on an extra buffer to the end'); + cb(); + } + )) + .pipe(fs.createWriteStream('/tmp/wut.txt')); +``` + +through2.ctor([ options, ] transformFunction[, flushFunction ]) + +Instead of returning a `stream.Transform` instance, `through2.ctor()` returns a **constructor** for a custom Transform. This is useful when you want to use the same transform logic in multiple instances. + +```js +var FToC = through2.ctor({objectMode: true}, function (record, encoding, callback) { + if (record.temp != null && record.unit == "F") { + record.temp = ( ( record.temp - 32 ) * 5 ) / 9 + record.unit = "C" + } + this.push(record) + callback() +}) + +// Create instances of FToC like so: +var converter = new FToC() +// Or: +var converter = FToC() +// Or specify/override options when you instantiate, if you prefer: +var converter = FToC({objectMode: true}) +``` + +## See Also + + - [through2-map](https://github.com/brycebaril/through2-map) - Array.prototype.map analog for streams. + - [through2-filter](https://github.com/brycebaril/through2-filter) - Array.prototype.filter analog for streams. + - [through2-reduce](https://github.com/brycebaril/through2-reduce) - Array.prototype.reduce analog for streams. + - [through2-spy](https://github.com/brycebaril/through2-spy) - Wrapper for simple stream.PassThrough spies. + - the [mississippi stream utility collection](https://github.com/maxogden/mississippi) includes `through2` as well as many more useful stream modules similar to this one + +## License + +**through2** is Copyright (c) Rod Vagg [@rvagg](https://twitter.com/rvagg) and additional contributors and licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/node_modules/through2/package.json b/node_modules/through2/package.json new file mode 100644 index 0000000000000000000000000000000000000000..15960b638dc30ec535d6e91955449ee470790da9 --- /dev/null +++ b/node_modules/through2/package.json @@ -0,0 +1,33 @@ +{ + "name": "through2", + "version": "2.0.5", + "description": "A tiny wrapper around Node streams2 Transform to avoid explicit subclassing noise", + "main": "through2.js", + "scripts": { + "test": "node test/test.js | faucet" + }, + "repository": { + "type": "git", + "url": "https://github.com/rvagg/through2.git" + }, + "keywords": [ + "stream", + "streams2", + "through", + "transform" + ], + "author": "Rod Vagg (https://github.com/rvagg)", + "license": "MIT", + "dependencies": { + "readable-stream": "~2.3.6", + "xtend": "~4.0.1" + }, + "devDependencies": { + "bl": "~2.0.1", + "faucet": "0.0.1", + "nyc": "~13.1.0", + "safe-buffer": "~5.1.2", + "stream-spigot": "~3.0.6", + "tape": "~4.9.1" + } +} diff --git a/node_modules/through2/through2.js b/node_modules/through2/through2.js new file mode 100644 index 0000000000000000000000000000000000000000..6baa6a1e8ff831ecc87a32ead711735acb6c4288 --- /dev/null +++ b/node_modules/through2/through2.js @@ -0,0 +1,96 @@ +var Transform = require('readable-stream').Transform + , inherits = require('util').inherits + , xtend = require('xtend') + +function DestroyableTransform(opts) { + Transform.call(this, opts) + this._destroyed = false +} + +inherits(DestroyableTransform, Transform) + +DestroyableTransform.prototype.destroy = function(err) { + if (this._destroyed) return + this._destroyed = true + + var self = this + process.nextTick(function() { + if (err) + self.emit('error', err) + self.emit('close') + }) +} + +// a noop _transform function +function noop (chunk, enc, callback) { + callback(null, chunk) +} + + +// create a new export function, used by both the main export and +// the .ctor export, contains common logic for dealing with arguments +function through2 (construct) { + return function (options, transform, flush) { + if (typeof options == 'function') { + flush = transform + transform = options + options = {} + } + + if (typeof transform != 'function') + transform = noop + + if (typeof flush != 'function') + flush = null + + return construct(options, transform, flush) + } +} + + +// main export, just make me a transform stream! +module.exports = through2(function (options, transform, flush) { + var t2 = new DestroyableTransform(options) + + t2._transform = transform + + if (flush) + t2._flush = flush + + return t2 +}) + + +// make me a reusable prototype that I can `new`, or implicitly `new` +// with a constructor call +module.exports.ctor = through2(function (options, transform, flush) { + function Through2 (override) { + if (!(this instanceof Through2)) + return new Through2(override) + + this.options = xtend(options, override) + + DestroyableTransform.call(this, this.options) + } + + inherits(Through2, DestroyableTransform) + + Through2.prototype._transform = transform + + if (flush) + Through2.prototype._flush = flush + + return Through2 +}) + + +module.exports.obj = through2(function (options, transform, flush) { + var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) + + t2._transform = transform + + if (flush) + t2._flush = flush + + return t2 +}) diff --git a/node_modules/timers-browserify/CHANGELOG.md b/node_modules/timers-browserify/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..34aa4930bc191961d70c6a874d8de6225187c3e7 --- /dev/null +++ b/node_modules/timers-browserify/CHANGELOG.md @@ -0,0 +1,153 @@ +# Change Log +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +## 2.0.12 - 2020-10-27 + +### Fixed + +* Remove `.DS_Store` from published package +* Upgrade `connect` dev dependency + +## 2.0.11 - 2019-08-10 + +### Fixed + +* License metadata in `package.json` now in standard SPDX format + +## 2.0.10 - 2018-04-18 + +### Fixed + +* Guard `global` usage in scope to avoid reference errors + +## 2.0.9 - 2018-04-17 + +### Fixed + +* Guard `self` usage in scope to avoid Webpack reference errors + +## 2.0.8 - 2018-04-17 + +### Fixed + +* Worker support now explicitly references `self` and `window` rather then using + `this` implicitly to fix issues in Webpack builds. + +## 2.0.7 - 2018-04-16 + +### Fixed + +* Support `setTimeout` / `setInterval` in workers + +## 2.0.6 - 2018-01-24 + +### Fixed + +* Use `typeof` to search globals more carefully. + +## 2.0.5 - 2018-01-23 + +### Fixed + +* Try harder to retrieve `setImmediate` and `clearImmediate` in esoteric + environments. + +## 2.0.4 - 2017-08-14 + +### Fixed + +* Revert `setImmediate` and `clearImmediate` changes from 2.0.3 because they + appear to break Webpack. + +## 2.0.3 - 2017-07-31 + +### Fixed + +* `setImmediate` and `clearImmediate` are indirected through the `global` module + for better coverage of esoteric environments. + +## 2.0.2 - 2016-10-19 + +### Added + +* `.npmignore` now excludes example scripts, reducing package size + +## 2.0.1 - 2016-06-21 + +### Fixed +* `clearTimeout` and `clearInterval` no longer throws when passed null or + undefined instead of the timeout token. + +## 2.0.0 - 2016-03-28 + +### Changed +* `setImmediate` and `clearImmediate` now use the `setimmediate` module which + has better cross-browser coverage. In particular, it resolves a crash in + Safari. The `setimmediate` module adds these methods to the global + immediately, so a major version bump seems safest. + +## 1.4.2 - 2015-12-08 + +### Added +* Metadata used by `jspm` in `package.json` + +## 1.4.1 - 2015-05-10 + +### Changed +* Update `process` dependency + +## 1.4.0 - 2015-02-23 + +### Added +* Link to `timers-browserify-full`, which offers a larger, but much more exact, + version of Node's `timers` library + +### Changed +* `setTimeout` and `setInterval` return objects with the same API as the Node + implementation, instead of just IDs + +### Fixed +* `active` implementation actually has an effect, as in Node +* Replaced usages of `apply` that break in IE 8 + +## 1.3.0 - 2015-02-04 + +### Changed +* Prefer native versions of `setImmediate` and `clearImmediate` if they exist + +## 1.2.0 - 2015-01-02 + +### Changed +* Update `process` dependency + +## 1.1.0 - 2014-08-26 + +### Added +* `clearImmediate` available to undo `setImmediate` + +## 1.0.3 - 2014-06-30 + +### Fixed +* Resume returning opaque IDs from `setTimeout` and `setInterval` + +## 1.0.2 - 2014-06-30 + +### Fixed +* Pass `window` explicitly to `setTimeout` and others to resolve an error in + Chrome + +## 1.0.1 - 2013-12-28 + +### Changed +* Replaced `setimmediate` dependency with `process` for the `nextTick` shim + +## 1.0.0 - 2013-12-10 + +### Added +* Guard against undefined globals like `setTimeout` in some environments + +## 0.0.0 - 2012-05-30 + +### Added +* Basic functionality for initial release diff --git a/node_modules/timers-browserify/LICENSE.md b/node_modules/timers-browserify/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..940ec90a7c86243adbd22d626f19012c5dfcc85a --- /dev/null +++ b/node_modules/timers-browserify/LICENSE.md @@ -0,0 +1,46 @@ +# timers-browserify + +This project uses the [MIT](http://jryans.mit-license.org/) license: + + Copyright © 2012 J. Ryan Stinnett + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the “Software”), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + +# lib/node + +The `lib/node` directory borrows files from joyent/node which uses the following license: + + Copyright Joyent, Inc. and other Node contributors. All rights reserved. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + sell copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. diff --git a/node_modules/timers-browserify/README.md b/node_modules/timers-browserify/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7efa1921bbcba5eba05aeafd9a5402b52614202 --- /dev/null +++ b/node_modules/timers-browserify/README.md @@ -0,0 +1,40 @@ +# Overview + +Adds support for the `timers` module to browserify. + +## Wait, isn't it already supported in the browser? + +The public methods of the `timers` module are: + +* `setTimeout(callback, delay, [arg], [...])` +* `clearTimeout(timeoutId)` +* `setInterval(callback, delay, [arg], [...])` +* `clearInterval(intervalId)` + +and indeed, browsers support these already. + +## So, why does this exist? + +The `timers` module also includes some private methods used in other built-in +Node.js modules: + +* `enroll(item, delay)` +* `unenroll(item)` +* `active(item)` + +These are used to efficiently support a large quantity of timers with the same +timeouts by creating only a few timers under the covers. + +Node.js also offers the `immediate` APIs, which aren't yet available cross-browser, so we polyfill those: + +* `setImmediate(callback, [arg], [...])` +* `clearImmediate(immediateId)` + +## I need lots of timers and want to use linked list timers as Node.js does. + +Linked lists are efficient when you have thousands (millions?) of timers with the same delay. +Take a look at [timers-browserify-full](https://www.npmjs.com/package/timers-browserify-full) in this case. + +# License + +[MIT](http://jryans.mit-license.org/) diff --git a/node_modules/timers-browserify/main.js b/node_modules/timers-browserify/main.js new file mode 100644 index 0000000000000000000000000000000000000000..4214e74bc7f678131edf8b01693ca89dc075ae51 --- /dev/null +++ b/node_modules/timers-browserify/main.js @@ -0,0 +1,63 @@ +var scope = (typeof global !== "undefined" && global) || + (typeof self !== "undefined" && self) || + window; +var apply = Function.prototype.apply; + +// DOM APIs, for completeness + +exports.setTimeout = function() { + return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout); +}; +exports.setInterval = function() { + return new Timeout(apply.call(setInterval, scope, arguments), clearInterval); +}; +exports.clearTimeout = +exports.clearInterval = function(timeout) { + if (timeout) { + timeout.close(); + } +}; + +function Timeout(id, clearFn) { + this._id = id; + this._clearFn = clearFn; +} +Timeout.prototype.unref = Timeout.prototype.ref = function() {}; +Timeout.prototype.close = function() { + this._clearFn.call(scope, this._id); +}; + +// Does not start the time, just sets up the members needed. +exports.enroll = function(item, msecs) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = msecs; +}; + +exports.unenroll = function(item) { + clearTimeout(item._idleTimeoutId); + item._idleTimeout = -1; +}; + +exports._unrefActive = exports.active = function(item) { + clearTimeout(item._idleTimeoutId); + + var msecs = item._idleTimeout; + if (msecs >= 0) { + item._idleTimeoutId = setTimeout(function onTimeout() { + if (item._onTimeout) + item._onTimeout(); + }, msecs); + } +}; + +// setimmediate attaches itself to the global object +require("setimmediate"); +// On some exotic environments, it's not clear which object `setimmediate` was +// able to install onto. Search each possibility in the same order as the +// `setimmediate` library. +exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) || + (typeof global !== "undefined" && global.setImmediate) || + (this && this.setImmediate); +exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) || + (typeof global !== "undefined" && global.clearImmediate) || + (this && this.clearImmediate); diff --git a/node_modules/timers-browserify/package.json b/node_modules/timers-browserify/package.json new file mode 100644 index 0000000000000000000000000000000000000000..be8978f29ecefb685b75865ad12400afd0fb6bb6 --- /dev/null +++ b/node_modules/timers-browserify/package.json @@ -0,0 +1,53 @@ +{ + "author": "J. Ryan Stinnett (https://convolv.es/)", + "name": "timers-browserify", + "description": "timers module for browserify", + "version": "2.0.12", + "homepage": "https://github.com/jryans/timers-browserify", + "bugs": "https://github.com/jryans/timers-browserify/issues", + "repository": { + "type": "git", + "url": "git://github.com/jryans/timers-browserify.git" + }, + "contributors": [ + "Colton Brown ", + "Dario Segura ", + "Guy Bedford ", + "Ionut-Cristian Florescu ", + "James Halliday ", + "Jan Schär ", + "Johannes Ewald ", + "Jonathan Prins ", + "Matt Esch ", + "Renée Kooi ", + "Simon Meusel ", + "taoqf ", + "Thiago Felix ", + "wtgtybhertgeghgtwtg " + ], + "main": "main.js", + "dependencies": { + "setimmediate": "^1.0.4" + }, + "devDependencies": { + "browserify": "~1.10.16", + "connect": "~2.30.2" + }, + "optionalDependencies": {}, + "engines": { + "node": ">=0.6.0" + }, + "keywords": [ + "timers", + "browserify", + "browser" + ], + "license": "MIT", + "jspm": { + "map": { + "./main.js": { + "node": "@node/timers" + } + } + } +} diff --git a/node_modules/tiny-invariant/LICENSE b/node_modules/tiny-invariant/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f3dcb580722abf344fe352e2ac43c5c7ac0a37cf --- /dev/null +++ b/node_modules/tiny-invariant/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Alexander Reardon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/node_modules/tiny-invariant/README.md b/node_modules/tiny-invariant/README.md new file mode 100644 index 0000000000000000000000000000000000000000..761d14151ad17ba69a7bd5a94e06534e234b9586 --- /dev/null +++ b/node_modules/tiny-invariant/README.md @@ -0,0 +1,109 @@ +# tiny-invariant 🔬💥 + +[![Build Status](https://travis-ci.org/alexreardon/tiny-invariant.svg?branch=master)](https://travis-ci.org/alexreardon/tiny-invariant) +[![npm](https://img.shields.io/npm/v/tiny-invariant.svg)](https://www.npmjs.com/package/tiny-invariant) [![dependencies](https://david-dm.org/alexreardon/tiny-invariant.svg)](https://david-dm.org/alexreardon/tiny-invariant) +![types](https://img.shields.io/badge/types-typescript%20%7C%20flow-blueviolet) +[![minzip](https://img.shields.io/bundlephobia/minzip/tiny-invariant.svg)](https://www.npmjs.com/package/tiny-invariant) +[![Downloads per month](https://img.shields.io/npm/dm/tiny-invariant.svg)](https://www.npmjs.com/package/tiny-invariant) + +A tiny [`invariant`](https://www.npmjs.com/package/invariant) alternative. + +## What is `invariant`? + +An `invariant` function takes a value, and if the value is [falsy](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy) then the `invariant` function will throw. If the value is [truthy](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy), then the function will not throw. + +```js +import invariant from 'tiny-invariant'; + +invariant(truthyValue, 'This should not throw!'); + +invariant(falsyValue, 'This will throw!'); +// Error('Invariant violation: This will throw!'); +``` + +You can also provide a function to generate your message, for when your message is expensive to create + +```js +import invariant from 'tiny-invariant'; + +invariant(value, () => getExpensiveMessage()); +``` + +## Why `tiny-invariant`? + +The [`library: invariant`](https://www.npmjs.com/package/invariant) supports passing in arguments to the `invariant` function in a sprintf style `(condition, format, a, b, c, d, e, f)`. It has internal logic to execute the sprintf substitutions. The sprintf logic is not removed in production builds. `tiny-invariant` has dropped all of the sprintf logic. `tiny-invariant` allows you to pass a single string message. With [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) there is really no need for a custom message formatter to be built into the library. If you need a multi part message you can just do this: + +```js +invariant(condition, `Hello, ${name} - how are you today?`); +``` + +## Type narrowing + +`tiny-invariant` is useful for correctly narrowing types for `flow` and `typescript` + +```ts +const value: Person | null = { name: 'Alex' }; // type of value == 'Person | null' +invariant(value, 'Expected value to be a person'); +// type of value has been narrowed to 'Person' +``` + +## API: `(condition: any, message?: string | (() => string)) => void` + +- `condition` is required and can be anything +- `message` optional `string` or a function that returns a `string` (`() => string`) + +## Installation + +```bash +# yarn +yarn add tiny-invariant + +# npm +npm install tiny-invariant --save +``` + +## Dropping your `message` for kb savings! + +Big idea: you will want your compiler to convert this code: + +```js +invariant(condition, 'My cool message that takes up a lot of kbs'); +``` + +Into this: + +```js +if (!condition) { + if ('production' !== process.env.NODE_ENV) { + invariant(false, 'My cool message that takes up a lot of kbs'); + } else { + invariant(false); + } +} +``` + +- **Babel**: recommend [`babel-plugin-dev-expression`](https://www.npmjs.com/package/babel-plugin-dev-expression) +- **TypeScript**: recommend [`tsdx`](https://github.com/jaredpalmer/tsdx#invariant) (or you can run `babel-plugin-dev-expression` after TypeScript compiling) + +Your bundler can then drop the code in the `"production" !== process.env.NODE_ENV` block for your production builds to end up with this: + +```js +if (!condition) { + invariant(false); +} +``` + +- rollup: use [rollup-plugin-replace](https://github.com/rollup/rollup-plugin-replace) and set `NODE_ENV` to `production` and then `rollup` will treeshake out the unused code +- Webpack: [instructions](https://webpack.js.org/guides/production/#specify-the-mode) + +## Builds + +- We have a `es` (EcmaScript module) build +- We have a `cjs` (CommonJS) build +- We have a `umd` (Universal module definition) build in case you needed it + +We expect `process.env.NODE_ENV` to be available at module compilation. We cache this value + +## That's it! + +🤘 diff --git a/node_modules/tiny-invariant/dist/esm/package.json b/node_modules/tiny-invariant/dist/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5ffd9800b97cf26f3962c0fcda77cdb56cb946a8 --- /dev/null +++ b/node_modules/tiny-invariant/dist/esm/package.json @@ -0,0 +1 @@ +{ "type": "module" } diff --git a/node_modules/tiny-invariant/dist/esm/tiny-invariant.d.ts b/node_modules/tiny-invariant/dist/esm/tiny-invariant.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..109a4d706f0b1b9c791597640fa52d6b538ebd76 --- /dev/null +++ b/node_modules/tiny-invariant/dist/esm/tiny-invariant.d.ts @@ -0,0 +1,21 @@ +/** + * `invariant` is used to [assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions) that the `condition` is [truthy](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy). + * + * 💥 `invariant` will `throw` an `Error` if the `condition` is [falsey](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy) + * + * 🤏 `message`s are not displayed in production environments to help keep bundles small + * + * @example + * + * ```ts + * const value: Person | null = { name: 'Alex' }; + * invariant(value, 'Expected value to be a person'); + * // type of `value`` has been narrowed to `Person` + * ``` + */ +export default function invariant(condition: any, +/** + * Can provide a string, or a function that returns a string for cases where + * the message takes a fair amount of effort to compute + */ +message?: string | (() => string)): asserts condition; diff --git a/node_modules/tiny-invariant/dist/esm/tiny-invariant.js b/node_modules/tiny-invariant/dist/esm/tiny-invariant.js new file mode 100644 index 0000000000000000000000000000000000000000..07c9a58538a1da825202e1c58cd9d9fbd375f9ab --- /dev/null +++ b/node_modules/tiny-invariant/dist/esm/tiny-invariant.js @@ -0,0 +1,15 @@ +var isProduction = process.env.NODE_ENV === 'production'; +var prefix = 'Invariant failed'; +function invariant(condition, message) { + if (condition) { + return; + } + if (isProduction) { + throw new Error(prefix); + } + var provided = typeof message === 'function' ? message() : message; + var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix; + throw new Error(value); +} + +export { invariant as default }; diff --git a/node_modules/tiny-invariant/dist/tiny-invariant.cjs.js b/node_modules/tiny-invariant/dist/tiny-invariant.cjs.js new file mode 100644 index 0000000000000000000000000000000000000000..0734005a03ab6377081360b156e5a64e62ab0a4f --- /dev/null +++ b/node_modules/tiny-invariant/dist/tiny-invariant.cjs.js @@ -0,0 +1,17 @@ +'use strict'; + +var isProduction = process.env.NODE_ENV === 'production'; +var prefix = 'Invariant failed'; +function invariant(condition, message) { + if (condition) { + return; + } + if (isProduction) { + throw new Error(prefix); + } + var provided = typeof message === 'function' ? message() : message; + var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix; + throw new Error(value); +} + +module.exports = invariant; diff --git a/node_modules/tiny-invariant/dist/tiny-invariant.d.ts b/node_modules/tiny-invariant/dist/tiny-invariant.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..109a4d706f0b1b9c791597640fa52d6b538ebd76 --- /dev/null +++ b/node_modules/tiny-invariant/dist/tiny-invariant.d.ts @@ -0,0 +1,21 @@ +/** + * `invariant` is used to [assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions) that the `condition` is [truthy](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy). + * + * 💥 `invariant` will `throw` an `Error` if the `condition` is [falsey](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy) + * + * 🤏 `message`s are not displayed in production environments to help keep bundles small + * + * @example + * + * ```ts + * const value: Person | null = { name: 'Alex' }; + * invariant(value, 'Expected value to be a person'); + * // type of `value`` has been narrowed to `Person` + * ``` + */ +export default function invariant(condition: any, +/** + * Can provide a string, or a function that returns a string for cases where + * the message takes a fair amount of effort to compute + */ +message?: string | (() => string)): asserts condition; diff --git a/node_modules/tiny-invariant/dist/tiny-invariant.esm.js b/node_modules/tiny-invariant/dist/tiny-invariant.esm.js new file mode 100644 index 0000000000000000000000000000000000000000..07c9a58538a1da825202e1c58cd9d9fbd375f9ab --- /dev/null +++ b/node_modules/tiny-invariant/dist/tiny-invariant.esm.js @@ -0,0 +1,15 @@ +var isProduction = process.env.NODE_ENV === 'production'; +var prefix = 'Invariant failed'; +function invariant(condition, message) { + if (condition) { + return; + } + if (isProduction) { + throw new Error(prefix); + } + var provided = typeof message === 'function' ? message() : message; + var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix; + throw new Error(value); +} + +export { invariant as default }; diff --git a/node_modules/tiny-invariant/dist/tiny-invariant.js b/node_modules/tiny-invariant/dist/tiny-invariant.js new file mode 100644 index 0000000000000000000000000000000000000000..c70256bcb694dbbfe7b44c0b272c58785c615994 --- /dev/null +++ b/node_modules/tiny-invariant/dist/tiny-invariant.js @@ -0,0 +1,23 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.invariant = factory()); +})(this, (function () { 'use strict'; + + var isProduction = process.env.NODE_ENV === 'production'; + var prefix = 'Invariant failed'; + function invariant(condition, message) { + if (condition) { + return; + } + if (isProduction) { + throw new Error(prefix); + } + var provided = typeof message === 'function' ? message() : message; + var value = provided ? "".concat(prefix, ": ").concat(provided) : prefix; + throw new Error(value); + } + + return invariant; + +})); diff --git a/node_modules/tiny-invariant/dist/tiny-invariant.min.js b/node_modules/tiny-invariant/dist/tiny-invariant.min.js new file mode 100644 index 0000000000000000000000000000000000000000..c7685bfd70d465871ca732742666b7f454a55b4e --- /dev/null +++ b/node_modules/tiny-invariant/dist/tiny-invariant.min.js @@ -0,0 +1 @@ +!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).invariant=n()}(this,(function(){"use strict";return function(e,n){if(!e)throw new Error("Invariant failed")}})); diff --git a/node_modules/tiny-invariant/package.json b/node_modules/tiny-invariant/package.json new file mode 100644 index 0000000000000000000000000000000000000000..737dc358feed7462294fb728aa5291b4fbfc9a1b --- /dev/null +++ b/node_modules/tiny-invariant/package.json @@ -0,0 +1,89 @@ +{ + "name": "tiny-invariant", + "version": "1.3.3", + "description": "A tiny invariant function", + "author": "Alex Reardon ", + "license": "MIT", + "keywords": [ + "invariant", + "error", + "assert", + "asserts" + ], + "repository": { + "type": "git", + "url": "https://github.com/alexreardon/tiny-invariant.git" + }, + "bugs": { + "url": "https://github.com/alexreardon/tiny-invariant/issues" + }, + "main": "dist/tiny-invariant.cjs.js", + "module": "dist/tiny-invariant.esm.js", + "types": "dist/tiny-invariant.d.ts", + "exports": { + ".": { + "import": "./dist/esm/tiny-invariant.js", + "default": { + "types": "./dist/tiny-invariant.d.ts", + "default": "./dist/tiny-invariant.cjs.js" + } + } + }, + "sideEffects": false, + "files": [ + "/dist", + "/src" + ], + "size-limit": [ + { + "path": "dist/tiny-invariant.min.js", + "limit": "217B" + }, + { + "path": "dist/tiny-invariant.js", + "limit": "267B" + }, + { + "path": "dist/tiny-invariant.cjs.js", + "limit": "171B" + }, + { + "path": "dist/tiny-invariant.esm.js", + "import": "foo", + "limit": "112B" + } + ], + "scripts": { + "test": "yarn jest", + "test:size": "yarn build && yarn size-limit", + "prettier:write": "yarn prettier --debug-check src/** test/**", + "prettier:check": "yarn prettier --write src/** test/**", + "typescript:check": "tsc --noEmit", + "validate": "yarn prettier:check && yarn typescript:check", + "build:clean": "rimraf dist", + "build:flow": "cp src/tiny-invariant.js.flow dist/tiny-invariant.cjs.js.flow", + "build:typescript": "tsc ./src/tiny-invariant.ts --emitDeclarationOnly --declaration --outDir ./dist", + "build:typescript:esm": "tsc ./src/tiny-invariant.ts --emitDeclarationOnly --declaration --outDir ./dist/esm", + "build:dist": "yarn rollup --config rollup.config.mjs", + "build": "yarn build:clean && yarn build:dist && yarn build:typescript && yarn build:typescript:esm", + "prepublishOnly": "yarn build" + }, + "devDependencies": { + "@rollup/plugin-replace": "^5.0.5", + "@rollup/plugin-typescript": "^11.1.6", + "@size-limit/preset-small-lib": "^11.0.2", + "@types/jest": "^29.5.12", + "@types/node": "^20.11.20", + "@types/rollup": "^0.54.0", + "expect-type": "^0.17.3", + "jest": "^29.7.0", + "prettier": "^3.2.5", + "rimraf": "^5.0.5", + "rollup": "^4.12.0", + "rollup-plugin-terser": "^7.0.2", + "size-limit": "^11.0.2", + "ts-jest": "^29.1.2", + "tslib": "^2.6.2", + "typescript": "^5.3.3" + } +} diff --git a/node_modules/tiny-invariant/src/tiny-invariant.flow.js b/node_modules/tiny-invariant/src/tiny-invariant.flow.js new file mode 100644 index 0000000000000000000000000000000000000000..0f534cc8a8876217b9658b2b0dcce69030e7cae2 --- /dev/null +++ b/node_modules/tiny-invariant/src/tiny-invariant.flow.js @@ -0,0 +1,12 @@ +// @flow +// This file is not actually executed +// It is just used by flow for typing + +const prefix: string = 'Invariant failed'; + +export default function invariant(condition: mixed, message?: string | (() => string)) { + if (condition) { + return; + } + throw new Error(`${prefix}: ${message || ''}`); +} diff --git a/node_modules/tiny-invariant/src/tiny-invariant.ts b/node_modules/tiny-invariant/src/tiny-invariant.ts new file mode 100644 index 0000000000000000000000000000000000000000..72edc6b241bf6287601f2873b2fe71696a8ec96e --- /dev/null +++ b/node_modules/tiny-invariant/src/tiny-invariant.ts @@ -0,0 +1,48 @@ +const isProduction: boolean = process.env.NODE_ENV === 'production'; +const prefix: string = 'Invariant failed'; + +/** + * `invariant` is used to [assert](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions) that the `condition` is [truthy](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy). + * + * 💥 `invariant` will `throw` an `Error` if the `condition` is [falsey](https://github.com/getify/You-Dont-Know-JS/blob/bdbe570600d4e1107d0b131787903ca1c9ec8140/up%20%26%20going/ch2.md#truthy--falsy) + * + * 🤏 `message`s are not displayed in production environments to help keep bundles small + * + * @example + * + * ```ts + * const value: Person | null = { name: 'Alex' }; + * invariant(value, 'Expected value to be a person'); + * // type of `value`` has been narrowed to `Person` + * ``` + */ +export default function invariant( + condition: any, + // Not providing an inline default argument for message as the result is smaller + /** + * Can provide a string, or a function that returns a string for cases where + * the message takes a fair amount of effort to compute + */ + message?: string | (() => string), +): asserts condition { + if (condition) { + return; + } + // Condition not passed + + // In production we strip the message but still throw + if (isProduction) { + throw new Error(prefix); + } + + // When not in production we allow the message to pass through + // *This block will be removed in production builds* + + const provided: string | undefined = typeof message === 'function' ? message() : message; + + // Options: + // 1. message provided: `${prefix}: ${provided}` + // 2. message not provided: prefix + const value: string = provided ? `${prefix}: ${provided}` : prefix; + throw new Error(value); +} diff --git a/node_modules/tinycolor2/LICENSE b/node_modules/tinycolor2/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b6424d8362292b516584860d3fb1a372f6d23dd2 --- /dev/null +++ b/node_modules/tinycolor2/LICENSE @@ -0,0 +1,20 @@ +Copyright (c), Brian Grinstead, http://briangrinstead.com + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/tinycolor2/README.md b/node_modules/tinycolor2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..71b6d767013316ca5de65e227037ac3ed3d43eb3 --- /dev/null +++ b/node_modules/tinycolor2/README.md @@ -0,0 +1,492 @@ +# TinyColor + +## JavaScript color tooling + +TinyColor is a small, fast library for color manipulation and conversion in JavaScript. It allows many forms of input, while providing color conversions and other color utility functions. It has no dependencies. + +## Including in node + +`tinycolor` can be installed from npm: + + npm install tinycolor2 + +Then it can be used in your script like so: + +```js +var tinycolor = require("tinycolor2"); +var color = tinycolor("red"); +``` + +Or in a module like so: + +```js +import tinycolor from "tinycolor2"; +var color = tinycolor("red"); +``` + +## Including in a browser + +The package can be bundled from npm, but if you prefer to download it locally you have two choices: + +### ESM + +It can be used as a module by downloading [npm/esm/tinycolor.js](https://github.com/bgrins/TinyColor/blob/master/npm/esm/tinycolor.js) or using https://esm.sh/tinycolor2. + +```html + +``` + +### UMD + +You can use it directly in a script tag by downloading the UMD file from [npm/cjs/tinycolor.js](https://github.com/bgrins/TinyColor/blob/master/npm/cjs/tinycolor.js): + +```html + + +``` + +## Usage + +Call `tinycolor(input)` or `new tinycolor(input)`, and you will have an object with the following properties. See Accepted String Input and Accepted Object Input below for more information about what is accepted. + +## Accepted String Input + +The string parsing is very permissive. It is meant to make typing a color as input as easy as possible. All commas, percentages, parenthesis are optional, and most input allow either 0-1, 0%-100%, or 0-n (where n is either 100, 255, or 360 depending on the value). + +HSL and HSV both require either 0%-100% or 0-1 for the `S`/`L`/`V` properties. The `H` (hue) can have values between 0%-100% or 0-360. + +RGB input requires either 0-255 or 0%-100%. + +If you call `tinycolor.fromRatio`, RGB and Hue input can also accept 0-1. + +Here are some examples of string input: + +### Hex, 8-digit (RGBA) Hex +```js +tinycolor("#000"); +tinycolor("000"); +tinycolor("#369C"); +tinycolor("369C"); +tinycolor("#f0f0f6"); +tinycolor("f0f0f6"); +tinycolor("#f0f0f688"); +tinycolor("f0f0f688"); +``` +### RGB, RGBA +```js +tinycolor("rgb (255, 0, 0)"); +tinycolor("rgb 255 0 0"); +tinycolor("rgba (255, 0, 0, .5)"); +tinycolor({ r: 255, g: 0, b: 0 }); +tinycolor.fromRatio({ r: 1, g: 0, b: 0 }); +tinycolor.fromRatio({ r: .5, g: .5, b: .5 }); +``` +### HSL, HSLA +```js +tinycolor("hsl(0, 100%, 50%)"); +tinycolor("hsla(0, 100%, 50%, .5)"); +tinycolor("hsl(0, 100%, 50%)"); +tinycolor("hsl 0 1.0 0.5"); +tinycolor({ h: 0, s: 1, l: .5 }); +tinycolor.fromRatio({ h: 1, s: 0, l: 0 }); +tinycolor.fromRatio({ h: .5, s: .5, l: .5 }); +``` +### HSV, HSVA +```js +tinycolor("hsv(0, 100%, 100%)"); +tinycolor("hsva(0, 100%, 100%, .5)"); +tinycolor("hsv (0 100% 100%)"); +tinycolor("hsv 0 1 1"); +tinycolor({ h: 0, s: 100, v: 100 }); +tinycolor.fromRatio({ h: 1, s: 0, v: 0 }); +tinycolor.fromRatio({ h: .5, s: .5, v: .5 }); +``` +### Named + +Case insenstive names are accepted, using the [list of colors in the CSS spec](https://www.w3.org/TR/css-color-4/#named-colors). + +```js +tinycolor("RED"); +tinycolor("blanchedalmond"); +tinycolor("darkblue"); +``` +### Accepted Object Input + +If you are calling this from code, you may want to use object input. Here are some examples of the different types of accepted object inputs: + + { r: 255, g: 0, b: 0 } + { r: 255, g: 0, b: 0, a: .5 } + { h: 0, s: 100, l: 50 } + { h: 0, s: 100, v: 100 } + +## Methods + +### getFormat + +Returns the format used to create the tinycolor instance +```js +var color = tinycolor("red"); +color.getFormat(); // "name" +color = tinycolor({r:255, g:255, b:255}); +color.getFormat(); // "rgb" +``` + +### getOriginalInput + +Returns the input passed into the constructor used to create the tinycolor instance +```js +var color = tinycolor("red"); +color.getOriginalInput(); // "red" +color = tinycolor({r:255, g:255, b:255}); +color.getOriginalInput(); // "{r: 255, g: 255, b: 255}" +``` + +### isValid + +Return a boolean indicating whether the color was successfully parsed. Note: if the color is not valid then it will act like `black` when being used with other methods. +```js +var color1 = tinycolor("red"); +color1.isValid(); // true +color1.toHexString(); // "#ff0000" + +var color2 = tinycolor("not a color"); +color2.isValid(); // false +color2.toString(); // "#000000" +``` +### getBrightness + +Returns the perceived brightness of a color, from `0-255`, as defined by [Web Content Accessibility Guidelines (Version 1.0)](http://www.w3.org/TR/AERT#color-contrast). +```js +var color1 = tinycolor("#fff"); +color1.getBrightness(); // 255 + +var color2 = tinycolor("#000"); +color2.getBrightness(); // 0 +``` +### isLight + +Return a boolean indicating whether the color's perceived brightness is light. +```js +var color1 = tinycolor("#fff"); +color1.isLight(); // true + +var color2 = tinycolor("#000"); +color2.isLight(); // false +``` +### isDark + +Return a boolean indicating whether the color's perceived brightness is dark. +```js +var color1 = tinycolor("#fff"); +color1.isDark(); // false + +var color2 = tinycolor("#000"); +color2.isDark(); // true +``` +### getLuminance + +Returns the perceived luminance of a color, from `0-1` as defined by [Web Content Accessibility Guidelines (Version 2.0).](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef) +```js +var color1 = tinycolor("#fff"); +color1.getLuminance(); // 1 + +var color2 = tinycolor("#000"); +color2.getLuminance(); // 0 +``` +### getAlpha + +Returns the alpha value of a color, from `0-1`. +```js +var color1 = tinycolor("rgba(255, 0, 0, .5)"); +color1.getAlpha(); // 0.5 + +var color2 = tinycolor("rgb(255, 0, 0)"); +color2.getAlpha(); // 1 + +var color3 = tinycolor("transparent"); +color3.getAlpha(); // 0 +``` +### setAlpha + +Sets the alpha value on a current color. Accepted range is in between `0-1`. +```js +var color = tinycolor("red"); +color.getAlpha(); // 1 +color.setAlpha(.5); +color.getAlpha(); // .5 +color.toRgbString(); // "rgba(255, 0, 0, .5)" +``` +### String Representations + +The following methods will return a property for the `alpha` value, which can be ignored: `toHsv`, `toHsl`, `toRgb` + +### toHsv +```js +var color = tinycolor("red"); +color.toHsv(); // { h: 0, s: 1, v: 1, a: 1 } +``` +### toHsvString +```js +var color = tinycolor("red"); +color.toHsvString(); // "hsv(0, 100%, 100%)" +color.setAlpha(0.5); +color.toHsvString(); // "hsva(0, 100%, 100%, 0.5)" +``` +### toHsl +```js +var color = tinycolor("red"); +color.toHsl(); // { h: 0, s: 1, l: 0.5, a: 1 } +``` +### toHslString +```js +var color = tinycolor("red"); +color.toHslString(); // "hsl(0, 100%, 50%)" +color.setAlpha(0.5); +color.toHslString(); // "hsla(0, 100%, 50%, 0.5)" +``` +### toHex +```js +var color = tinycolor("red"); +color.toHex(); // "ff0000" +``` +### toHexString +```js +var color = tinycolor("red"); +color.toHexString(); // "#ff0000" +``` +### toHex8 +```js +var color = tinycolor("red"); +color.toHex8(); // "ff0000ff" +``` +### toHex8String +```js +var color = tinycolor("red"); +color.toHex8String(); // "#ff0000ff" +``` +### toRgb +```js +var color = tinycolor("red"); +color.toRgb(); // { r: 255, g: 0, b: 0, a: 1 } +``` +### toRgbString +```js +var color = tinycolor("red"); +color.toRgbString(); // "rgb(255, 0, 0)" +color.setAlpha(0.5); +color.toRgbString(); // "rgba(255, 0, 0, 0.5)" +``` +### toPercentageRgb +```js +var color = tinycolor("red"); +color.toPercentageRgb() // { r: "100%", g: "0%", b: "0%", a: 1 } +``` +### toPercentageRgbString +```js +var color = tinycolor("red"); +color.toPercentageRgbString(); // "rgb(100%, 0%, 0%)" +color.setAlpha(0.5); +color.toPercentageRgbString(); // "rgba(100%, 0%, 0%, 0.5)" +``` +### toName +```js +var color = tinycolor("red"); +color.toName(); // "red" +``` +### toFilter +``` +var color = tinycolor("red"); +color.toFilter(); // "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" +``` +### toString + +Print to a string, depending on the input format. You can also override this by passing one of `"rgb", "prgb", "hex6", "hex3", "hex8", "name", "hsl", "hsv"` into the function. +```js +var color1 = tinycolor("red"); +color1.toString(); // "red" +color1.toString("hsv"); // "hsv(0, 100%, 100%)" + +var color2 = tinycolor("rgb(255, 0, 0)"); +color2.toString(); // "rgb(255, 0, 0)" +color2.setAlpha(.5); +color2.toString(); // "rgba(255, 0, 0, 0.5)" +``` +### Color Modification + +These methods manipulate the current color, and return it for chaining. For instance: +```js +tinycolor("red").lighten().desaturate().toHexString() // "#f53d3d" +``` +### lighten + +`lighten: function(amount = 10) -> TinyColor`. Lighten the color a given amount, from 0 to 100. Providing 100 will always return white. +```js +tinycolor("#f00").lighten().toString(); // "#ff3333" +tinycolor("#f00").lighten(100).toString(); // "#ffffff" +``` +### brighten + +`brighten: function(amount = 10) -> TinyColor`. Brighten the color a given amount, from 0 to 100. +```js +tinycolor("#f00").brighten().toString(); // "#ff1919" +``` +### darken + +`darken: function(amount = 10) -> TinyColor`. Darken the color a given amount, from 0 to 100. Providing 100 will always return black. +```js +tinycolor("#f00").darken().toString(); // "#cc0000" +tinycolor("#f00").darken(100).toString(); // "#000000" +``` +### desaturate + +`desaturate: function(amount = 10) -> TinyColor`. Desaturate the color a given amount, from 0 to 100. Providing 100 will is the same as calling `greyscale`. +```js +tinycolor("#f00").desaturate().toString(); // "#f20d0d" +tinycolor("#f00").desaturate(100).toString(); // "#808080" +``` +### saturate + +`saturate: function(amount = 10) -> TinyColor`. Saturate the color a given amount, from 0 to 100. +```js +tinycolor("hsl(0, 10%, 50%)").saturate().toString(); // "hsl(0, 20%, 50%)" +``` +### greyscale + +`greyscale: function() -> TinyColor`. Completely desaturates a color into greyscale. Same as calling `desaturate(100)`. +```js +tinycolor("#f00").greyscale().toString(); // "#808080" +``` +### spin + +`spin: function(amount = 0) -> TinyColor`. Spin the hue a given amount, from -360 to 360. Calling with 0, 360, or -360 will do nothing (since it sets the hue back to what it was before). +```js +tinycolor("#f00").spin(180).toString(); // "#00ffff" +tinycolor("#f00").spin(-90).toString(); // "#7f00ff" +tinycolor("#f00").spin(90).toString(); // "#80ff00" + +// spin(0) and spin(360) do nothing +tinycolor("#f00").spin(0).toString(); // "#ff0000" +tinycolor("#f00").spin(360).toString(); // "#ff0000" +``` +### Color Combinations + +Combination functions return an array of TinyColor objects unless otherwise noted. + +### analogous + +`analogous: function(, results = 6, slices = 30) -> array`. +```js +var colors = tinycolor("#f00").analogous(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ff0066", "#ff0033", "#ff0000", "#ff3300", "#ff6600" ] +``` +### monochromatic + +`monochromatic: function(, results = 6) -> array`. +```js +var colors = tinycolor("#f00").monochromatic(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#2a0000", "#550000", "#800000", "#aa0000", "#d40000" ] +``` +### splitcomplement + +`splitcomplement: function() -> array`. +```js +var colors = tinycolor("#f00").splitcomplement(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#ccff00", "#0066ff" ] +``` +### triad + +`triad: function() -> array`. +```js +var colors = tinycolor("#f00").triad(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#00ff00", "#0000ff" ] +``` +### tetrad + +`tetrad: function() -> array`. +```js +var colors = tinycolor("#f00").tetrad(); + +colors.map(function(t) { return t.toHexString(); }); // [ "#ff0000", "#80ff00", "#00ffff", "#7f00ff" ] + +``` +### complement + +`complement: function() -> TinyColor`. +```js +tinycolor("#f00").complement().toHexString(); // "#00ffff" +``` +## Color Utilities +```js +tinycolor.equals(color1, color2) +tinycolor.mix(color1, color2, amount = 50) +``` +### random + +Returns a random color. +```js +var color = tinycolor.random(); +color.toRgb(); // "{r: 145, g: 40, b: 198, a: 1}" +``` + +### Readability + +TinyColor assesses readability based on the [Web Content Accessibility Guidelines (Version 2.0)](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef). + +#### readability + +`readability: function(TinyColor, TinyColor) -> Object`. +Returns the contrast ratio between two colors. +```js +tinycolor.readability("#000", "#000"); // 1 +tinycolor.readability("#000", "#111"); // 1.1121078324840545 +tinycolor.readability("#000", "#fff"); // 21 +``` +Use the values in your own calculations, or use one of the convenience functions below. + +#### isReadable + +`isReadable: function(TinyColor, TinyColor, Object) -> Boolean`. Ensure that foreground and background color combinations meet WCAG guidelines. `Object` is optional, defaulting to `{level: "AA",size: "small"}`. `level` can be `"AA"` or "AAA" and `size` can be `"small"` or `"large"`. + +Here are links to read more about the [AA](http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html) and [AAA](http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast7.html) requirements. +```js +tinycolor.isReadable("#000", "#111", {}); // false +tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"small"}); //false +tinycolor.isReadable("#ff0088", "#5c1a72",{level:"AA",size:"large"}), //true +``` +#### mostReadable + +`mostReadable: function(TinyColor, [TinyColor, Tinycolor ...], Object) -> Boolean`. +Given a base color and a list of possible foreground or background colors for that base, returns the most readable color. +If none of the colors in the list is readable, `mostReadable` will return the better of black or white if `includeFallbackColors:true`. +```js +tinycolor.mostReadable("#000", ["#f00", "#0f0", "#00f"]).toHexString(); // "#00ff00" +tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString() // "#2e0c3a", +tinycolor.mostReadable("#ff0088", ["#2e0c3a"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString() // "#000000", +``` +See [index.html](https://github.com/bgrins/TinyColor/blob/master/index.html) in the project for a demo. + +## Common operations + +### clone + +`clone: function() -> TinyColor`. +Instantiate a new TinyColor object with the same color. Any changes to the new one won't affect the old one. +```js +var color1 = tinycolor("#F00"); +var color2 = color1.clone(); +color2.setAlpha(.5); + +color1.toString(); // "#ff0000" +color2.toString(); // "rgba(255, 0, 0, 0.5)" +``` diff --git a/node_modules/tinycolor2/cjs/package.json b/node_modules/tinycolor2/cjs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5bbefffbabee392d1855491b84dc0a716b6a3bf2 --- /dev/null +++ b/node_modules/tinycolor2/cjs/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/tinycolor2/cjs/test.js b/node_modules/tinycolor2/cjs/test.js new file mode 100644 index 0000000000000000000000000000000000000000..40be5fddcb6c99a97dbf9938a7ae156dbd8e619c --- /dev/null +++ b/node_modules/tinycolor2/cjs/test.js @@ -0,0 +1,2191 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +const tinycolor = require("./tinycolor.js"); +const { Deno, testDefinitions } = require("@deno/shim-deno-test"); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} +(async () => { + const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" + ); + + // TEST_BEGINS_HERE + +Deno.test("TinyColor initialization", function () { + assert( + typeof tinycolor != "undefined", + "tinycolor is initialized on the page" + ); + assert( + typeof tinycolor("red") == "object", + "tinycolor is able to be instantiated" + ); + + var r = tinycolor("red"); + assert( + tinycolor(r) === r, + "when given a tinycolor instance, tinycolor() returns it" + ); + assert( + new tinycolor(r) === r, + "when given a tinycolor instance, new tinycolor() returns it" + ); + assertEquals( + tinycolor("red", { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + + var obj = { h: 180, s: 0.5, l: 0.5 }; + var color = tinycolor(obj); + assert( + obj.s === 0.5, + "when given an object, the original object is not modified" + ); +}); + +Deno.test("Original input", function () { + var colorRgbUp = "RGB(39, 39, 39)"; + var colorRgbLow = "rgb(39, 39, 39)"; + var colorRgbMix = "RgB(39, 39, 39)"; + var tinycolorObj = tinycolor(colorRgbMix); + var inputObj = { r: 100, g: 100, b: 100 }; + var r = tinycolor("red"); + + assert( + tinycolor(colorRgbLow).getOriginalInput() === colorRgbLow, + "original lowercase input is returned" + ); + assert( + tinycolor(colorRgbUp).getOriginalInput() === colorRgbUp, + "original uppercase input is returned" + ); + assert( + tinycolor(colorRgbMix).getOriginalInput() === colorRgbMix, + "original mixed input is returned" + ); + assert( + tinycolor(tinycolorObj).getOriginalInput() === colorRgbMix, + "when given a tinycolor instance, the color string is returned" + ); + assert( + tinycolor(inputObj).getOriginalInput() === inputObj, + "when given an object, the object is returned" + ); + assert( + new tinycolor("").getOriginalInput() === "", + "when given an empty string, an empty string is returned" + ); + assert( + new tinycolor(null).getOriginalInput() === "", + "when given a null value, an empty string is returned" + ); +}); + +Deno.test("Cloning color", function () { + var originalColor = tinycolor("red"); + var originalColorRgbString = originalColor.toRgbString(); + + var clonedColor = originalColor.clone(); + assert( + clonedColor.toRgbString() === originalColor.toRgbString(), + "cloned color is identical" + ); + + clonedColor.setAlpha(0.5); + assert( + clonedColor.toRgbString() !== originalColor.toRgbString(), + "cloned color is changing independently from original color" + ); + assert( + originalColorRgbString === originalColor.toRgbString(), + "original color was not changed by cloned color change" + ); +}); +Deno.test("Random color", function () { + var randomColor = tinycolor.random(); + assertEquals(randomColor.getAlpha(), 1); + assertEquals(randomColor.getFormat(), "prgb"); + + randomColor.setAlpha(0.5); + assertEquals(randomColor.toHex8String().slice(-2), "80"); +}); + +// Taken from convertWikipediaColors.html +var conversions = [ + { + hex: "#FFFFFF", + hex8: "#FFFFFFFF", + rgb: { r: "100.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "0", s: "0.000", v: "1.000" }, + hsl: { h: "0", s: "0.000", l: "1.000" }, + }, + { + hex: "#808080", + hex8: "#808080FF", + rgb: { r: "050.0%", g: "050.0%", b: "050.0%" }, + hsv: { h: "0", s: "0.000", v: "0.500" }, + hsl: { h: "0", s: "0.000", l: "0.500" }, + }, + { + hex: "#000000", + hex8: "#000000FF", + rgb: { r: "000.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0", s: "0.000", v: "0.000" }, + hsl: { h: "0", s: "0.000", l: "0.000" }, + }, + { + hex: "#FF0000", + hex8: "#FF0000FF", + rgb: { r: "100.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0.0", s: "1.000", v: "1.000" }, + hsl: { h: "0.0", s: "1.000", l: "0.500" }, + }, + { + hex: "#BFBF00", + hex8: "#BFBF00FF", + rgb: { r: "075.0%", g: "075.0%", b: "000.0%" }, + hsv: { h: "60.0", s: "1.000", v: "0.750" }, + hsl: { h: "60.0", s: "1.000", l: "0.375" }, + }, + { + hex: "#008000", + hex8: "#008000FF", + rgb: { r: "000.0%", g: "050.0%", b: "000.0%" }, + hsv: { h: "120.0", s: "1.000", v: "0.500" }, + hsl: { h: "120.0", s: "1.000", l: "0.250" }, + }, + { + hex: "#80FFFF", + hex8: "#80FFFFFF", + rgb: { r: "050.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "180.0", s: "0.500", v: "1.000" }, + hsl: { h: "180.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#8080FF", + hex8: "#8080FFFF", + rgb: { r: "050.0%", g: "050.0%", b: "100.0%" }, + hsv: { h: "240.0", s: "0.500", v: "1.000" }, + hsl: { h: "240.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#BF40BF", + hex8: "#BF40BFFF", + rgb: { r: "075.0%", g: "025.0%", b: "075.0%" }, + hsv: { h: "300.0", s: "0.667", v: "0.750" }, + hsl: { h: "300.0", s: "0.500", l: "0.500" }, + }, + { + hex: "#A0A424", + hex8: "#A0A424FF", + rgb: { r: "062.8%", g: "064.3%", b: "014.2%" }, + hsv: { h: "61.8", s: "0.779", v: "0.643" }, + hsl: { h: "61.8", s: "0.638", l: "0.393" }, + }, + { + hex: "#1EAC41", + hex8: "#1EAC41FF", + rgb: { r: "011.6%", g: "067.5%", b: "025.5%" }, + hsv: { h: "134.9", s: "0.828", v: "0.675" }, + hsl: { h: "134.9", s: "0.707", l: "0.396" }, + }, + { + hex: "#B430E5", + hex8: "#B430E5FF", + rgb: { r: "070.4%", g: "018.7%", b: "089.7%" }, + hsv: { h: "283.7", s: "0.792", v: "0.897" }, + hsl: { h: "283.7", s: "0.775", l: "0.542" }, + }, + { + hex: "#FEF888", + hex8: "#FEF888FF", + rgb: { r: "099.8%", g: "097.4%", b: "053.2%" }, + hsv: { h: "56.9", s: "0.467", v: "0.998" }, + hsl: { h: "56.9", s: "0.991", l: "0.765" }, + }, + { + hex: "#19CB97", + hex8: "#19CB97FF", + rgb: { r: "009.9%", g: "079.5%", b: "059.1%" }, + hsv: { h: "162.4", s: "0.875", v: "0.795" }, + hsl: { h: "162.4", s: "0.779", l: "0.447" }, + }, + { + hex: "#362698", + hex8: "#362698FF", + rgb: { r: "021.1%", g: "014.9%", b: "059.7%" }, + hsv: { h: "248.3", s: "0.750", v: "0.597" }, + hsl: { h: "248.3", s: "0.601", l: "0.373" }, + }, + { + hex: "#7E7EB8", + hex8: "#7E7EB8FF", + rgb: { r: "049.5%", g: "049.3%", b: "072.1%" }, + hsv: { h: "240.5", s: "0.316", v: "0.721" }, + hsl: { h: "240.5", s: "0.290", l: "0.607" }, + }, +]; + +Deno.test("Color Equality", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + + assert(true, tiny.isValid()); + assert( + true, + "Testing " + + c.hex + + ": " + + tiny.toRgbString() + + " " + + tiny.toPercentageRgbString() + + " " + + tiny.toHsvString() + + " " + + tiny.toHslString() + + " " + + tiny.toHexString() + + "Original: " + + JSON.stringify(c.rgb) + + " " + + JSON.stringify(c.hsv) + + " " + + JSON.stringify(c.hsl) + ); + assert(tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); + assert(tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); + + assert(tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); + assert(tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); + assert(tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); + assert(tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); + + assert(tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); + } +}); + +Deno.test("With Ratio", function () { + assertEquals( + tinycolor.fromRatio({ r: 1, g: 1, b: 1 }).toHexString(), + "#ffffff", + "white" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 0.5 }).toRgbString(), + "rgba(255, 0, 0, 0.5)", + "alpha works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha = 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 10 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha > 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: -1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha < 1 works when ratio is parsed" + ); +}); + +Deno.test("Without Ratio", function () { + assertEquals( + tinycolor({ r: 1, g: 1, b: 1 }).toHexString(), + "#010101", + "010101" + ); + assertEquals( + tinycolor({ r: 0.1, g: 0.1, b: 0.1 }).toHexString(), + "#000000", + "000000" + ); + assertEquals(tinycolor("rgb .1 .1 .1").toHexString(), "#000000", "000000"); +}); + +Deno.test("RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 255 0 0").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert( + tinycolor.equals({ r: 200, g: 100, b: 0, a: 0.4 }, "rgba 200 100 0 .4") + ); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgba 200 100 0 1")); + + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb(200, 100, 0)") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); +}); + +Deno.test("Percentage RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 100% 0% 0%").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert( + tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert( + tinycolor.equals( + { r: "90%", g: "45%", b: "0%", a: 0.4 }, + "rgba 90% 45% 0% .4" + ) + ); + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1") + ); + + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb(90%, 45%, 0%)" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); +}); + +Deno.test("HSL parsing", function () { + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38, a: 0.5 }).toHslString(), + "hsla(251, 100%, 38%, 0.5)", + "to hsla" + ); + assertEquals( + tinycolor("hsl(251, 100, 38)").toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor("hsl 100 20 10").toHslString(), + "hsl(100, 20%, 10%)", + "problematic hsl" + ); +}); + +Deno.test("Hex Parsing", function () { + assertEquals(tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHexString(true), "#f00"); + + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8String(), "#ff000080"); + assertEquals(tinycolor("rgba 255 0 0 0").toHex8String(), "#ff000000"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(), "#ff0000ff"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(true), "#f00f"); + + assertEquals(tinycolor("rgb 255 0 0").toHex(), "ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHex(true), "f00"); + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8(), "ff000080"); +}); + +Deno.test("HSV Parsing", function () { + assertEquals( + tinycolor("hsv 251.1 0.887 .918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsv 251.1 0.887 0.918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsva 251.1 0.887 0.918 0.5").toHsvString(), + "hsva(251, 89%, 92%, 0.5)" + ); +}); + +Deno.test("Invalid Parsing", function () { + var invalidColor = tinycolor("this is not a color"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("#red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" #red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" ##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ r: "invalid", g: "invalid", b: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", l: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", v: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); +}); + +Deno.test("Named colors", function () { + assertEquals(tinycolor("aliceblue").toHex(), "f0f8ff"); + assertEquals(tinycolor("antiquewhite").toHex(), "faebd7"); + assertEquals(tinycolor("aqua").toHex(), "00ffff"); + assertEquals(tinycolor("aquamarine").toHex(), "7fffd4"); + assertEquals(tinycolor("azure").toHex(), "f0ffff"); + assertEquals(tinycolor("beige").toHex(), "f5f5dc"); + assertEquals(tinycolor("bisque").toHex(), "ffe4c4"); + assertEquals(tinycolor("black").toHex(), "000000"); + assertEquals(tinycolor("blanchedalmond").toHex(), "ffebcd"); + assertEquals(tinycolor("blue").toHex(), "0000ff"); + assertEquals(tinycolor("blueviolet").toHex(), "8a2be2"); + assertEquals(tinycolor("brown").toHex(), "a52a2a"); + assertEquals(tinycolor("burlywood").toHex(), "deb887"); + assertEquals(tinycolor("cadetblue").toHex(), "5f9ea0"); + assertEquals(tinycolor("chartreuse").toHex(), "7fff00"); + assertEquals(tinycolor("chocolate").toHex(), "d2691e"); + assertEquals(tinycolor("coral").toHex(), "ff7f50"); + assertEquals(tinycolor("cornflowerblue").toHex(), "6495ed"); + assertEquals(tinycolor("cornsilk").toHex(), "fff8dc"); + assertEquals(tinycolor("crimson").toHex(), "dc143c"); + assertEquals(tinycolor("cyan").toHex(), "00ffff"); + assertEquals(tinycolor("darkblue").toHex(), "00008b"); + assertEquals(tinycolor("darkcyan").toHex(), "008b8b"); + assertEquals(tinycolor("darkgoldenrod").toHex(), "b8860b"); + assertEquals(tinycolor("darkgray").toHex(), "a9a9a9"); + assertEquals(tinycolor("darkgreen").toHex(), "006400"); + assertEquals(tinycolor("darkkhaki").toHex(), "bdb76b"); + assertEquals(tinycolor("darkmagenta").toHex(), "8b008b"); + assertEquals(tinycolor("darkolivegreen").toHex(), "556b2f"); + assertEquals(tinycolor("darkorange").toHex(), "ff8c00"); + assertEquals(tinycolor("darkorchid").toHex(), "9932cc"); + assertEquals(tinycolor("darkred").toHex(), "8b0000"); + assertEquals(tinycolor("darksalmon").toHex(), "e9967a"); + assertEquals(tinycolor("darkseagreen").toHex(), "8fbc8f"); + assertEquals(tinycolor("darkslateblue").toHex(), "483d8b"); + assertEquals(tinycolor("darkslategray").toHex(), "2f4f4f"); + assertEquals(tinycolor("darkturquoise").toHex(), "00ced1"); + assertEquals(tinycolor("darkviolet").toHex(), "9400d3"); + assertEquals(tinycolor("deeppink").toHex(), "ff1493"); + assertEquals(tinycolor("deepskyblue").toHex(), "00bfff"); + assertEquals(tinycolor("dimgray").toHex(), "696969"); + assertEquals(tinycolor("dodgerblue").toHex(), "1e90ff"); + assertEquals(tinycolor("firebrick").toHex(), "b22222"); + assertEquals(tinycolor("floralwhite").toHex(), "fffaf0"); + assertEquals(tinycolor("forestgreen").toHex(), "228b22"); + assertEquals(tinycolor("fuchsia").toHex(), "ff00ff"); + assertEquals(tinycolor("gainsboro").toHex(), "dcdcdc"); + assertEquals(tinycolor("ghostwhite").toHex(), "f8f8ff"); + assertEquals(tinycolor("gold").toHex(), "ffd700"); + assertEquals(tinycolor("goldenrod").toHex(), "daa520"); + assertEquals(tinycolor("gray").toHex(), "808080"); + assertEquals(tinycolor("grey").toHex(), "808080"); + assertEquals(tinycolor("green").toHex(), "008000"); + assertEquals(tinycolor("greenyellow").toHex(), "adff2f"); + assertEquals(tinycolor("honeydew").toHex(), "f0fff0"); + assertEquals(tinycolor("hotpink").toHex(), "ff69b4"); + assertEquals(tinycolor("indianred ").toHex(), "cd5c5c"); + assertEquals(tinycolor("indigo ").toHex(), "4b0082"); + assertEquals(tinycolor("ivory").toHex(), "fffff0"); + assertEquals(tinycolor("khaki").toHex(), "f0e68c"); + assertEquals(tinycolor("lavender").toHex(), "e6e6fa"); + assertEquals(tinycolor("lavenderblush").toHex(), "fff0f5"); + assertEquals(tinycolor("lawngreen").toHex(), "7cfc00"); + assertEquals(tinycolor("lemonchiffon").toHex(), "fffacd"); + assertEquals(tinycolor("lightblue").toHex(), "add8e6"); + assertEquals(tinycolor("lightcoral").toHex(), "f08080"); + assertEquals(tinycolor("lightcyan").toHex(), "e0ffff"); + assertEquals(tinycolor("lightgoldenrodyellow").toHex(), "fafad2"); + assertEquals(tinycolor("lightgrey").toHex(), "d3d3d3"); + assertEquals(tinycolor("lightgreen").toHex(), "90ee90"); + assertEquals(tinycolor("lightpink").toHex(), "ffb6c1"); + assertEquals(tinycolor("lightsalmon").toHex(), "ffa07a"); + assertEquals(tinycolor("lightseagreen").toHex(), "20b2aa"); + assertEquals(tinycolor("lightskyblue").toHex(), "87cefa"); + assertEquals(tinycolor("lightslategray").toHex(), "778899"); + assertEquals(tinycolor("lightsteelblue").toHex(), "b0c4de"); + assertEquals(tinycolor("lightyellow").toHex(), "ffffe0"); + assertEquals(tinycolor("lime").toHex(), "00ff00"); + assertEquals(tinycolor("limegreen").toHex(), "32cd32"); + assertEquals(tinycolor("linen").toHex(), "faf0e6"); + assertEquals(tinycolor("magenta").toHex(), "ff00ff"); + assertEquals(tinycolor("maroon").toHex(), "800000"); + assertEquals(tinycolor("mediumaquamarine").toHex(), "66cdaa"); + assertEquals(tinycolor("mediumblue").toHex(), "0000cd"); + assertEquals(tinycolor("mediumorchid").toHex(), "ba55d3"); + assertEquals(tinycolor("mediumpurple").toHex(), "9370db"); + assertEquals(tinycolor("mediumseagreen").toHex(), "3cb371"); + assertEquals(tinycolor("mediumslateblue").toHex(), "7b68ee"); + assertEquals(tinycolor("mediumspringgreen").toHex(), "00fa9a"); + assertEquals(tinycolor("mediumturquoise").toHex(), "48d1cc"); + assertEquals(tinycolor("mediumvioletred").toHex(), "c71585"); + assertEquals(tinycolor("midnightblue").toHex(), "191970"); + assertEquals(tinycolor("mintcream").toHex(), "f5fffa"); + assertEquals(tinycolor("mistyrose").toHex(), "ffe4e1"); + assertEquals(tinycolor("moccasin").toHex(), "ffe4b5"); + assertEquals(tinycolor("navajowhite").toHex(), "ffdead"); + assertEquals(tinycolor("navy").toHex(), "000080"); + assertEquals(tinycolor("oldlace").toHex(), "fdf5e6"); + assertEquals(tinycolor("olive").toHex(), "808000"); + assertEquals(tinycolor("olivedrab").toHex(), "6b8e23"); + assertEquals(tinycolor("orange").toHex(), "ffa500"); + assertEquals(tinycolor("orangered").toHex(), "ff4500"); + assertEquals(tinycolor("orchid").toHex(), "da70d6"); + assertEquals(tinycolor("palegoldenrod").toHex(), "eee8aa"); + assertEquals(tinycolor("palegreen").toHex(), "98fb98"); + assertEquals(tinycolor("paleturquoise").toHex(), "afeeee"); + assertEquals(tinycolor("palevioletred").toHex(), "db7093"); + assertEquals(tinycolor("papayawhip").toHex(), "ffefd5"); + assertEquals(tinycolor("peachpuff").toHex(), "ffdab9"); + assertEquals(tinycolor("peru").toHex(), "cd853f"); + assertEquals(tinycolor("pink").toHex(), "ffc0cb"); + assertEquals(tinycolor("plum").toHex(), "dda0dd"); + assertEquals(tinycolor("powderblue").toHex(), "b0e0e6"); + assertEquals(tinycolor("purple").toHex(), "800080"); + assertEquals(tinycolor("rebeccapurple").toHex(), "663399"); + assertEquals(tinycolor("red").toHex(), "ff0000"); + assertEquals(tinycolor("rosybrown").toHex(), "bc8f8f"); + assertEquals(tinycolor("royalblue").toHex(), "4169e1"); + assertEquals(tinycolor("saddlebrown").toHex(), "8b4513"); + assertEquals(tinycolor("salmon").toHex(), "fa8072"); + assertEquals(tinycolor("sandybrown").toHex(), "f4a460"); + assertEquals(tinycolor("seagreen").toHex(), "2e8b57"); + assertEquals(tinycolor("seashell").toHex(), "fff5ee"); + assertEquals(tinycolor("sienna").toHex(), "a0522d"); + assertEquals(tinycolor("silver").toHex(), "c0c0c0"); + assertEquals(tinycolor("skyblue").toHex(), "87ceeb"); + assertEquals(tinycolor("slateblue").toHex(), "6a5acd"); + assertEquals(tinycolor("slategray").toHex(), "708090"); + assertEquals(tinycolor("snow").toHex(), "fffafa"); + assertEquals(tinycolor("springgreen").toHex(), "00ff7f"); + assertEquals(tinycolor("steelblue").toHex(), "4682b4"); + assertEquals(tinycolor("tan").toHex(), "d2b48c"); + assertEquals(tinycolor("teal").toHex(), "008080"); + assertEquals(tinycolor("thistle").toHex(), "d8bfd8"); + assertEquals(tinycolor("tomato").toHex(), "ff6347"); + assertEquals(tinycolor("turquoise").toHex(), "40e0d0"); + assertEquals(tinycolor("violet").toHex(), "ee82ee"); + assertEquals(tinycolor("wheat").toHex(), "f5deb3"); + assertEquals(tinycolor("white").toHex(), "ffffff"); + assertEquals(tinycolor("whitesmoke").toHex(), "f5f5f5"); + assertEquals(tinycolor("yellow").toHex(), "ffff00"); + assertEquals(tinycolor("yellowgreen").toHex(), "9acd32"); + + assertEquals(tinycolor("#f00").toName(), "red"); + assertEquals(tinycolor("#fa0a0a").toName(), false); +}); + +Deno.test("Invalid alpha should normalize to 1", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -1 }).toRgbString(), + "rgb(255, 20, 10)", + "Negative value" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "Negative 0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0.5 }).toRgbString(), + "rgba(255, 20, 10, 0.5)", + ".5" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 1 }).toRgbString(), + "rgb(255, 20, 10)", + "1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 100 }).toRgbString(), + "rgb(255, 20, 10)", + "Greater than 1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: "asdfasd" }).toRgbString(), + "rgb(255, 20, 10)", + "Non Numeric" + ); + + assertEquals( + tinycolor("#fff").toRgbString(), + "rgb(255, 255, 255)", + "Hex should be 1" + ); + assertEquals( + tinycolor("rgba 255 0 0 100").toRgbString(), + "rgb(255, 0, 0)", + "Greater than 1 in string parsing" + ); +}); + +Deno.test("toString() with alpha set", function () { + var redNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.6 }, + { + format: "name", + } + ); + var transparentNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0 }, + { + format: "name", + } + ); + var redHex = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.4 }, + { + format: "hex", + } + ); + + assertEquals(redNamed.getFormat(), "name", "getFormat() is correct"); + assertEquals(redHex.getFormat(), "hex", "getFormat() is correct"); + + assertEquals( + redNamed.toString(), + "rgba(255, 0, 0, 0.6)", + "Names should default to rgba if alpha is < 1" + ); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + + assertEquals( + redNamed.toString("hex"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex6"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex3"), + "#f00", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex8"), + "#ff000099", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex4"), + "#f009", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("name"), + "#ff0000", + "Semi transparent names should return hex in toString() if name format is specified" + ); + + assertEquals( + redNamed.toName(), + false, + "Semi transparent names should be false in toName()" + ); + + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + assertEquals( + transparentNamed.toString(), + "transparent", + "Named color should equal transparent if alpha == 0" + ); + + redHex.setAlpha(0); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0)", + "Hex should default to rgba if alpha is = 0" + ); +}); + +Deno.test("setting alpha", function () { + var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); + assertEquals(hexSetter.getAlpha(), 1, "Alpha should start as 1"); + var returnedFromSetAlpha = hexSetter.setAlpha(0.9); + assertEquals( + returnedFromSetAlpha, + hexSetter, + "setAlpha return value should be the color." + ); + assertEquals(hexSetter.getAlpha(), 0.9, "setAlpha should change alpha value"); + hexSetter.setAlpha(0.5); + assertEquals(hexSetter.getAlpha(), 0.5, "setAlpha should change alpha value"); + hexSetter.setAlpha(0); + assertEquals(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); + hexSetter.setAlpha(-1); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value < 0 should be bound to 1" + ); + hexSetter.setAlpha(2); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value > 1 should be bound to 1" + ); + hexSetter.setAlpha(); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha(null); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha("test"); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); +}); + +Deno.test("Alpha = 0 should act differently on toName()", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toName(), + "transparent", + "0" + ); + assertEquals( + tinycolor("transparent").toString(), + "transparent", + "toString when passed" + ); + assertEquals(tinycolor("transparent").toHex(), "000000", "toHex"); +}); + +Deno.test("getBrightness", function () { + assertEquals(tinycolor("#000").getBrightness(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getBrightness(), 255, "returns 255 for #fff"); +}); + +Deno.test("getLuminance", function () { + assertEquals(tinycolor("#000").getLuminance(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getLuminance(), 1, "returns 1 for #fff"); +}); + +Deno.test("isDark returns true/false for dark/light colors", function () { + assertEquals(tinycolor("#000").isDark(), true, "#000 is dark"); + assertEquals(tinycolor("#111").isDark(), true, "#111 is dark"); + assertEquals(tinycolor("#222").isDark(), true, "#222 is dark"); + assertEquals(tinycolor("#333").isDark(), true, "#333 is dark"); + assertEquals(tinycolor("#444").isDark(), true, "#444 is dark"); + assertEquals(tinycolor("#555").isDark(), true, "#555 is dark"); + assertEquals(tinycolor("#666").isDark(), true, "#666 is dark"); + assertEquals(tinycolor("#777").isDark(), true, "#777 is dark"); + assertEquals(tinycolor("#888").isDark(), false, "#888 is not dark"); + assertEquals(tinycolor("#999").isDark(), false, "#999 is not dark"); + assertEquals(tinycolor("#aaa").isDark(), false, "#aaa is not dark"); + assertEquals(tinycolor("#bbb").isDark(), false, "#bbb is not dark"); + assertEquals(tinycolor("#ccc").isDark(), false, "#ccc is not dark"); + assertEquals(tinycolor("#ddd").isDark(), false, "#ddd is not dark"); + assertEquals(tinycolor("#eee").isDark(), false, "#eee is not dark"); + assertEquals(tinycolor("#fff").isDark(), false, "#fff is not dark"); +}); + +Deno.test("isLight returns true/false for light/dark colors", function () { + assertEquals(tinycolor("#000").isLight(), false, "#000 is not light"); + assertEquals(tinycolor("#111").isLight(), false, "#111 is not light"); + assertEquals(tinycolor("#222").isLight(), false, "#222 is not light"); + assertEquals(tinycolor("#333").isLight(), false, "#333 is not light"); + assertEquals(tinycolor("#444").isLight(), false, "#444 is not light"); + assertEquals(tinycolor("#555").isLight(), false, "#555 is not light"); + assertEquals(tinycolor("#666").isLight(), false, "#666 is not light"); + assertEquals(tinycolor("#777").isLight(), false, "#777 is not light"); + assertEquals(tinycolor("#888").isLight(), true, "#888 is light"); + assertEquals(tinycolor("#999").isLight(), true, "#999 is light"); + assertEquals(tinycolor("#aaa").isLight(), true, "#aaa is light"); + assertEquals(tinycolor("#bbb").isLight(), true, "#bbb is light"); + assertEquals(tinycolor("#ccc").isLight(), true, "#ccc is light"); + assertEquals(tinycolor("#ddd").isLight(), true, "#ddd is light"); + assertEquals(tinycolor("#eee").isLight(), true, "#eee is light"); + assertEquals(tinycolor("#fff").isLight(), true, "#fff is light"); +}); + +Deno.test("HSL Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsl()).toHexString(), + "HSL Object" + ); + } +}); + +Deno.test("HSL String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHslString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHslString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHslString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHslString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHsvString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHsvString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHsvString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHsvString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsv()).toHexString(), + "HSV Object" + ); + } +}); + +Deno.test("RGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgb()).toHexString(), + "RGB Object" + ); + } +}); + +Deno.test("RGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgbString()).toHexString(), + "RGB String" + ); + } +}); + +Deno.test("PRGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgb()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("PRGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgbString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals(tiny.toHexString(), tinycolor(tiny).toHexString(), "Object"); + } +}); + +Deno.test("Color equality", function () { + assert(tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); + assert( + !tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), + "Different alphas" + ); + assert(tinycolor.equals("#ff000066", "rgba(255, 0, 0, .4)"), "Same alphas"); + assert(tinycolor.equals("#f009", "rgba(255, 0, 0, .6)"), "Same alphas"); + assert(tinycolor.equals("#336699CC", "369C"), "Same hex"); + assert(tinycolor.equals("ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("f00", "#ff0000"), "Same hex"); + assertEquals(tinycolor("010101").toHexString(), "#010101"); + assert(!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); + assert( + tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), + "Percentage bounds checking" + ); +}); + +Deno.test("isReadable", function () { + // "#ff0088", "#8822aa" (values used in old WCAG1 tests) + assert( + tinycolor.isReadable("#000000", "#ffffff", { level: "AA", size: "small" }), + "white/black is readable" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", {}), + "not readable - empty wcag2 object" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "large" }), + "not readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // values derived from and validated using the calculators at http://www.dasplankton.de/ContrastA/ + // and http://webaim.org/resources/contrastchecker/ + + // "#ff0088", "#5c1a72": contrast ratio 3.04 + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // "#ff0088", "#2e0c3a": contrast ratio 4.56 + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#2e0c3a", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); + + // "#db91b8", "#2e0c3a": contrast ratio 7.12 + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "small" }), + "readable - AAA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); +}); + +Deno.test("readability", function () { + // check return values from readability function. See isReadable above for standards tests. + assertEquals( + tinycolor.readability("#000", "#000"), + 1, + "Readability function test 0" + ); + assertEquals( + tinycolor.readability("#000", "#111"), + 1.1121078324840545, + "Readability function test 1" + ); + assertEquals( + tinycolor.readability("#000", "#fff"), + 21, + "Readability function test 2" + ); +}); + +Deno.test("mostReadable", function () { + assertEquals( + tinycolor + .mostReadable("#000", ["#111", "#222", { wcag2: {} }]) + .toHexString(), + "#222222", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#f00", ["#d00", "#0d0"], { wcag2: {} }) + .toHexString(), + "#00dd00", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { wcag2: {} }) + .toHexString(), + "#ffffff", + "no different color in list" + ); + //includeFallbackColors + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { + includeFallbackColors: true, + }) + .toHexString(), + "#000000", + "no different color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: false, + }) + .toHexString(), + "#112255", + "no readable color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: true, + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#000000", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#2e0c3a", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#000000", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#a9acb6", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); +}); + +Deno.test("Filters", function () { + assertEquals( + tinycolor("red").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" + ); + assertEquals( + tinycolor("red").toFilter("blue"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)" + ); + + assertEquals( + tinycolor("transparent").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)" + ); + assertEquals( + tinycolor("transparent").toFilter("red"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)" + ); + + assertEquals( + tinycolor("#f0f0f0dd").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)" + ); + assertEquals( + tinycolor("rgba(0, 0, 255, .5").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)" + ); +}); + +/* Originally generated with: +var results = []; +for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) +console.log(JSON.stringify(results)) +*/ +var DESATURATIONS = [ + "ff0000", + "fe0101", + "fc0303", + "fb0404", + "fa0505", + "f90606", + "f70808", + "f60909", + "f50a0a", + "f40b0b", + "f20d0d", + "f10e0e", + "f00f0f", + "ee1111", + "ed1212", + "ec1313", + "eb1414", + "e91616", + "e81717", + "e71818", + "e61919", + "e41b1b", + "e31c1c", + "e21d1d", + "e01f1f", + "df2020", + "de2121", + "dd2222", + "db2424", + "da2525", + "d92626", + "d72828", + "d62929", + "d52a2a", + "d42b2b", + "d22d2d", + "d12e2e", + "d02f2f", + "cf3030", + "cd3232", + "cc3333", + "cb3434", + "c93636", + "c83737", + "c73838", + "c63939", + "c43b3b", + "c33c3c", + "c23d3d", + "c13e3e", + "bf4040", + "be4141", + "bd4242", + "bb4444", + "ba4545", + "b94646", + "b84747", + "b64949", + "b54a4a", + "b44b4b", + "b34d4d", + "b14e4e", + "b04f4f", + "af5050", + "ad5252", + "ac5353", + "ab5454", + "aa5555", + "a85757", + "a75858", + "a65959", + "a45b5b", + "a35c5c", + "a25d5d", + "a15e5e", + "9f6060", + "9e6161", + "9d6262", + "9c6363", + "9a6565", + "996666", + "986767", + "966969", + "956a6a", + "946b6b", + "936c6c", + "916e6e", + "906f6f", + "8f7070", + "8e7171", + "8c7373", + "8b7474", + "8a7575", + "887777", + "877878", + "867979", + "857a7a", + "837c7c", + "827d7d", + "817e7e", + "808080", +]; +var SATURATIONS = [ + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", +]; +var LIGHTENS = [ + "ff0000", + "ff0505", + "ff0a0a", + "ff0f0f", + "ff1414", + "ff1a1a", + "ff1f1f", + "ff2424", + "ff2929", + "ff2e2e", + "ff3333", + "ff3838", + "ff3d3d", + "ff4242", + "ff4747", + "ff4d4d", + "ff5252", + "ff5757", + "ff5c5c", + "ff6161", + "ff6666", + "ff6b6b", + "ff7070", + "ff7575", + "ff7a7a", + "ff8080", + "ff8585", + "ff8a8a", + "ff8f8f", + "ff9494", + "ff9999", + "ff9e9e", + "ffa3a3", + "ffa8a8", + "ffadad", + "ffb3b3", + "ffb8b8", + "ffbdbd", + "ffc2c2", + "ffc7c7", + "ffcccc", + "ffd1d1", + "ffd6d6", + "ffdbdb", + "ffe0e0", + "ffe5e5", + "ffebeb", + "fff0f0", + "fff5f5", + "fffafa", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", +]; +var BRIGHTENS = [ + "ff0000", + "ff0303", + "ff0505", + "ff0808", + "ff0a0a", + "ff0d0d", + "ff0f0f", + "ff1212", + "ff1414", + "ff1717", + "ff1919", + "ff1c1c", + "ff1f1f", + "ff2121", + "ff2424", + "ff2626", + "ff2929", + "ff2b2b", + "ff2e2e", + "ff3030", + "ff3333", + "ff3636", + "ff3838", + "ff3b3b", + "ff3d3d", + "ff4040", + "ff4242", + "ff4545", + "ff4747", + "ff4a4a", + "ff4c4c", + "ff4f4f", + "ff5252", + "ff5454", + "ff5757", + "ff5959", + "ff5c5c", + "ff5e5e", + "ff6161", + "ff6363", + "ff6666", + "ff6969", + "ff6b6b", + "ff6e6e", + "ff7070", + "ff7373", + "ff7575", + "ff7878", + "ff7a7a", + "ff7d7d", + "ff7f7f", + "ff8282", + "ff8585", + "ff8787", + "ff8a8a", + "ff8c8c", + "ff8f8f", + "ff9191", + "ff9494", + "ff9696", + "ff9999", + "ff9c9c", + "ff9e9e", + "ffa1a1", + "ffa3a3", + "ffa6a6", + "ffa8a8", + "ffabab", + "ffadad", + "ffb0b0", + "ffb2b2", + "ffb5b5", + "ffb8b8", + "ffbaba", + "ffbdbd", + "ffbfbf", + "ffc2c2", + "ffc4c4", + "ffc7c7", + "ffc9c9", + "ffcccc", + "ffcfcf", + "ffd1d1", + "ffd4d4", + "ffd6d6", + "ffd9d9", + "ffdbdb", + "ffdede", + "ffe0e0", + "ffe3e3", + "ffe5e5", + "ffe8e8", + "ffebeb", + "ffeded", + "fff0f0", + "fff2f2", + "fff5f5", + "fff7f7", + "fffafa", + "fffcfc", + "ffffff", +]; +var DARKENS = [ + "ff0000", + "fa0000", + "f50000", + "f00000", + "eb0000", + "e60000", + "e00000", + "db0000", + "d60000", + "d10000", + "cc0000", + "c70000", + "c20000", + "bd0000", + "b80000", + "b30000", + "ad0000", + "a80000", + "a30000", + "9e0000", + "990000", + "940000", + "8f0000", + "8a0000", + "850000", + "800000", + "7a0000", + "750000", + "700000", + "6b0000", + "660000", + "610000", + "5c0000", + "570000", + "520000", + "4d0000", + "470000", + "420000", + "3d0000", + "380000", + "330000", + "2e0000", + "290000", + "240000", + "1f0000", + "190000", + "140000", + "0f0000", + "0a0000", + "050000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", +]; + +Deno.test("Modifications", function () { + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").desaturate(i).toHex(), + DESATURATIONS[i], + "Desaturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").saturate(i).toHex(), + SATURATIONS[i], + "Saturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").lighten(i).toHex(), + LIGHTENS[i], + "Lighten " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").brighten(i).toHex(), + BRIGHTENS[i], + "Brighter " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").darken(i).toHex(), + DARKENS[i], + "Darken " + i + " works" + ); + } + + assertEquals( + tinycolor("red").greyscale().toHex(), + "808080", + "Greyscale works" + ); +}); + +Deno.test("Spin", function () { + assertEquals( + Math.round(tinycolor("#f00").spin(-1234).toHsl().h), + 206, + "Spinning -1234 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-360).toHsl().h), + 0, + "Spinning -360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-120).toHsl().h), + 240, + "Spinning -120 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(0).toHsl().h), + 0, + "Spinning 0 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(10).toHsl().h), + 10, + "Spinning 10 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(360).toHsl().h), + 0, + "Spinning 360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(2345).toHsl().h), + 185, + "Spinning 2345 works" + ); + + [-360, 0, 360].forEach(function (delta) { + Object.keys(tinycolor.names).forEach(function (name) { + assertEquals( + tinycolor(name).toHex(), + tinycolor(name).spin(delta).toHex(), + "Spinning " + delta.toString() + " has no effect" + ); + }); + }); +}); + +Deno.test("Mix", function () { + // amount 0 or none + assertEquals( + tinycolor.mix("#000", "#fff").toHsl().l, + 0.5, + "Mixing without amount works" + ); + assertEquals( + tinycolor.mix("#f00", "#000", 0).toHex(), + "ff0000", + "Mixing with 0 amount works" + ); + // This case checks the the problem with floating point numbers (eg 255/90) + assertEquals( + tinycolor.mix("#fff", "#000", 90).toHex(), + "1a1a1a", + "Mixing with 90 amount works correctly" + ); + + // black and white + for (var i = 0; i < 100; i++) { + assertEquals( + Math.round(tinycolor.mix("#000", "#fff", i).toHsl().l * 100) / 100, + i / 100, + "Mixing black and white with " + i + " amount works" + ); + } + + // with colors + for (var i = 0; i < 100; i++) { + var new_hex = Math.round((255 * (100 - i)) / 100).toString(16); + + if (new_hex.length === 1) { + new_hex = "0" + new_hex; + } + + assertEquals( + tinycolor.mix("#f00", "#000", i).toHex(), + new_hex + "0000", + "Mixing " + i + " (red channel)" + ); + assertEquals( + tinycolor.mix("#0f0", "#000", i).toHex(), + "00" + new_hex + "00", + "Mixing " + i + " (green channel)" + ); + assertEquals( + tinycolor.mix("#00f", "#000", i).toHex(), + "0000" + new_hex, + "Mixing " + i + " (blue channel)" + ); + assertEquals( + tinycolor.mix(tinycolor("transparent"), "#000", i).toRgb().a, + i / 100, + "Mixing " + i + " (alpha channel)" + ); + } +}); + +// The combination tests need to be expanded furthe + +function colorsToHexString(colors) { + return colors + .map(function (c) { + return c.toHex(); + }) + .join(","); +} + +Deno.test("complement", function () { + var complementDoesntModifyInstance = tinycolor("red"); + assertEquals( + complementDoesntModifyInstance.complement().toHex(), + "00ffff", + "Complement works" + ); + assertEquals( + complementDoesntModifyInstance.toHex(), + "ff0000", + "Complement did not modify this color" + ); +}); + +Deno.test("analogous", function () { + var combination = tinycolor("red").analogous(); + assertEquals( + colorsToHexString(combination), + "ff0000,ff0066,ff0033,ff0000,ff3300,ff6600", + "Correct Combination" + ); +}); + +Deno.test("monochromatic", function () { + var combination = tinycolor("red").monochromatic(); + assertEquals( + colorsToHexString(combination), + "ff0000,2a0000,550000,800000,aa0000,d40000", + "Correct Combination" + ); +}); + +Deno.test("splitcomplement", function () { + var combination = tinycolor("red").splitcomplement(); + assertEquals( + colorsToHexString(combination), + "ff0000,ccff00,0066ff", + "Correct Combination" + ); +}); + +Deno.test("triad", function () { + var combination = tinycolor("red").triad(); + assertEquals( + colorsToHexString(combination), + "ff0000,00ff00,0000ff", + "Correct Combination" + ); +}); + +Deno.test("tetrad", function () { + var combination = tinycolor("red").tetrad(); + assertEquals( + colorsToHexString(combination), + "ff0000,80ff00,00ffff,7f00ff", + "Correct Combination" + ); +}); + +Deno.test({ + name: "polyad", + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + ignore: true, + fn: function () { + assertThrows(() => { + tinycolor("red").polyad(); + }); + assertThrows(() => { + tinycolor("red").polyad(-1); + }); + assertThrows(() => { + tinycolor("red").polyad("invalid"); + }); + assertEquals(colorsToHexString(tinycolor("red").polyad(1)), "ff0000"); + assertEquals(colorsToHexString(tinycolor("red").polyad("1")), "ff0000"); + assertEquals( + colorsToHexString(tinycolor("red").polyad(2)), + "ff0000,00ffff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(3)), + "ff0000,00ff00,0000ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(4)), + "ff0000,80ff00,00ffff,7f00ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(5)), + "ff0000,ccff00,00ff66,0066ff,cc00ff" + ); + }, +}); + + runDenoTests(); +})(); diff --git a/node_modules/tinycolor2/cjs/test_template.js b/node_modules/tinycolor2/cjs/test_template.js new file mode 100644 index 0000000000000000000000000000000000000000..d170c2cd736e00f8ddfeb2e4b4464455613fa7ac --- /dev/null +++ b/node_modules/tinycolor2/cjs/test_template.js @@ -0,0 +1,26 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +const tinycolor = require("./tinycolor.js"); +const { Deno, testDefinitions } = require("@deno/shim-deno-test"); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} +(async () => { + const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" + ); + + // CONTENT_GOES_HERE + + runDenoTests(); +})(); diff --git a/node_modules/tinycolor2/cjs/tinycolor.js b/node_modules/tinycolor2/cjs/tinycolor.js new file mode 100644 index 0000000000000000000000000000000000000000..4f584cab54d4a124cb17b47458c0e85fd141b0ca --- /dev/null +++ b/node_modules/tinycolor2/cjs/tinycolor.js @@ -0,0 +1,1188 @@ +// This file is autogenerated. It's used to publish CJS to npm. +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.tinycolor = factory()); +})(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + + // https://github.com/bgrins/TinyColor + // Brian Grinstead, MIT License + + var trimLeft = /^\s+/; + var trimRight = /\s+$/; + function tinycolor(color, opts) { + color = color ? color : ""; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } + var rgb = inputToRGB(color); + this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb.ok; + } + tinycolor.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function getLuminance() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r / 255; + GsRGB = rgb.g / 255; + BsRGB = rgb.b / 255; + if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }, + setAlpha: function setAlpha(value) { + this._a = boundAlpha(value); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), + s = Math.round(hsv.s * 100), + v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl.h * 360, + s: hsl.s, + l: hsl.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl.h * 360), + s = Math.round(hsl.s * 100), + l = Math.round(hsl.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString(format) { + var formatSet = !!format; + format = format || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone() { + return tinycolor(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } + }; + + // If input is an object, force 1 into "1.0" to handle ratios properly + // String input requires "1.0" as input, so 1 will be treated as 1 + tinycolor.fromRatio = function (color, opts) { + if (_typeof(color) == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + return tinycolor(color, opts); + }; + + // Given a string or object, convert that input to RGB + // Possible string inputs: + // + // "red" + // "#f00" or "f00" + // "#ff0000" or "ff0000" + // "#ff000000" or "ff000000" + // "rgb 255 0 0" or "rgb (255, 0, 0)" + // "rgb 1.0 0 0" or "rgb (1, 0, 0)" + // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" + // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" + // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" + // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" + // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" + // + function inputToRGB(color) { + var rgb = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } + if (_typeof(color) == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: Math.min(255, Math.max(rgb.r, 0)), + g: Math.min(255, Math.max(rgb.g, 0)), + b: Math.min(255, Math.max(rgb.b, 0)), + a: a + }; + } + + // Conversion Functions + // -------------------- + + // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: + // + + // `rgbToRgb` + // Handle bounds / percentage checking to conform to CSS color spec + // + // *Assumes:* r, g, b in [0, 255] or [0, 1] + // *Returns:* { r, g, b } in [0, 255] + function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + + // `rgbToHsl` + // Converts an RGB color value to HSL. + // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] + // *Returns:* { h, s, l } in [0,1] + function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + l = (max + min) / 2; + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + l: l + }; + } + + // `hslToRgb` + // Converts an HSL color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHsv` + // Converts an RGB color value to HSV + // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] + // *Returns:* { h, s, v } in [0,1] + function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + v: v + }; + } + + // `hsvToRgb` + // Converts an HSV color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHex` + // Converts an RGB color to hex + // Assumes r, g, and b are contained in the set [0, 255] + // Returns a 3 or 6 character hex + function rgbToHex(r, g, b, allow3Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + return hex.join(""); + } + + // `rgbaToHex` + // Converts an RGBA color plus alpha transparency to hex + // Assumes r, g, b are contained in the set [0, 255] and + // a in [0, 1]. Returns a 4 or 8 character rgba hex + function rgbaToHex(r, g, b, a, allow4Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); + } + return hex.join(""); + } + + // `rgbaToArgbHex` + // Converts an RGBA color to an ARGB Hex8 string + // Rarely used, but required for "toFilter()" + function rgbaToArgbHex(r, g, b, a) { + var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex.join(""); + } + + // `equals` + // Can be called with any tinycolor input + tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) return false; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); + }; + tinycolor.random = function () { + return tinycolor.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); + }; + + // Modification Functions + // ---------------------- + // Thanks to less.js for some of the basics here + // + + function _desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _greyscale(color) { + return tinycolor(color).desaturate(100); + } + function _lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + function _brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); + rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); + rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); + return tinycolor(rgb); + } + function _darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + + // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. + // Values outside of this range will be wrapped into this range. + function _spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); + } + + // Combination Functions + // --------------------- + // Thanks to jQuery xColor for some of the ideas behind these + // + + function _complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); + } + function polyad(color, number) { + if (isNaN(number) || number <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl = tinycolor(color).toHsl(); + var result = [tinycolor(color)]; + var step = 360 / number; + for (var i = 1; i < number; i++) { + result.push(tinycolor({ + h: (hsl.h + i * step) % 360, + s: hsl.s, + l: hsl.l + })); + } + return result; + } + function _splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [tinycolor(color), tinycolor({ + h: (h + 72) % 360, + s: hsl.s, + l: hsl.l + }), tinycolor({ + h: (h + 216) % 360, + s: hsl.s, + l: hsl.l + })]; + } + function _analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; + } + function _monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor({ + h: h, + s: s, + v: v + })); + v = (v + modification) % 1; + } + return ret; + } + + // Utility Functions + // --------------------- + + tinycolor.mix = function (color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + var p = amount / 100; + var rgba = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor(rgba); + }; + + // Readability Functions + // --------------------- + // false + // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false + tinycolor.isReadable = function (color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; + }; + + // `mostReadable` + // Given a base color and a list of possible foreground or background + // colors for that base, returns the most readable color. + // Optionally returns Black or White if the most readable color is unreadable. + // *Example* + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" + tinycolor.mostReadable = function (baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } + if (tinycolor.isReadable(baseColor, bestColor, { + level: level, + size: size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); + } + }; + + // Big List of Colors + // ------------------ + // + var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" + }; + + // Make it easy to access colors via `hexNames[hex]` + var hexNames = tinycolor.hexNames = flip(names); + + // Utilities + // --------- + + // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` + function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } + + // Return a valid alpha value [0,1] with all invalid values being set to 1 + function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; + } + + // Take input from [0, n] and return it as [0, 1] + function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if (Math.abs(n - max) < 0.000001) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return n % max / parseFloat(max); + } + + // Force a number between 0 and 1 + function clamp01(val) { + return Math.min(1, Math.max(0, val)); + } + + // Parse a base-16 hex value into a base-10 integer + function parseIntFromHex(val) { + return parseInt(val, 16); + } + + // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 + // + function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; + } + + // Check to see if string passed in is a percentage + function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; + } + + // Force a hex value to have 2 characters + function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; + } + + // Replace a decimal with it's percentage value + function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; + } + + // Converts a decimal to a hex value + function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); + } + // Converts a hex value to a decimal + function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; + } + var matchers = function () { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + }(); + + // `isValidCSSUnit` + // Take in a single string / number and check to see if it looks like a CSS unit + // (see `matchers` above for definition). + function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); + } + + // `stringInputToObject` + // Permissive string parsing. Take in a number of formats, and output an object + // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` + function stringInputToObject(color) { + color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if (match = matchers.rgb.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named ? "name" : "hex" + }; + } + return false; + } + function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level: level, + size: size + }; + } + + return tinycolor; + +})); diff --git a/node_modules/tinycolor2/deno_asserts@0.168.0.mjs b/node_modules/tinycolor2/deno_asserts@0.168.0.mjs new file mode 100644 index 0000000000000000000000000000000000000000..685fdd20acadd30a682cdd228ac15ce1aa46b205 --- /dev/null +++ b/node_modules/tinycolor2/deno_asserts@0.168.0.mjs @@ -0,0 +1,807 @@ +// deno-fmt-ignore-file +// deno-lint-ignore-file +// This code was bundled using `deno bundle` and it's not recommended to edit it manually +// Using `deno bundle https://deno.land/std@0.168.0/testing/asserts.ts > npm/deno_asserts@0.168.0.mjs` + +const { Deno } = globalThis; +const noColor = typeof Deno?.noColor === "boolean" ? Deno.noColor : true; +let enabled = !noColor; +function code(open, close) { + return { + open: `\x1b[${open.join(";")}m`, + close: `\x1b[${close}m`, + regexp: new RegExp(`\\x1b\\[${close}m`, "g") + }; +} +function run(str, code) { + return enabled ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` : str; +} +function bold(str) { + return run(str, code([ + 1 + ], 22)); +} +function red(str) { + return run(str, code([ + 31 + ], 39)); +} +function green(str) { + return run(str, code([ + 32 + ], 39)); +} +function white(str) { + return run(str, code([ + 37 + ], 39)); +} +function gray(str) { + return brightBlack(str); +} +function brightBlack(str) { + return run(str, code([ + 90 + ], 39)); +} +function bgRed(str) { + return run(str, code([ + 41 + ], 49)); +} +function bgGreen(str) { + return run(str, code([ + 42 + ], 49)); +} +const ANSI_PATTERN = new RegExp([ + "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", + "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))" +].join("|"), "g"); +function stripColor(string) { + return string.replace(ANSI_PATTERN, ""); +} +var DiffType; +(function(DiffType) { + DiffType["removed"] = "removed"; + DiffType["common"] = "common"; + DiffType["added"] = "added"; +})(DiffType || (DiffType = {})); +const REMOVED = 1; +const COMMON = 2; +const ADDED = 3; +function createCommon(A, B, reverse) { + const common = []; + if (A.length === 0 || B.length === 0) return []; + for(let i = 0; i < Math.min(A.length, B.length); i += 1){ + if (A[reverse ? A.length - i - 1 : i] === B[reverse ? B.length - i - 1 : i]) { + common.push(A[reverse ? A.length - i - 1 : i]); + } else { + return common; + } + } + return common; +} +function diff(A, B) { + const prefixCommon = createCommon(A, B); + const suffixCommon = createCommon(A.slice(prefixCommon.length), B.slice(prefixCommon.length), true).reverse(); + A = suffixCommon.length ? A.slice(prefixCommon.length, -suffixCommon.length) : A.slice(prefixCommon.length); + B = suffixCommon.length ? B.slice(prefixCommon.length, -suffixCommon.length) : B.slice(prefixCommon.length); + const swapped = B.length > A.length; + [A, B] = swapped ? [ + B, + A + ] : [ + A, + B + ]; + const M = A.length; + const N = B.length; + if (!M && !N && !suffixCommon.length && !prefixCommon.length) return []; + if (!N) { + return [ + ...prefixCommon.map((c)=>({ + type: DiffType.common, + value: c + })), + ...A.map((a)=>({ + type: swapped ? DiffType.added : DiffType.removed, + value: a + })), + ...suffixCommon.map((c)=>({ + type: DiffType.common, + value: c + })) + ]; + } + const offset = N; + const delta = M - N; + const size = M + N + 1; + const fp = Array.from({ + length: size + }, ()=>({ + y: -1, + id: -1 + })); + const routes = new Uint32Array((M * N + size + 1) * 2); + const diffTypesPtrOffset = routes.length / 2; + let ptr = 0; + let p = -1; + function backTrace(A, B, current, swapped) { + const M = A.length; + const N = B.length; + const result = []; + let a = M - 1; + let b = N - 1; + let j = routes[current.id]; + let type = routes[current.id + diffTypesPtrOffset]; + while(true){ + if (!j && !type) break; + const prev = j; + if (type === 1) { + result.unshift({ + type: swapped ? DiffType.removed : DiffType.added, + value: B[b] + }); + b -= 1; + } else if (type === 3) { + result.unshift({ + type: swapped ? DiffType.added : DiffType.removed, + value: A[a] + }); + a -= 1; + } else { + result.unshift({ + type: DiffType.common, + value: A[a] + }); + a -= 1; + b -= 1; + } + j = routes[prev]; + type = routes[prev + diffTypesPtrOffset]; + } + return result; + } + function createFP(slide, down, k, M) { + if (slide && slide.y === -1 && down && down.y === -1) { + return { + y: 0, + id: 0 + }; + } + if (down && down.y === -1 || k === M || (slide && slide.y) > (down && down.y) + 1) { + const prev = slide.id; + ptr++; + routes[ptr] = prev; + routes[ptr + diffTypesPtrOffset] = ADDED; + return { + y: slide.y, + id: ptr + }; + } else { + const prev1 = down.id; + ptr++; + routes[ptr] = prev1; + routes[ptr + diffTypesPtrOffset] = REMOVED; + return { + y: down.y + 1, + id: ptr + }; + } + } + function snake(k, slide, down, _offset, A, B) { + const M = A.length; + const N = B.length; + if (k < -N || M < k) return { + y: -1, + id: -1 + }; + const fp = createFP(slide, down, k, M); + while(fp.y + k < M && fp.y < N && A[fp.y + k] === B[fp.y]){ + const prev = fp.id; + ptr++; + fp.id = ptr; + fp.y += 1; + routes[ptr] = prev; + routes[ptr + diffTypesPtrOffset] = COMMON; + } + return fp; + } + while(fp[delta + offset].y < N){ + p = p + 1; + for(let k = -p; k < delta; ++k){ + fp[k + offset] = snake(k, fp[k - 1 + offset], fp[k + 1 + offset], offset, A, B); + } + for(let k1 = delta + p; k1 > delta; --k1){ + fp[k1 + offset] = snake(k1, fp[k1 - 1 + offset], fp[k1 + 1 + offset], offset, A, B); + } + fp[delta + offset] = snake(delta, fp[delta - 1 + offset], fp[delta + 1 + offset], offset, A, B); + } + return [ + ...prefixCommon.map((c)=>({ + type: DiffType.common, + value: c + })), + ...backTrace(A, B, fp[delta + offset], swapped), + ...suffixCommon.map((c)=>({ + type: DiffType.common, + value: c + })) + ]; +} +function diffstr(A, B) { + function unescape(string) { + return string.replaceAll("\b", "\\b").replaceAll("\f", "\\f").replaceAll("\t", "\\t").replaceAll("\v", "\\v").replaceAll(/\r\n|\r|\n/g, (str)=>str === "\r" ? "\\r" : str === "\n" ? "\\n\n" : "\\r\\n\r\n"); + } + function tokenize(string, { wordDiff =false } = {}) { + if (wordDiff) { + const tokens = string.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); + const words = /^[a-zA-Z\u{C0}-\u{FF}\u{D8}-\u{F6}\u{F8}-\u{2C6}\u{2C8}-\u{2D7}\u{2DE}-\u{2FF}\u{1E00}-\u{1EFF}]+$/u; + for(let i = 0; i < tokens.length - 1; i++){ + if (!tokens[i + 1] && tokens[i + 2] && words.test(tokens[i]) && words.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + return tokens.filter((token)=>token); + } else { + const tokens1 = [], lines = string.split(/(\n|\r\n)/); + if (!lines[lines.length - 1]) { + lines.pop(); + } + for(let i1 = 0; i1 < lines.length; i1++){ + if (i1 % 2) { + tokens1[tokens1.length - 1] += lines[i1]; + } else { + tokens1.push(lines[i1]); + } + } + return tokens1; + } + } + function createDetails(line, tokens) { + return tokens.filter(({ type })=>type === line.type || type === DiffType.common).map((result, i, t)=>{ + if (result.type === DiffType.common && t[i - 1] && t[i - 1]?.type === t[i + 1]?.type && /\s+/.test(result.value)) { + result.type = t[i - 1].type; + } + return result; + }); + } + const diffResult = diff(tokenize(`${unescape(A)}\n`), tokenize(`${unescape(B)}\n`)); + const added = [], removed = []; + for (const result of diffResult){ + if (result.type === DiffType.added) { + added.push(result); + } + if (result.type === DiffType.removed) { + removed.push(result); + } + } + const aLines = added.length < removed.length ? added : removed; + const bLines = aLines === removed ? added : removed; + for (const a of aLines){ + let tokens = [], b; + while(bLines.length){ + b = bLines.shift(); + tokens = diff(tokenize(a.value, { + wordDiff: true + }), tokenize(b?.value ?? "", { + wordDiff: true + })); + if (tokens.some(({ type , value })=>type === DiffType.common && value.trim().length)) { + break; + } + } + a.details = createDetails(a, tokens); + if (b) { + b.details = createDetails(b, tokens); + } + } + return diffResult; +} +function createColor(diffType, { background =false } = {}) { + background = false; + switch(diffType){ + case DiffType.added: + return (s)=>background ? bgGreen(white(s)) : green(bold(s)); + case DiffType.removed: + return (s)=>background ? bgRed(white(s)) : red(bold(s)); + default: + return white; + } +} +function createSign(diffType) { + switch(diffType){ + case DiffType.added: + return "+ "; + case DiffType.removed: + return "- "; + default: + return " "; + } +} +function buildMessage(diffResult, { stringDiff =false } = {}) { + const messages = [], diffMessages = []; + messages.push(""); + messages.push(""); + messages.push(` ${gray(bold("[Diff]"))} ${red(bold("Actual"))} / ${green(bold("Expected"))}`); + messages.push(""); + messages.push(""); + diffResult.forEach((result)=>{ + const c = createColor(result.type); + const line = result.details?.map((detail)=>detail.type !== DiffType.common ? createColor(detail.type, { + background: true + })(detail.value) : detail.value).join("") ?? result.value; + diffMessages.push(c(`${createSign(result.type)}${line}`)); + }); + messages.push(...stringDiff ? [ + diffMessages.join("") + ] : diffMessages); + messages.push(""); + return messages; +} +function format(v) { + const { Deno } = globalThis; + return typeof Deno?.inspect === "function" ? Deno.inspect(v, { + depth: Infinity, + sorted: true, + trailingComma: true, + compact: false, + iterableLimit: Infinity, + getters: true + }) : `"${String(v).replace(/(?=["\\])/g, "\\")}"`; +} +const CAN_NOT_DISPLAY = "[Cannot display]"; +class AssertionError extends Error { + name = "AssertionError"; + constructor(message){ + super(message); + } +} +function isKeyedCollection(x) { + return [ + Symbol.iterator, + "size" + ].every((k)=>k in x); +} +function equal(c, d) { + const seen = new Map(); + return function compare(a, b) { + if (a && b && (a instanceof RegExp && b instanceof RegExp || a instanceof URL && b instanceof URL)) { + return String(a) === String(b); + } + if (a instanceof Date && b instanceof Date) { + const aTime = a.getTime(); + const bTime = b.getTime(); + if (Number.isNaN(aTime) && Number.isNaN(bTime)) { + return true; + } + return aTime === bTime; + } + if (typeof a === "number" && typeof b === "number") { + return Number.isNaN(a) && Number.isNaN(b) || a === b; + } + if (Object.is(a, b)) { + return true; + } + if (a && typeof a === "object" && b && typeof b === "object") { + if (a && b && !constructorsEqual(a, b)) { + return false; + } + if (a instanceof WeakMap || b instanceof WeakMap) { + if (!(a instanceof WeakMap && b instanceof WeakMap)) return false; + throw new TypeError("cannot compare WeakMap instances"); + } + if (a instanceof WeakSet || b instanceof WeakSet) { + if (!(a instanceof WeakSet && b instanceof WeakSet)) return false; + throw new TypeError("cannot compare WeakSet instances"); + } + if (seen.get(a) === b) { + return true; + } + if (Object.keys(a || {}).length !== Object.keys(b || {}).length) { + return false; + } + seen.set(a, b); + if (isKeyedCollection(a) && isKeyedCollection(b)) { + if (a.size !== b.size) { + return false; + } + let unmatchedEntries = a.size; + for (const [aKey, aValue] of a.entries()){ + for (const [bKey, bValue] of b.entries()){ + if (aKey === aValue && bKey === bValue && compare(aKey, bKey) || compare(aKey, bKey) && compare(aValue, bValue)) { + unmatchedEntries--; + break; + } + } + } + return unmatchedEntries === 0; + } + const merged = { + ...a, + ...b + }; + for (const key of [ + ...Object.getOwnPropertyNames(merged), + ...Object.getOwnPropertySymbols(merged) + ]){ + if (!compare(a && a[key], b && b[key])) { + return false; + } + if (key in a && !(key in b) || key in b && !(key in a)) { + return false; + } + } + if (a instanceof WeakRef || b instanceof WeakRef) { + if (!(a instanceof WeakRef && b instanceof WeakRef)) return false; + return compare(a.deref(), b.deref()); + } + return true; + } + return false; + }(c, d); +} +function constructorsEqual(a, b) { + return a.constructor === b.constructor || a.constructor === Object && !b.constructor || !a.constructor && b.constructor === Object; +} +function assert(expr, msg = "") { + if (!expr) { + throw new AssertionError(msg); + } +} +function assertFalse(expr, msg = "") { + if (expr) { + throw new AssertionError(msg); + } +} +function assertEquals(actual, expected, msg) { + if (equal(actual, expected)) { + return; + } + let message = ""; + const actualString = format(actual); + const expectedString = format(expected); + try { + const stringDiff = typeof actual === "string" && typeof expected === "string"; + const diffResult = stringDiff ? diffstr(actual, expected) : diff(actualString.split("\n"), expectedString.split("\n")); + const diffMsg = buildMessage(diffResult, { + stringDiff + }).join("\n"); + message = `Values are not equal:\n${diffMsg}`; + } catch { + message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; + } + if (msg) { + message = msg; + } + throw new AssertionError(message); +} +function assertNotEquals(actual, expected, msg) { + if (!equal(actual, expected)) { + return; + } + let actualString; + let expectedString; + try { + actualString = String(actual); + } catch { + actualString = "[Cannot display]"; + } + try { + expectedString = String(expected); + } catch { + expectedString = "[Cannot display]"; + } + if (!msg) { + msg = `actual: ${actualString} expected not to be: ${expectedString}`; + } + throw new AssertionError(msg); +} +function assertStrictEquals(actual, expected, msg) { + if (Object.is(actual, expected)) { + return; + } + let message; + if (msg) { + message = msg; + } else { + const actualString = format(actual); + const expectedString = format(expected); + if (actualString === expectedString) { + const withOffset = actualString.split("\n").map((l)=>` ${l}`).join("\n"); + message = `Values have the same structure but are not reference-equal:\n\n${red(withOffset)}\n`; + } else { + try { + const stringDiff = typeof actual === "string" && typeof expected === "string"; + const diffResult = stringDiff ? diffstr(actual, expected) : diff(actualString.split("\n"), expectedString.split("\n")); + const diffMsg = buildMessage(diffResult, { + stringDiff + }).join("\n"); + message = `Values are not strictly equal:\n${diffMsg}`; + } catch { + message = `\n${red(CAN_NOT_DISPLAY)} + \n\n`; + } + } + } + throw new AssertionError(message); +} +function assertNotStrictEquals(actual, expected, msg) { + if (!Object.is(actual, expected)) { + return; + } + throw new AssertionError(msg ?? `Expected "actual" to be strictly unequal to: ${format(actual)}\n`); +} +function assertAlmostEquals(actual, expected, tolerance = 1e-7, msg) { + if (Object.is(actual, expected)) { + return; + } + const delta = Math.abs(expected - actual); + if (delta <= tolerance) { + return; + } + const f = (n)=>Number.isInteger(n) ? n : n.toExponential(); + throw new AssertionError(msg ?? `actual: "${f(actual)}" expected to be close to "${f(expected)}": \ +delta "${f(delta)}" is greater than "${f(tolerance)}"`); +} +function assertInstanceOf(actual, expectedType, msg = "") { + if (!msg) { + const expectedTypeStr = expectedType.name; + let actualTypeStr = ""; + if (actual === null) { + actualTypeStr = "null"; + } else if (actual === undefined) { + actualTypeStr = "undefined"; + } else if (typeof actual === "object") { + actualTypeStr = actual.constructor?.name ?? "Object"; + } else { + actualTypeStr = typeof actual; + } + if (expectedTypeStr == actualTypeStr) { + msg = `Expected object to be an instance of "${expectedTypeStr}".`; + } else if (actualTypeStr == "function") { + msg = `Expected object to be an instance of "${expectedTypeStr}" but was not an instanced object.`; + } else { + msg = `Expected object to be an instance of "${expectedTypeStr}" but was "${actualTypeStr}".`; + } + } + assert(actual instanceof expectedType, msg); +} +function assertNotInstanceOf(actual, unexpectedType, msg = `Expected object to not be an instance of "${typeof unexpectedType}"`) { + assertFalse(actual instanceof unexpectedType, msg); +} +function assertExists(actual, msg) { + if (actual === undefined || actual === null) { + if (!msg) { + msg = `actual: "${actual}" expected to not be null or undefined`; + } + throw new AssertionError(msg); + } +} +function assertStringIncludes(actual, expected, msg) { + if (!actual.includes(expected)) { + if (!msg) { + msg = `actual: "${actual}" expected to contain: "${expected}"`; + } + throw new AssertionError(msg); + } +} +function assertArrayIncludes(actual, expected, msg) { + const missing = []; + for(let i = 0; i < expected.length; i++){ + let found = false; + for(let j = 0; j < actual.length; j++){ + if (equal(expected[i], actual[j])) { + found = true; + break; + } + } + if (!found) { + missing.push(expected[i]); + } + } + if (missing.length === 0) { + return; + } + if (!msg) { + msg = `actual: "${format(actual)}" expected to include: "${format(expected)}"\nmissing: ${format(missing)}`; + } + throw new AssertionError(msg); +} +function assertMatch(actual, expected, msg) { + if (!expected.test(actual)) { + if (!msg) { + msg = `actual: "${actual}" expected to match: "${expected}"`; + } + throw new AssertionError(msg); + } +} +function assertNotMatch(actual, expected, msg) { + if (expected.test(actual)) { + if (!msg) { + msg = `actual: "${actual}" expected to not match: "${expected}"`; + } + throw new AssertionError(msg); + } +} +function assertObjectMatch(actual, expected) { + function filter(a, b) { + const seen = new WeakMap(); + return fn(a, b); + function fn(a, b) { + if (seen.has(a) && seen.get(a) === b) { + return a; + } + seen.set(a, b); + const filtered = {}; + const entries = [ + ...Object.getOwnPropertyNames(a), + ...Object.getOwnPropertySymbols(a) + ].filter((key)=>key in b).map((key)=>[ + key, + a[key] + ]); + for (const [key, value] of entries){ + if (Array.isArray(value)) { + const subset = b[key]; + if (Array.isArray(subset)) { + filtered[key] = fn({ + ...value + }, { + ...subset + }); + continue; + } + } else if (value instanceof RegExp) { + filtered[key] = value; + continue; + } else if (typeof value === "object") { + const subset1 = b[key]; + if (typeof subset1 === "object" && subset1) { + if (value instanceof Map && subset1 instanceof Map) { + filtered[key] = new Map([ + ...value + ].filter(([k])=>subset1.has(k)).map(([k, v])=>[ + k, + typeof v === "object" ? fn(v, subset1.get(k)) : v + ])); + continue; + } + if (value instanceof Set && subset1 instanceof Set) { + filtered[key] = new Set([ + ...value + ].filter((v)=>subset1.has(v))); + continue; + } + filtered[key] = fn(value, subset1); + continue; + } + } + filtered[key] = value; + } + return filtered; + } + } + return assertEquals(filter(actual, expected), filter(expected, expected)); +} +function fail(msg) { + assert(false, `Failed assertion${msg ? `: ${msg}` : "."}`); +} +function assertIsError(error, ErrorClass, msgIncludes, msg) { + if (error instanceof Error === false) { + throw new AssertionError(`Expected "error" to be an Error object.`); + } + if (ErrorClass && !(error instanceof ErrorClass)) { + msg = `Expected error to be instance of "${ErrorClass.name}", but was "${typeof error === "object" ? error?.constructor?.name : "[not an object]"}"${msg ? `: ${msg}` : "."}`; + throw new AssertionError(msg); + } + if (msgIncludes && (!(error instanceof Error) || !stripColor(error.message).includes(stripColor(msgIncludes)))) { + msg = `Expected error message to include "${msgIncludes}", but got "${error instanceof Error ? error.message : "[not an Error]"}"${msg ? `: ${msg}` : "."}`; + throw new AssertionError(msg); + } +} +function assertThrows(fn, errorClassOrMsg, msgIncludesOrMsg, msg) { + let ErrorClass = undefined; + let msgIncludes = undefined; + let err; + if (typeof errorClassOrMsg !== "string") { + if (errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype) { + ErrorClass = errorClassOrMsg; + msgIncludes = msgIncludesOrMsg; + } else { + msg = msgIncludesOrMsg; + } + } else { + msg = errorClassOrMsg; + } + let doesThrow = false; + const msgToAppendToError = msg ? `: ${msg}` : "."; + try { + fn(); + } catch (error) { + if (ErrorClass) { + if (error instanceof Error === false) { + throw new AssertionError("A non-Error object was thrown."); + } + assertIsError(error, ErrorClass, msgIncludes, msg); + } + err = error; + doesThrow = true; + } + if (!doesThrow) { + msg = `Expected function to throw${msgToAppendToError}`; + throw new AssertionError(msg); + } + return err; +} +async function assertRejects(fn, errorClassOrMsg, msgIncludesOrMsg, msg) { + let ErrorClass = undefined; + let msgIncludes = undefined; + let err; + if (typeof errorClassOrMsg !== "string") { + if (errorClassOrMsg === undefined || errorClassOrMsg.prototype instanceof Error || errorClassOrMsg.prototype === Error.prototype) { + ErrorClass = errorClassOrMsg; + msgIncludes = msgIncludesOrMsg; + } + } else { + msg = errorClassOrMsg; + } + let doesThrow = false; + let isPromiseReturned = false; + const msgToAppendToError = msg ? `: ${msg}` : "."; + try { + const possiblePromise = fn(); + if (possiblePromise && typeof possiblePromise === "object" && typeof possiblePromise.then === "function") { + isPromiseReturned = true; + await possiblePromise; + } + } catch (error) { + if (!isPromiseReturned) { + throw new AssertionError(`Function throws when expected to reject${msgToAppendToError}`); + } + if (ErrorClass) { + if (error instanceof Error === false) { + throw new AssertionError("A non-Error object was rejected."); + } + assertIsError(error, ErrorClass, msgIncludes, msg); + } + err = error; + doesThrow = true; + } + if (!doesThrow) { + throw new AssertionError(`Expected function to reject${msgToAppendToError}`); + } + return err; +} +function unimplemented(msg) { + throw new AssertionError(msg || "unimplemented"); +} +function unreachable() { + throw new AssertionError("unreachable"); +} +export { AssertionError as AssertionError }; +export { equal as equal }; +export { assert as assert }; +export { assertFalse as assertFalse }; +export { assertEquals as assertEquals }; +export { assertNotEquals as assertNotEquals }; +export { assertStrictEquals as assertStrictEquals }; +export { assertNotStrictEquals as assertNotStrictEquals }; +export { assertAlmostEquals as assertAlmostEquals }; +export { assertInstanceOf as assertInstanceOf }; +export { assertNotInstanceOf as assertNotInstanceOf }; +export { assertExists as assertExists }; +export { assertStringIncludes as assertStringIncludes }; +export { assertArrayIncludes as assertArrayIncludes }; +export { assertMatch as assertMatch }; +export { assertNotMatch as assertNotMatch }; +export { assertObjectMatch as assertObjectMatch }; +export { fail as fail }; +export { assertIsError as assertIsError }; +export { assertThrows as assertThrows }; +export { assertRejects as assertRejects }; +export { unimplemented as unimplemented }; +export { unreachable as unreachable }; + diff --git a/node_modules/tinycolor2/dist/tinycolor-min.js b/node_modules/tinycolor2/dist/tinycolor-min.js new file mode 100644 index 0000000000000000000000000000000000000000..14389aa181f3dd58f338ea2c53c92cc9f01ea629 --- /dev/null +++ b/node_modules/tinycolor2/dist/tinycolor-min.js @@ -0,0 +1,5 @@ +// This file is autogenerated. +// It's here at this path for backwards compatibility for links to it +// but the npm package now exports both CJS and ESM. +// See https://github.com/bgrins/TinyColor/ for instructions. + !function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):(t="undefined"!=typeof globalThis?globalThis:t||self).tinycolor=r()}(this,(function(){"use strict";function t(r){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(r)}var r=/^\s+/,e=/\s+$/;function n(a,i){if(i=i||{},(a=a||"")instanceof n)return a;if(!(this instanceof n))return new n(a,i);var o=function(n){var a={r:0,g:0,b:0},i=1,o=null,h=null,s=null,f=!1,u=!1;"string"==typeof n&&(n=function(t){t=t.replace(r,"").replace(e,"").toLowerCase();var n,a=!1;if(y[t])t=y[t],a=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};if(n=T.rgb.exec(t))return{r:n[1],g:n[2],b:n[3]};if(n=T.rgba.exec(t))return{r:n[1],g:n[2],b:n[3],a:n[4]};if(n=T.hsl.exec(t))return{h:n[1],s:n[2],l:n[3]};if(n=T.hsla.exec(t))return{h:n[1],s:n[2],l:n[3],a:n[4]};if(n=T.hsv.exec(t))return{h:n[1],s:n[2],v:n[3]};if(n=T.hsva.exec(t))return{h:n[1],s:n[2],v:n[3],a:n[4]};if(n=T.hex8.exec(t))return{r:w(n[1]),g:w(n[2]),b:w(n[3]),a:F(n[4]),format:a?"name":"hex8"};if(n=T.hex6.exec(t))return{r:w(n[1]),g:w(n[2]),b:w(n[3]),format:a?"name":"hex"};if(n=T.hex4.exec(t))return{r:w(n[1]+""+n[1]),g:w(n[2]+""+n[2]),b:w(n[3]+""+n[3]),a:F(n[4]+""+n[4]),format:a?"name":"hex8"};if(n=T.hex3.exec(t))return{r:w(n[1]+""+n[1]),g:w(n[2]+""+n[2]),b:w(n[3]+""+n[3]),format:a?"name":"hex"};return!1}(n));"object"==t(n)&&(E(n.r)&&E(n.g)&&E(n.b)?(l=n.r,c=n.g,d=n.b,a={r:255*A(l,255),g:255*A(c,255),b:255*A(d,255)},f=!0,u="%"===String(n.r).substr(-1)?"prgb":"rgb"):E(n.h)&&E(n.s)&&E(n.v)?(o=H(n.s),h=H(n.v),a=function(t,r,e){t=6*A(t,360),r=A(r,100),e=A(e,100);var n=Math.floor(t),a=t-n,i=e*(1-r),o=e*(1-a*r),h=e*(1-(1-a)*r),s=n%6,f=[e,o,i,i,h,e][s],u=[h,e,e,o,i,i][s],l=[i,i,h,e,e,o][s];return{r:255*f,g:255*u,b:255*l}}(n.h,o,h),f=!0,u="hsv"):E(n.h)&&E(n.s)&&E(n.l)&&(o=H(n.s),s=H(n.l),a=function(t,r,e){var n,a,i;function o(t,r,e){return e<0&&(e+=1),e>1&&(e-=1),e<1/6?t+6*(r-t)*e:e<.5?r:e<2/3?t+(r-t)*(2/3-e)*6:t}if(t=A(t,360),r=A(r,100),e=A(e,100),0===r)n=a=i=e;else{var h=e<.5?e*(1+r):e+r-e*r,s=2*e-h;n=o(s,h,t+1/3),a=o(s,h,t),i=o(s,h,t-1/3)}return{r:255*n,g:255*a,b:255*i}}(n.h,o,s),f=!0,u="hsl"),n.hasOwnProperty("a")&&(i=n.a));var l,c,d;return i=x(i),{ok:f,format:n.format||u,r:Math.min(255,Math.max(a.r,0)),g:Math.min(255,Math.max(a.g,0)),b:Math.min(255,Math.max(a.b,0)),a:i}}(a);this._originalInput=a,this._r=o.r,this._g=o.g,this._b=o.b,this._a=o.a,this._roundA=Math.round(100*this._a)/100,this._format=i.format||o.format,this._gradientType=i.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=o.ok}function a(t,r,e){t=A(t,255),r=A(r,255),e=A(e,255);var n,a,i=Math.max(t,r,e),o=Math.min(t,r,e),h=(i+o)/2;if(i==o)n=a=0;else{var s=i-o;switch(a=h>.5?s/(2-i-o):s/(i+o),i){case t:n=(r-e)/s+(r>1)+720)%360;--r;)a.h=(a.h+i)%360,o.push(n(a));return o}function v(t,r){r=r||6;for(var e=n(t).toHsv(),a=e.h,i=e.s,o=e.v,h=[],s=1/r;r--;)h.push(n({h:a,s:i,v:o})),o=(o+s)%1;return h}n.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,r,e,n=this.toRgb();return t=n.r/255,r=n.g/255,e=n.b/255,.2126*(t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4))+.7152*(r<=.03928?r/12.92:Math.pow((r+.055)/1.055,2.4))+.0722*(e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4))},setAlpha:function(t){return this._a=x(t),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var t=i(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=i(this._r,this._g,this._b),r=Math.round(360*t.h),e=Math.round(100*t.s),n=Math.round(100*t.v);return 1==this._a?"hsv("+r+", "+e+"%, "+n+"%)":"hsva("+r+", "+e+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),r=Math.round(360*t.h),e=Math.round(100*t.s),n=Math.round(100*t.l);return 1==this._a?"hsl("+r+", "+e+"%, "+n+"%)":"hsla("+r+", "+e+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return o(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(t){return function(t,r,e,n,a){var i=[S(Math.round(t).toString(16)),S(Math.round(r).toString(16)),S(Math.round(e).toString(16)),S(R(n))];if(a&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)&&i[3].charAt(0)==i[3].charAt(1))return i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0)+i[3].charAt(0);return i.join("")}(this._r,this._g,this._b,this._a,t)},toHex8String:function(t){return"#"+this.toHex8(t)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+")":"rgba("+Math.round(this._r)+", "+Math.round(this._g)+", "+Math.round(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:Math.round(100*A(this._r,255))+"%",g:Math.round(100*A(this._g,255))+"%",b:Math.round(100*A(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+Math.round(100*A(this._r,255))+"%, "+Math.round(100*A(this._g,255))+"%, "+Math.round(100*A(this._b,255))+"%)":"rgba("+Math.round(100*A(this._r,255))+"%, "+Math.round(100*A(this._g,255))+"%, "+Math.round(100*A(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":!(this._a<1)&&(M[o(this._r,this._g,this._b,!0)]||!1)},toFilter:function(t){var r="#"+h(this._r,this._g,this._b,this._a),e=r,a=this._gradientType?"GradientType = 1, ":"";if(t){var i=n(t);e="#"+h(i._r,i._g,i._b,i._a)}return"progid:DXImageTransform.Microsoft.gradient("+a+"startColorstr="+r+",endColorstr="+e+")"},toString:function(t){var r=!!t;t=t||this._format;var e=!1,n=this._a<1&&this._a>=0;return r||!n||"hex"!==t&&"hex6"!==t&&"hex3"!==t&&"hex4"!==t&&"hex8"!==t&&"name"!==t?("rgb"===t&&(e=this.toRgbString()),"prgb"===t&&(e=this.toPercentageRgbString()),"hex"!==t&&"hex6"!==t||(e=this.toHexString()),"hex3"===t&&(e=this.toHexString(!0)),"hex4"===t&&(e=this.toHex8String(!0)),"hex8"===t&&(e=this.toHex8String()),"name"===t&&(e=this.toName()),"hsl"===t&&(e=this.toHslString()),"hsv"===t&&(e=this.toHsvString()),e||this.toHexString()):"name"===t&&0===this._a?this.toName():this.toRgbString()},clone:function(){return n(this.toString())},_applyModification:function(t,r){var e=t.apply(null,[this].concat([].slice.call(r)));return this._r=e._r,this._g=e._g,this._b=e._b,this.setAlpha(e._a),this},lighten:function(){return this._applyModification(l,arguments)},brighten:function(){return this._applyModification(c,arguments)},darken:function(){return this._applyModification(d,arguments)},desaturate:function(){return this._applyModification(s,arguments)},saturate:function(){return this._applyModification(f,arguments)},greyscale:function(){return this._applyModification(u,arguments)},spin:function(){return this._applyModification(g,arguments)},_applyCombination:function(t,r){return t.apply(null,[this].concat([].slice.call(r)))},analogous:function(){return this._applyCombination(_,arguments)},complement:function(){return this._applyCombination(b,arguments)},monochromatic:function(){return this._applyCombination(v,arguments)},splitcomplement:function(){return this._applyCombination(p,arguments)},triad:function(){return this._applyCombination(m,[3])},tetrad:function(){return this._applyCombination(m,[4])}},n.fromRatio=function(r,e){if("object"==t(r)){var a={};for(var i in r)r.hasOwnProperty(i)&&(a[i]="a"===i?r[i]:H(r[i]));r=a}return n(r,e)},n.equals=function(t,r){return!(!t||!r)&&n(t).toRgbString()==n(r).toRgbString()},n.random=function(){return n.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})},n.mix=function(t,r,e){e=0===e?0:e||50;var a=n(t).toRgb(),i=n(r).toRgb(),o=e/100;return n({r:(i.r-a.r)*o+a.r,g:(i.g-a.g)*o+a.g,b:(i.b-a.b)*o+a.b,a:(i.a-a.a)*o+a.a})},n.readability=function(t,r){var e=n(t),a=n(r);return(Math.max(e.getLuminance(),a.getLuminance())+.05)/(Math.min(e.getLuminance(),a.getLuminance())+.05)},n.isReadable=function(t,r,e){var a,i,o=n.readability(t,r);switch(i=!1,(a=function(t){var r,e;r=((t=t||{level:"AA",size:"small"}).level||"AA").toUpperCase(),e=(t.size||"small").toLowerCase(),"AA"!==r&&"AAA"!==r&&(r="AA");"small"!==e&&"large"!==e&&(e="small");return{level:r,size:e}}(e)).level+a.size){case"AAsmall":case"AAAlarge":i=o>=4.5;break;case"AAlarge":i=o>=3;break;case"AAAsmall":i=o>=7}return i},n.mostReadable=function(t,r,e){var a,i,o,h,s=null,f=0;i=(e=e||{}).includeFallbackColors,o=e.level,h=e.size;for(var u=0;uf&&(f=a,s=n(r[u]));return n.isReadable(t,s,{level:o,size:h})||!i?s:(e.includeFallbackColors=!1,n.mostReadable(t,["#fff","#000"],e))};var y=n.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},M=n.hexNames=function(t){var r={};for(var e in t)t.hasOwnProperty(e)&&(r[t[e]]=e);return r}(y);function x(t){return t=parseFloat(t),(isNaN(t)||t<0||t>1)&&(t=1),t}function A(t,r){(function(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)})(t)&&(t="100%");var e=function(t){return"string"==typeof t&&-1!=t.indexOf("%")}(t);return t=Math.min(r,Math.max(0,parseFloat(t))),e&&(t=parseInt(t*r,10)/100),Math.abs(t-r)<1e-6?1:t%r/parseFloat(r)}function k(t){return Math.min(1,Math.max(0,t))}function w(t){return parseInt(t,16)}function S(t){return 1==t.length?"0"+t:""+t}function H(t){return t<=1&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function F(t){return w(t)/255}var C,q,N,T=(q="[\\s|\\(]+("+(C="(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)")+")[,|\\s]+("+C+")[,|\\s]+("+C+")\\s*\\)?",N="[\\s|\\(]+("+C+")[,|\\s]+("+C+")[,|\\s]+("+C+")[,|\\s]+("+C+")\\s*\\)?",{CSS_UNIT:new RegExp(C),rgb:new RegExp("rgb"+q),rgba:new RegExp("rgba"+N),hsl:new RegExp("hsl"+q),hsla:new RegExp("hsla"+N),hsv:new RegExp("hsv"+q),hsva:new RegExp("hsva"+N),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/});function E(t){return!!T.CSS_UNIT.exec(t)}return n})); \ No newline at end of file diff --git a/node_modules/tinycolor2/esm/package.json b/node_modules/tinycolor2/esm/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbc1ca591c0557e35b6004aeba250e6a70b56e3 --- /dev/null +++ b/node_modules/tinycolor2/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} diff --git a/node_modules/tinycolor2/esm/test.js b/node_modules/tinycolor2/esm/test.js new file mode 100644 index 0000000000000000000000000000000000000000..4f02b0ce91a1732670f34f6f231f1f9b2adbac3a --- /dev/null +++ b/node_modules/tinycolor2/esm/test.js @@ -0,0 +1,2189 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +import tinycolor from "./tinycolor.js"; +import { Deno, testDefinitions } from "@deno/shim-deno-test"; +const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" +); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} + +// TEST_BEGINS_HERE + +Deno.test("TinyColor initialization", function () { + assert( + typeof tinycolor != "undefined", + "tinycolor is initialized on the page" + ); + assert( + typeof tinycolor("red") == "object", + "tinycolor is able to be instantiated" + ); + + var r = tinycolor("red"); + assert( + tinycolor(r) === r, + "when given a tinycolor instance, tinycolor() returns it" + ); + assert( + new tinycolor(r) === r, + "when given a tinycolor instance, new tinycolor() returns it" + ); + assertEquals( + tinycolor("red", { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0 }, { format: "hex" }).toString(), + "#ff0000", + "tinycolor options are being parsed" + ); + + var obj = { h: 180, s: 0.5, l: 0.5 }; + var color = tinycolor(obj); + assert( + obj.s === 0.5, + "when given an object, the original object is not modified" + ); +}); + +Deno.test("Original input", function () { + var colorRgbUp = "RGB(39, 39, 39)"; + var colorRgbLow = "rgb(39, 39, 39)"; + var colorRgbMix = "RgB(39, 39, 39)"; + var tinycolorObj = tinycolor(colorRgbMix); + var inputObj = { r: 100, g: 100, b: 100 }; + var r = tinycolor("red"); + + assert( + tinycolor(colorRgbLow).getOriginalInput() === colorRgbLow, + "original lowercase input is returned" + ); + assert( + tinycolor(colorRgbUp).getOriginalInput() === colorRgbUp, + "original uppercase input is returned" + ); + assert( + tinycolor(colorRgbMix).getOriginalInput() === colorRgbMix, + "original mixed input is returned" + ); + assert( + tinycolor(tinycolorObj).getOriginalInput() === colorRgbMix, + "when given a tinycolor instance, the color string is returned" + ); + assert( + tinycolor(inputObj).getOriginalInput() === inputObj, + "when given an object, the object is returned" + ); + assert( + new tinycolor("").getOriginalInput() === "", + "when given an empty string, an empty string is returned" + ); + assert( + new tinycolor(null).getOriginalInput() === "", + "when given a null value, an empty string is returned" + ); +}); + +Deno.test("Cloning color", function () { + var originalColor = tinycolor("red"); + var originalColorRgbString = originalColor.toRgbString(); + + var clonedColor = originalColor.clone(); + assert( + clonedColor.toRgbString() === originalColor.toRgbString(), + "cloned color is identical" + ); + + clonedColor.setAlpha(0.5); + assert( + clonedColor.toRgbString() !== originalColor.toRgbString(), + "cloned color is changing independently from original color" + ); + assert( + originalColorRgbString === originalColor.toRgbString(), + "original color was not changed by cloned color change" + ); +}); +Deno.test("Random color", function () { + var randomColor = tinycolor.random(); + assertEquals(randomColor.getAlpha(), 1); + assertEquals(randomColor.getFormat(), "prgb"); + + randomColor.setAlpha(0.5); + assertEquals(randomColor.toHex8String().slice(-2), "80"); +}); + +// Taken from convertWikipediaColors.html +var conversions = [ + { + hex: "#FFFFFF", + hex8: "#FFFFFFFF", + rgb: { r: "100.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "0", s: "0.000", v: "1.000" }, + hsl: { h: "0", s: "0.000", l: "1.000" }, + }, + { + hex: "#808080", + hex8: "#808080FF", + rgb: { r: "050.0%", g: "050.0%", b: "050.0%" }, + hsv: { h: "0", s: "0.000", v: "0.500" }, + hsl: { h: "0", s: "0.000", l: "0.500" }, + }, + { + hex: "#000000", + hex8: "#000000FF", + rgb: { r: "000.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0", s: "0.000", v: "0.000" }, + hsl: { h: "0", s: "0.000", l: "0.000" }, + }, + { + hex: "#FF0000", + hex8: "#FF0000FF", + rgb: { r: "100.0%", g: "000.0%", b: "000.0%" }, + hsv: { h: "0.0", s: "1.000", v: "1.000" }, + hsl: { h: "0.0", s: "1.000", l: "0.500" }, + }, + { + hex: "#BFBF00", + hex8: "#BFBF00FF", + rgb: { r: "075.0%", g: "075.0%", b: "000.0%" }, + hsv: { h: "60.0", s: "1.000", v: "0.750" }, + hsl: { h: "60.0", s: "1.000", l: "0.375" }, + }, + { + hex: "#008000", + hex8: "#008000FF", + rgb: { r: "000.0%", g: "050.0%", b: "000.0%" }, + hsv: { h: "120.0", s: "1.000", v: "0.500" }, + hsl: { h: "120.0", s: "1.000", l: "0.250" }, + }, + { + hex: "#80FFFF", + hex8: "#80FFFFFF", + rgb: { r: "050.0%", g: "100.0%", b: "100.0%" }, + hsv: { h: "180.0", s: "0.500", v: "1.000" }, + hsl: { h: "180.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#8080FF", + hex8: "#8080FFFF", + rgb: { r: "050.0%", g: "050.0%", b: "100.0%" }, + hsv: { h: "240.0", s: "0.500", v: "1.000" }, + hsl: { h: "240.0", s: "1.000", l: "0.750" }, + }, + { + hex: "#BF40BF", + hex8: "#BF40BFFF", + rgb: { r: "075.0%", g: "025.0%", b: "075.0%" }, + hsv: { h: "300.0", s: "0.667", v: "0.750" }, + hsl: { h: "300.0", s: "0.500", l: "0.500" }, + }, + { + hex: "#A0A424", + hex8: "#A0A424FF", + rgb: { r: "062.8%", g: "064.3%", b: "014.2%" }, + hsv: { h: "61.8", s: "0.779", v: "0.643" }, + hsl: { h: "61.8", s: "0.638", l: "0.393" }, + }, + { + hex: "#1EAC41", + hex8: "#1EAC41FF", + rgb: { r: "011.6%", g: "067.5%", b: "025.5%" }, + hsv: { h: "134.9", s: "0.828", v: "0.675" }, + hsl: { h: "134.9", s: "0.707", l: "0.396" }, + }, + { + hex: "#B430E5", + hex8: "#B430E5FF", + rgb: { r: "070.4%", g: "018.7%", b: "089.7%" }, + hsv: { h: "283.7", s: "0.792", v: "0.897" }, + hsl: { h: "283.7", s: "0.775", l: "0.542" }, + }, + { + hex: "#FEF888", + hex8: "#FEF888FF", + rgb: { r: "099.8%", g: "097.4%", b: "053.2%" }, + hsv: { h: "56.9", s: "0.467", v: "0.998" }, + hsl: { h: "56.9", s: "0.991", l: "0.765" }, + }, + { + hex: "#19CB97", + hex8: "#19CB97FF", + rgb: { r: "009.9%", g: "079.5%", b: "059.1%" }, + hsv: { h: "162.4", s: "0.875", v: "0.795" }, + hsl: { h: "162.4", s: "0.779", l: "0.447" }, + }, + { + hex: "#362698", + hex8: "#362698FF", + rgb: { r: "021.1%", g: "014.9%", b: "059.7%" }, + hsv: { h: "248.3", s: "0.750", v: "0.597" }, + hsl: { h: "248.3", s: "0.601", l: "0.373" }, + }, + { + hex: "#7E7EB8", + hex8: "#7E7EB8FF", + rgb: { r: "049.5%", g: "049.3%", b: "072.1%" }, + hsv: { h: "240.5", s: "0.316", v: "0.721" }, + hsl: { h: "240.5", s: "0.290", l: "0.607" }, + }, +]; + +Deno.test("Color Equality", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + + assert(true, tiny.isValid()); + assert( + true, + "Testing " + + c.hex + + ": " + + tiny.toRgbString() + + " " + + tiny.toPercentageRgbString() + + " " + + tiny.toHsvString() + + " " + + tiny.toHslString() + + " " + + tiny.toHexString() + + "Original: " + + JSON.stringify(c.rgb) + + " " + + JSON.stringify(c.hsv) + + " " + + JSON.stringify(c.hsl) + ); + assert(tinycolor.equals(c.rgb, c.hex), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hex8), "RGB equals hex " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsl), "RGB equals HSL " + c.hex); + assert(tinycolor.equals(c.rgb, c.hsv), "RGB equals HSV " + c.hex); + assert(tinycolor.equals(c.rgb, c.rgb), "RGB equals RGB " + c.hex); + + assert(tinycolor.equals(c.hex, c.hex), "hex equals hex " + c.hex); + assert(tinycolor.equals(c.hex, c.hex8), "hex equals hex8 " + c.hex); + assert(tinycolor.equals(c.hex, c.hsl), "hex equals HSL " + c.hex); + assert(tinycolor.equals(c.hex, c.hsv), "hex equals HSV " + c.hex); + + assert(tinycolor.equals(c.hsl, c.hsv), "HSL equals HSV " + c.hex); + } +}); + +Deno.test("With Ratio", function () { + assertEquals( + tinycolor.fromRatio({ r: 1, g: 1, b: 1 }).toHexString(), + "#ffffff", + "white" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 0.5 }).toRgbString(), + "rgba(255, 0, 0, 0.5)", + "alpha works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha = 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: 10 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha > 1 works when ratio is parsed" + ); + assertEquals( + tinycolor.fromRatio({ r: 1, g: 0, b: 0, a: -1 }).toRgbString(), + "rgb(255, 0, 0)", + "alpha < 1 works when ratio is parsed" + ); +}); + +Deno.test("Without Ratio", function () { + assertEquals( + tinycolor({ r: 1, g: 1, b: 1 }).toHexString(), + "#010101", + "010101" + ); + assertEquals( + tinycolor({ r: 0.1, g: 0.1, b: 0.1 }).toHexString(), + "#000000", + "000000" + ); + assertEquals(tinycolor("rgb .1 .1 .1").toHexString(), "#000000", "000000"); +}); + +Deno.test("RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 255 0 0").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (255, 0, 0)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: 255, g: 0, b: 0 }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert(tinycolor.equals({ r: 200, g: 100, b: 0 }, "rgb 200 100 0")); + assert( + tinycolor.equals({ r: 200, g: 100, b: 0, a: 0.4 }, "rgba 200 100 0 .4") + ); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgba 200 100 0 1")); + + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb(200, 100, 0)")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + assert(!tinycolor.equals({ r: 199, g: 100, b: 0 }, "rgb 200 100 0")); + + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb(200, 100, 0)") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); + assert( + tinycolor.equals(tinycolor({ r: 200, g: 100, b: 0 }), "rgb 200 100 0") + ); +}); + +Deno.test("Percentage RGB Text Parsing", function () { + assertEquals( + tinycolor("rgb 100% 0% 0%").toHexString(), + "#ff0000", + "spaced input" + ); + assertEquals( + tinycolor("rgb(100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized input" + ); + assertEquals( + tinycolor("rgb (100%, 0%, 0%)").toHexString(), + "#ff0000", + "parenthesized spaced input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toHexString(), + "#ff0000", + "object input" + ); + assertEquals( + tinycolor({ r: "100%", g: "0%", b: "0%" }).toRgb(), + { + r: 255, + g: 0, + b: 0, + a: 1, + }, + "object input and compare" + ); + + assert( + tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(tinycolor.equals({ r: "90%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert( + tinycolor.equals( + { r: "90%", g: "45%", b: "0%", a: 0.4 }, + "rgba 90% 45% 0% .4" + ) + ); + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgba 90% 45% 0% 1") + ); + + assert( + !tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb(90%, 45%, 0%)") + ); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + assert(!tinycolor.equals({ r: "89%", g: "45%", b: "0%" }, "rgb 90% 45% 0%")); + + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb(90%, 45%, 0%)" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); + assert( + tinycolor.equals( + tinycolor({ r: "90%", g: "45%", b: "0%" }), + "rgb 90% 45% 0%" + ) + ); +}); + +Deno.test("HSL parsing", function () { + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38 }).toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor({ h: 251, s: 100, l: 0.38, a: 0.5 }).toHslString(), + "hsla(251, 100%, 38%, 0.5)", + "to hsla" + ); + assertEquals( + tinycolor("hsl(251, 100, 38)").toHexString(), + "#2400c2", + "to hex" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toRgbString(), + "rgb(36, 0, 194)", + "to rgb" + ); + assertEquals( + tinycolor("hsl(251, 100%, 38%)").toHslString(), + "hsl(251, 100%, 38%)", + "to hsl" + ); + assertEquals( + tinycolor("hsl 100 20 10").toHslString(), + "hsl(100, 20%, 10%)", + "problematic hsl" + ); +}); + +Deno.test("Hex Parsing", function () { + assertEquals(tinycolor("rgb 255 0 0").toHexString(), "#ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHexString(true), "#f00"); + + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8String(), "#ff000080"); + assertEquals(tinycolor("rgba 255 0 0 0").toHex8String(), "#ff000000"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(), "#ff0000ff"); + assertEquals(tinycolor("rgba 255 0 0 1").toHex8String(true), "#f00f"); + + assertEquals(tinycolor("rgb 255 0 0").toHex(), "ff0000"); + assertEquals(tinycolor("rgb 255 0 0").toHex(true), "f00"); + assertEquals(tinycolor("rgba 255 0 0 0.5").toHex8(), "ff000080"); +}); + +Deno.test("HSV Parsing", function () { + assertEquals( + tinycolor("hsv 251.1 0.887 .918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsv 251.1 0.887 0.918").toHsvString(), + "hsv(251, 89%, 92%)" + ); + assertEquals( + tinycolor("hsva 251.1 0.887 0.918 0.5").toHsvString(), + "hsva(251, 89%, 92%, 0.5)" + ); +}); + +Deno.test("Invalid Parsing", function () { + var invalidColor = tinycolor("this is not a color"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("#red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" #red"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor("##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor(" ##123456"); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ r: "invalid", g: "invalid", b: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", l: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); + + invalidColor = tinycolor({ h: "invalid", s: "invalid", v: "invalid" }); + assertEquals(invalidColor.toHexString(), "#000000"); + assertEquals(false, invalidColor.isValid()); +}); + +Deno.test("Named colors", function () { + assertEquals(tinycolor("aliceblue").toHex(), "f0f8ff"); + assertEquals(tinycolor("antiquewhite").toHex(), "faebd7"); + assertEquals(tinycolor("aqua").toHex(), "00ffff"); + assertEquals(tinycolor("aquamarine").toHex(), "7fffd4"); + assertEquals(tinycolor("azure").toHex(), "f0ffff"); + assertEquals(tinycolor("beige").toHex(), "f5f5dc"); + assertEquals(tinycolor("bisque").toHex(), "ffe4c4"); + assertEquals(tinycolor("black").toHex(), "000000"); + assertEquals(tinycolor("blanchedalmond").toHex(), "ffebcd"); + assertEquals(tinycolor("blue").toHex(), "0000ff"); + assertEquals(tinycolor("blueviolet").toHex(), "8a2be2"); + assertEquals(tinycolor("brown").toHex(), "a52a2a"); + assertEquals(tinycolor("burlywood").toHex(), "deb887"); + assertEquals(tinycolor("cadetblue").toHex(), "5f9ea0"); + assertEquals(tinycolor("chartreuse").toHex(), "7fff00"); + assertEquals(tinycolor("chocolate").toHex(), "d2691e"); + assertEquals(tinycolor("coral").toHex(), "ff7f50"); + assertEquals(tinycolor("cornflowerblue").toHex(), "6495ed"); + assertEquals(tinycolor("cornsilk").toHex(), "fff8dc"); + assertEquals(tinycolor("crimson").toHex(), "dc143c"); + assertEquals(tinycolor("cyan").toHex(), "00ffff"); + assertEquals(tinycolor("darkblue").toHex(), "00008b"); + assertEquals(tinycolor("darkcyan").toHex(), "008b8b"); + assertEquals(tinycolor("darkgoldenrod").toHex(), "b8860b"); + assertEquals(tinycolor("darkgray").toHex(), "a9a9a9"); + assertEquals(tinycolor("darkgreen").toHex(), "006400"); + assertEquals(tinycolor("darkkhaki").toHex(), "bdb76b"); + assertEquals(tinycolor("darkmagenta").toHex(), "8b008b"); + assertEquals(tinycolor("darkolivegreen").toHex(), "556b2f"); + assertEquals(tinycolor("darkorange").toHex(), "ff8c00"); + assertEquals(tinycolor("darkorchid").toHex(), "9932cc"); + assertEquals(tinycolor("darkred").toHex(), "8b0000"); + assertEquals(tinycolor("darksalmon").toHex(), "e9967a"); + assertEquals(tinycolor("darkseagreen").toHex(), "8fbc8f"); + assertEquals(tinycolor("darkslateblue").toHex(), "483d8b"); + assertEquals(tinycolor("darkslategray").toHex(), "2f4f4f"); + assertEquals(tinycolor("darkturquoise").toHex(), "00ced1"); + assertEquals(tinycolor("darkviolet").toHex(), "9400d3"); + assertEquals(tinycolor("deeppink").toHex(), "ff1493"); + assertEquals(tinycolor("deepskyblue").toHex(), "00bfff"); + assertEquals(tinycolor("dimgray").toHex(), "696969"); + assertEquals(tinycolor("dodgerblue").toHex(), "1e90ff"); + assertEquals(tinycolor("firebrick").toHex(), "b22222"); + assertEquals(tinycolor("floralwhite").toHex(), "fffaf0"); + assertEquals(tinycolor("forestgreen").toHex(), "228b22"); + assertEquals(tinycolor("fuchsia").toHex(), "ff00ff"); + assertEquals(tinycolor("gainsboro").toHex(), "dcdcdc"); + assertEquals(tinycolor("ghostwhite").toHex(), "f8f8ff"); + assertEquals(tinycolor("gold").toHex(), "ffd700"); + assertEquals(tinycolor("goldenrod").toHex(), "daa520"); + assertEquals(tinycolor("gray").toHex(), "808080"); + assertEquals(tinycolor("grey").toHex(), "808080"); + assertEquals(tinycolor("green").toHex(), "008000"); + assertEquals(tinycolor("greenyellow").toHex(), "adff2f"); + assertEquals(tinycolor("honeydew").toHex(), "f0fff0"); + assertEquals(tinycolor("hotpink").toHex(), "ff69b4"); + assertEquals(tinycolor("indianred ").toHex(), "cd5c5c"); + assertEquals(tinycolor("indigo ").toHex(), "4b0082"); + assertEquals(tinycolor("ivory").toHex(), "fffff0"); + assertEquals(tinycolor("khaki").toHex(), "f0e68c"); + assertEquals(tinycolor("lavender").toHex(), "e6e6fa"); + assertEquals(tinycolor("lavenderblush").toHex(), "fff0f5"); + assertEquals(tinycolor("lawngreen").toHex(), "7cfc00"); + assertEquals(tinycolor("lemonchiffon").toHex(), "fffacd"); + assertEquals(tinycolor("lightblue").toHex(), "add8e6"); + assertEquals(tinycolor("lightcoral").toHex(), "f08080"); + assertEquals(tinycolor("lightcyan").toHex(), "e0ffff"); + assertEquals(tinycolor("lightgoldenrodyellow").toHex(), "fafad2"); + assertEquals(tinycolor("lightgrey").toHex(), "d3d3d3"); + assertEquals(tinycolor("lightgreen").toHex(), "90ee90"); + assertEquals(tinycolor("lightpink").toHex(), "ffb6c1"); + assertEquals(tinycolor("lightsalmon").toHex(), "ffa07a"); + assertEquals(tinycolor("lightseagreen").toHex(), "20b2aa"); + assertEquals(tinycolor("lightskyblue").toHex(), "87cefa"); + assertEquals(tinycolor("lightslategray").toHex(), "778899"); + assertEquals(tinycolor("lightsteelblue").toHex(), "b0c4de"); + assertEquals(tinycolor("lightyellow").toHex(), "ffffe0"); + assertEquals(tinycolor("lime").toHex(), "00ff00"); + assertEquals(tinycolor("limegreen").toHex(), "32cd32"); + assertEquals(tinycolor("linen").toHex(), "faf0e6"); + assertEquals(tinycolor("magenta").toHex(), "ff00ff"); + assertEquals(tinycolor("maroon").toHex(), "800000"); + assertEquals(tinycolor("mediumaquamarine").toHex(), "66cdaa"); + assertEquals(tinycolor("mediumblue").toHex(), "0000cd"); + assertEquals(tinycolor("mediumorchid").toHex(), "ba55d3"); + assertEquals(tinycolor("mediumpurple").toHex(), "9370db"); + assertEquals(tinycolor("mediumseagreen").toHex(), "3cb371"); + assertEquals(tinycolor("mediumslateblue").toHex(), "7b68ee"); + assertEquals(tinycolor("mediumspringgreen").toHex(), "00fa9a"); + assertEquals(tinycolor("mediumturquoise").toHex(), "48d1cc"); + assertEquals(tinycolor("mediumvioletred").toHex(), "c71585"); + assertEquals(tinycolor("midnightblue").toHex(), "191970"); + assertEquals(tinycolor("mintcream").toHex(), "f5fffa"); + assertEquals(tinycolor("mistyrose").toHex(), "ffe4e1"); + assertEquals(tinycolor("moccasin").toHex(), "ffe4b5"); + assertEquals(tinycolor("navajowhite").toHex(), "ffdead"); + assertEquals(tinycolor("navy").toHex(), "000080"); + assertEquals(tinycolor("oldlace").toHex(), "fdf5e6"); + assertEquals(tinycolor("olive").toHex(), "808000"); + assertEquals(tinycolor("olivedrab").toHex(), "6b8e23"); + assertEquals(tinycolor("orange").toHex(), "ffa500"); + assertEquals(tinycolor("orangered").toHex(), "ff4500"); + assertEquals(tinycolor("orchid").toHex(), "da70d6"); + assertEquals(tinycolor("palegoldenrod").toHex(), "eee8aa"); + assertEquals(tinycolor("palegreen").toHex(), "98fb98"); + assertEquals(tinycolor("paleturquoise").toHex(), "afeeee"); + assertEquals(tinycolor("palevioletred").toHex(), "db7093"); + assertEquals(tinycolor("papayawhip").toHex(), "ffefd5"); + assertEquals(tinycolor("peachpuff").toHex(), "ffdab9"); + assertEquals(tinycolor("peru").toHex(), "cd853f"); + assertEquals(tinycolor("pink").toHex(), "ffc0cb"); + assertEquals(tinycolor("plum").toHex(), "dda0dd"); + assertEquals(tinycolor("powderblue").toHex(), "b0e0e6"); + assertEquals(tinycolor("purple").toHex(), "800080"); + assertEquals(tinycolor("rebeccapurple").toHex(), "663399"); + assertEquals(tinycolor("red").toHex(), "ff0000"); + assertEquals(tinycolor("rosybrown").toHex(), "bc8f8f"); + assertEquals(tinycolor("royalblue").toHex(), "4169e1"); + assertEquals(tinycolor("saddlebrown").toHex(), "8b4513"); + assertEquals(tinycolor("salmon").toHex(), "fa8072"); + assertEquals(tinycolor("sandybrown").toHex(), "f4a460"); + assertEquals(tinycolor("seagreen").toHex(), "2e8b57"); + assertEquals(tinycolor("seashell").toHex(), "fff5ee"); + assertEquals(tinycolor("sienna").toHex(), "a0522d"); + assertEquals(tinycolor("silver").toHex(), "c0c0c0"); + assertEquals(tinycolor("skyblue").toHex(), "87ceeb"); + assertEquals(tinycolor("slateblue").toHex(), "6a5acd"); + assertEquals(tinycolor("slategray").toHex(), "708090"); + assertEquals(tinycolor("snow").toHex(), "fffafa"); + assertEquals(tinycolor("springgreen").toHex(), "00ff7f"); + assertEquals(tinycolor("steelblue").toHex(), "4682b4"); + assertEquals(tinycolor("tan").toHex(), "d2b48c"); + assertEquals(tinycolor("teal").toHex(), "008080"); + assertEquals(tinycolor("thistle").toHex(), "d8bfd8"); + assertEquals(tinycolor("tomato").toHex(), "ff6347"); + assertEquals(tinycolor("turquoise").toHex(), "40e0d0"); + assertEquals(tinycolor("violet").toHex(), "ee82ee"); + assertEquals(tinycolor("wheat").toHex(), "f5deb3"); + assertEquals(tinycolor("white").toHex(), "ffffff"); + assertEquals(tinycolor("whitesmoke").toHex(), "f5f5f5"); + assertEquals(tinycolor("yellow").toHex(), "ffff00"); + assertEquals(tinycolor("yellowgreen").toHex(), "9acd32"); + + assertEquals(tinycolor("#f00").toName(), "red"); + assertEquals(tinycolor("#fa0a0a").toName(), false); +}); + +Deno.test("Invalid alpha should normalize to 1", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -1 }).toRgbString(), + "rgb(255, 20, 10)", + "Negative value" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: -0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "Negative 0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toRgbString(), + "rgba(255, 20, 10, 0)", + "0" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0.5 }).toRgbString(), + "rgba(255, 20, 10, 0.5)", + ".5" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 1 }).toRgbString(), + "rgb(255, 20, 10)", + "1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 100 }).toRgbString(), + "rgb(255, 20, 10)", + "Greater than 1" + ); + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: "asdfasd" }).toRgbString(), + "rgb(255, 20, 10)", + "Non Numeric" + ); + + assertEquals( + tinycolor("#fff").toRgbString(), + "rgb(255, 255, 255)", + "Hex should be 1" + ); + assertEquals( + tinycolor("rgba 255 0 0 100").toRgbString(), + "rgb(255, 0, 0)", + "Greater than 1 in string parsing" + ); +}); + +Deno.test("toString() with alpha set", function () { + var redNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.6 }, + { + format: "name", + } + ); + var transparentNamed = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0 }, + { + format: "name", + } + ); + var redHex = tinycolor.fromRatio( + { r: 255, g: 0, b: 0, a: 0.4 }, + { + format: "hex", + } + ); + + assertEquals(redNamed.getFormat(), "name", "getFormat() is correct"); + assertEquals(redHex.getFormat(), "hex", "getFormat() is correct"); + + assertEquals( + redNamed.toString(), + "rgba(255, 0, 0, 0.6)", + "Names should default to rgba if alpha is < 1" + ); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + + assertEquals( + redNamed.toString("hex"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex6"), + "#ff0000", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex3"), + "#f00", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex8"), + "#ff000099", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("hex4"), + "#f009", + "Names should not be returned as rgba if format is specified" + ); + assertEquals( + redNamed.toString("name"), + "#ff0000", + "Semi transparent names should return hex in toString() if name format is specified" + ); + + assertEquals( + redNamed.toName(), + false, + "Semi transparent names should be false in toName()" + ); + + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0.4)", + "Hex should default to rgba if alpha is < 1" + ); + assertEquals( + transparentNamed.toString(), + "transparent", + "Named color should equal transparent if alpha == 0" + ); + + redHex.setAlpha(0); + assertEquals( + redHex.toString(), + "rgba(255, 0, 0, 0)", + "Hex should default to rgba if alpha is = 0" + ); +}); + +Deno.test("setting alpha", function () { + var hexSetter = tinycolor("rgba(255, 0, 0, 1)"); + assertEquals(hexSetter.getAlpha(), 1, "Alpha should start as 1"); + var returnedFromSetAlpha = hexSetter.setAlpha(0.9); + assertEquals( + returnedFromSetAlpha, + hexSetter, + "setAlpha return value should be the color." + ); + assertEquals(hexSetter.getAlpha(), 0.9, "setAlpha should change alpha value"); + hexSetter.setAlpha(0.5); + assertEquals(hexSetter.getAlpha(), 0.5, "setAlpha should change alpha value"); + hexSetter.setAlpha(0); + assertEquals(hexSetter.getAlpha(), 0, "setAlpha should change alpha value"); + hexSetter.setAlpha(-1); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value < 0 should be bound to 1" + ); + hexSetter.setAlpha(2); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with value > 1 should be bound to 1" + ); + hexSetter.setAlpha(); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha(null); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); + hexSetter.setAlpha("test"); + assertEquals( + hexSetter.getAlpha(), + 1, + "setAlpha with invalid value should be bound to 1" + ); +}); + +Deno.test("Alpha = 0 should act differently on toName()", function () { + assertEquals( + tinycolor({ r: 255, g: 20, b: 10, a: 0 }).toName(), + "transparent", + "0" + ); + assertEquals( + tinycolor("transparent").toString(), + "transparent", + "toString when passed" + ); + assertEquals(tinycolor("transparent").toHex(), "000000", "toHex"); +}); + +Deno.test("getBrightness", function () { + assertEquals(tinycolor("#000").getBrightness(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getBrightness(), 255, "returns 255 for #fff"); +}); + +Deno.test("getLuminance", function () { + assertEquals(tinycolor("#000").getLuminance(), 0, "returns 0 for #000"); + assertEquals(tinycolor("#fff").getLuminance(), 1, "returns 1 for #fff"); +}); + +Deno.test("isDark returns true/false for dark/light colors", function () { + assertEquals(tinycolor("#000").isDark(), true, "#000 is dark"); + assertEquals(tinycolor("#111").isDark(), true, "#111 is dark"); + assertEquals(tinycolor("#222").isDark(), true, "#222 is dark"); + assertEquals(tinycolor("#333").isDark(), true, "#333 is dark"); + assertEquals(tinycolor("#444").isDark(), true, "#444 is dark"); + assertEquals(tinycolor("#555").isDark(), true, "#555 is dark"); + assertEquals(tinycolor("#666").isDark(), true, "#666 is dark"); + assertEquals(tinycolor("#777").isDark(), true, "#777 is dark"); + assertEquals(tinycolor("#888").isDark(), false, "#888 is not dark"); + assertEquals(tinycolor("#999").isDark(), false, "#999 is not dark"); + assertEquals(tinycolor("#aaa").isDark(), false, "#aaa is not dark"); + assertEquals(tinycolor("#bbb").isDark(), false, "#bbb is not dark"); + assertEquals(tinycolor("#ccc").isDark(), false, "#ccc is not dark"); + assertEquals(tinycolor("#ddd").isDark(), false, "#ddd is not dark"); + assertEquals(tinycolor("#eee").isDark(), false, "#eee is not dark"); + assertEquals(tinycolor("#fff").isDark(), false, "#fff is not dark"); +}); + +Deno.test("isLight returns true/false for light/dark colors", function () { + assertEquals(tinycolor("#000").isLight(), false, "#000 is not light"); + assertEquals(tinycolor("#111").isLight(), false, "#111 is not light"); + assertEquals(tinycolor("#222").isLight(), false, "#222 is not light"); + assertEquals(tinycolor("#333").isLight(), false, "#333 is not light"); + assertEquals(tinycolor("#444").isLight(), false, "#444 is not light"); + assertEquals(tinycolor("#555").isLight(), false, "#555 is not light"); + assertEquals(tinycolor("#666").isLight(), false, "#666 is not light"); + assertEquals(tinycolor("#777").isLight(), false, "#777 is not light"); + assertEquals(tinycolor("#888").isLight(), true, "#888 is light"); + assertEquals(tinycolor("#999").isLight(), true, "#999 is light"); + assertEquals(tinycolor("#aaa").isLight(), true, "#aaa is light"); + assertEquals(tinycolor("#bbb").isLight(), true, "#bbb is light"); + assertEquals(tinycolor("#ccc").isLight(), true, "#ccc is light"); + assertEquals(tinycolor("#ddd").isLight(), true, "#ddd is light"); + assertEquals(tinycolor("#eee").isLight(), true, "#eee is light"); + assertEquals(tinycolor("#fff").isLight(), true, "#fff is light"); +}); + +Deno.test("HSL Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsl()).toHexString(), + "HSL Object" + ); + } +}); + +Deno.test("HSL String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHslString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHslString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHslString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHslString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toHsvString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "toHsvString red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "toHsvString green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "toHsvString blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("HSV Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toHsv()).toHexString(), + "HSV Object" + ); + } +}); + +Deno.test("RGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgb()).toHexString(), + "RGB Object" + ); + } +}); + +Deno.test("RGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals( + tiny.toHexString(), + tinycolor(tiny.toRgbString()).toHexString(), + "RGB String" + ); + } +}); + +Deno.test("PRGB Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgb()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("PRGB String", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + var input = tiny.toRgb(); + var output = tinycolor(tiny.toPercentageRgbString()).toRgb(); + var maxDiff = 2; + + assertEquals( + Math.abs(input.r - output.r) <= maxDiff, + true, + "Red value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.g - output.g) <= maxDiff, + true, + "Green value difference <= " + maxDiff + ); + assertEquals( + Math.abs(input.b - output.b) <= maxDiff, + true, + "Blue value difference <= " + maxDiff + ); + } +}); + +Deno.test("Object", function () { + for (var i = 0; i < conversions.length; i++) { + var c = conversions[i]; + var tiny = tinycolor(c.hex); + assertEquals(tiny.toHexString(), tinycolor(tiny).toHexString(), "Object"); + } +}); + +Deno.test("Color equality", function () { + assert(tinycolor.equals("#ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#ff0000", "rgb(255, 0, 0)"), "Same alphas"); + assert( + !tinycolor.equals("#ff0000", "rgba(255, 0, 0, .1)"), + "Different alphas" + ); + assert(tinycolor.equals("#ff000066", "rgba(255, 0, 0, .4)"), "Same alphas"); + assert(tinycolor.equals("#f009", "rgba(255, 0, 0, .6)"), "Same alphas"); + assert(tinycolor.equals("#336699CC", "369C"), "Same hex"); + assert(tinycolor.equals("ff0000", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("#f00", "#ff0000"), "Same hex"); + assert(tinycolor.equals("f00", "#ff0000"), "Same hex"); + assertEquals(tinycolor("010101").toHexString(), "#010101"); + assert(!tinycolor.equals("#ff0000", "#00ff00"), "Different hex"); + assert( + tinycolor.equals("#ff8000", "rgb(100%, 50%, 0%)"), + "Percentage bounds checking" + ); +}); + +Deno.test("isReadable", function () { + // "#ff0088", "#8822aa" (values used in old WCAG1 tests) + assert( + tinycolor.isReadable("#000000", "#ffffff", { level: "AA", size: "small" }), + "white/black is readable" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", {}), + "not readable - empty wcag2 object" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { level: "AA", size: "large" }), + "not readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#8822aa", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // values derived from and validated using the calculators at http://www.dasplankton.de/ContrastA/ + // and http://webaim.org/resources/contrastchecker/ + + // "#ff0088", "#5c1a72": contrast ratio 3.04 + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "small" }), + "not readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#5c1a72", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + !tinycolor.isReadable("#ff0088", "#5c1a72", { + level: "AAA", + size: "large", + }), + "not readable - AAA large" + ); + + // "#ff0088", "#2e0c3a": contrast ratio 4.56 + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + !tinycolor.isReadable("#ff0088", "#2e0c3a", { + level: "AAA", + size: "small", + }), + "not readable - AAA small" + ); + assert( + tinycolor.isReadable("#ff0088", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); + + // "#db91b8", "#2e0c3a": contrast ratio 7.12 + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "small" }), + "readable - AA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AA", size: "large" }), + "readable - AA large" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "small" }), + "readable - AAA small" + ); + assert( + tinycolor.isReadable("#db91b8", "#2e0c3a", { level: "AAA", size: "large" }), + "readable - AAA large" + ); +}); + +Deno.test("readability", function () { + // check return values from readability function. See isReadable above for standards tests. + assertEquals( + tinycolor.readability("#000", "#000"), + 1, + "Readability function test 0" + ); + assertEquals( + tinycolor.readability("#000", "#111"), + 1.1121078324840545, + "Readability function test 1" + ); + assertEquals( + tinycolor.readability("#000", "#fff"), + 21, + "Readability function test 2" + ); +}); + +Deno.test("mostReadable", function () { + assertEquals( + tinycolor + .mostReadable("#000", ["#111", "#222", { wcag2: {} }]) + .toHexString(), + "#222222", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#f00", ["#d00", "#0d0"], { wcag2: {} }) + .toHexString(), + "#00dd00", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { wcag2: {} }) + .toHexString(), + "#ffffff", + "no different color in list" + ); + //includeFallbackColors + assertEquals( + tinycolor + .mostReadable("#fff", ["#fff", "#fff"], { + includeFallbackColors: true, + }) + .toHexString(), + "#000000", + "no different color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: false, + }) + .toHexString(), + "#112255", + "no readable color in list" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#123", ["#124", "#125"], { + includeFallbackColors: true, + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#000000", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#2e0c3a", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#ff0088", ["#2e0c3a"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#000000", + "no readable color in list" + ); + + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#000", "#fff"], { + includeFallbackColors: false, + }) + .toHexString(), + "#ffffff", + "verify assumption" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "large", + }) + .toHexString(), + "#a9acb6", + "readable color present" + ); + assertEquals( + tinycolor + .mostReadable("#371b2c", ["#a9acb6"], { + includeFallbackColors: true, + level: "AAA", + size: "small", + }) + .toHexString(), + "#ffffff", + "no readable color in list" + ); +}); + +Deno.test("Filters", function () { + assertEquals( + tinycolor("red").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ffff0000)" + ); + assertEquals( + tinycolor("red").toFilter("blue"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffff0000,endColorstr=#ff0000ff)" + ); + + assertEquals( + tinycolor("transparent").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#00000000)" + ); + assertEquals( + tinycolor("transparent").toFilter("red"), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00000000,endColorstr=#ffff0000)" + ); + + assertEquals( + tinycolor("#f0f0f0dd").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#ddf0f0f0,endColorstr=#ddf0f0f0)" + ); + assertEquals( + tinycolor("rgba(0, 0, 255, .5").toFilter(), + "progid:DXImageTransform.Microsoft.gradient(startColorstr=#800000ff,endColorstr=#800000ff)" + ); +}); + +/* Originally generated with: +var results = []; +for (var i = 0; i <= 100; i++) results.push( tinycolor.saturate("red", i).toHex() ) +console.log(JSON.stringify(results)) +*/ +var DESATURATIONS = [ + "ff0000", + "fe0101", + "fc0303", + "fb0404", + "fa0505", + "f90606", + "f70808", + "f60909", + "f50a0a", + "f40b0b", + "f20d0d", + "f10e0e", + "f00f0f", + "ee1111", + "ed1212", + "ec1313", + "eb1414", + "e91616", + "e81717", + "e71818", + "e61919", + "e41b1b", + "e31c1c", + "e21d1d", + "e01f1f", + "df2020", + "de2121", + "dd2222", + "db2424", + "da2525", + "d92626", + "d72828", + "d62929", + "d52a2a", + "d42b2b", + "d22d2d", + "d12e2e", + "d02f2f", + "cf3030", + "cd3232", + "cc3333", + "cb3434", + "c93636", + "c83737", + "c73838", + "c63939", + "c43b3b", + "c33c3c", + "c23d3d", + "c13e3e", + "bf4040", + "be4141", + "bd4242", + "bb4444", + "ba4545", + "b94646", + "b84747", + "b64949", + "b54a4a", + "b44b4b", + "b34d4d", + "b14e4e", + "b04f4f", + "af5050", + "ad5252", + "ac5353", + "ab5454", + "aa5555", + "a85757", + "a75858", + "a65959", + "a45b5b", + "a35c5c", + "a25d5d", + "a15e5e", + "9f6060", + "9e6161", + "9d6262", + "9c6363", + "9a6565", + "996666", + "986767", + "966969", + "956a6a", + "946b6b", + "936c6c", + "916e6e", + "906f6f", + "8f7070", + "8e7171", + "8c7373", + "8b7474", + "8a7575", + "887777", + "877878", + "867979", + "857a7a", + "837c7c", + "827d7d", + "817e7e", + "808080", +]; +var SATURATIONS = [ + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", + "ff0000", +]; +var LIGHTENS = [ + "ff0000", + "ff0505", + "ff0a0a", + "ff0f0f", + "ff1414", + "ff1a1a", + "ff1f1f", + "ff2424", + "ff2929", + "ff2e2e", + "ff3333", + "ff3838", + "ff3d3d", + "ff4242", + "ff4747", + "ff4d4d", + "ff5252", + "ff5757", + "ff5c5c", + "ff6161", + "ff6666", + "ff6b6b", + "ff7070", + "ff7575", + "ff7a7a", + "ff8080", + "ff8585", + "ff8a8a", + "ff8f8f", + "ff9494", + "ff9999", + "ff9e9e", + "ffa3a3", + "ffa8a8", + "ffadad", + "ffb3b3", + "ffb8b8", + "ffbdbd", + "ffc2c2", + "ffc7c7", + "ffcccc", + "ffd1d1", + "ffd6d6", + "ffdbdb", + "ffe0e0", + "ffe5e5", + "ffebeb", + "fff0f0", + "fff5f5", + "fffafa", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", + "ffffff", +]; +var BRIGHTENS = [ + "ff0000", + "ff0303", + "ff0505", + "ff0808", + "ff0a0a", + "ff0d0d", + "ff0f0f", + "ff1212", + "ff1414", + "ff1717", + "ff1919", + "ff1c1c", + "ff1f1f", + "ff2121", + "ff2424", + "ff2626", + "ff2929", + "ff2b2b", + "ff2e2e", + "ff3030", + "ff3333", + "ff3636", + "ff3838", + "ff3b3b", + "ff3d3d", + "ff4040", + "ff4242", + "ff4545", + "ff4747", + "ff4a4a", + "ff4c4c", + "ff4f4f", + "ff5252", + "ff5454", + "ff5757", + "ff5959", + "ff5c5c", + "ff5e5e", + "ff6161", + "ff6363", + "ff6666", + "ff6969", + "ff6b6b", + "ff6e6e", + "ff7070", + "ff7373", + "ff7575", + "ff7878", + "ff7a7a", + "ff7d7d", + "ff7f7f", + "ff8282", + "ff8585", + "ff8787", + "ff8a8a", + "ff8c8c", + "ff8f8f", + "ff9191", + "ff9494", + "ff9696", + "ff9999", + "ff9c9c", + "ff9e9e", + "ffa1a1", + "ffa3a3", + "ffa6a6", + "ffa8a8", + "ffabab", + "ffadad", + "ffb0b0", + "ffb2b2", + "ffb5b5", + "ffb8b8", + "ffbaba", + "ffbdbd", + "ffbfbf", + "ffc2c2", + "ffc4c4", + "ffc7c7", + "ffc9c9", + "ffcccc", + "ffcfcf", + "ffd1d1", + "ffd4d4", + "ffd6d6", + "ffd9d9", + "ffdbdb", + "ffdede", + "ffe0e0", + "ffe3e3", + "ffe5e5", + "ffe8e8", + "ffebeb", + "ffeded", + "fff0f0", + "fff2f2", + "fff5f5", + "fff7f7", + "fffafa", + "fffcfc", + "ffffff", +]; +var DARKENS = [ + "ff0000", + "fa0000", + "f50000", + "f00000", + "eb0000", + "e60000", + "e00000", + "db0000", + "d60000", + "d10000", + "cc0000", + "c70000", + "c20000", + "bd0000", + "b80000", + "b30000", + "ad0000", + "a80000", + "a30000", + "9e0000", + "990000", + "940000", + "8f0000", + "8a0000", + "850000", + "800000", + "7a0000", + "750000", + "700000", + "6b0000", + "660000", + "610000", + "5c0000", + "570000", + "520000", + "4d0000", + "470000", + "420000", + "3d0000", + "380000", + "330000", + "2e0000", + "290000", + "240000", + "1f0000", + "190000", + "140000", + "0f0000", + "0a0000", + "050000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", + "000000", +]; + +Deno.test("Modifications", function () { + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").desaturate(i).toHex(), + DESATURATIONS[i], + "Desaturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").saturate(i).toHex(), + SATURATIONS[i], + "Saturation " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").lighten(i).toHex(), + LIGHTENS[i], + "Lighten " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").brighten(i).toHex(), + BRIGHTENS[i], + "Brighter " + i + " works" + ); + } + for (var i = 0; i <= 100; i++) { + assertEquals( + tinycolor("red").darken(i).toHex(), + DARKENS[i], + "Darken " + i + " works" + ); + } + + assertEquals( + tinycolor("red").greyscale().toHex(), + "808080", + "Greyscale works" + ); +}); + +Deno.test("Spin", function () { + assertEquals( + Math.round(tinycolor("#f00").spin(-1234).toHsl().h), + 206, + "Spinning -1234 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-360).toHsl().h), + 0, + "Spinning -360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(-120).toHsl().h), + 240, + "Spinning -120 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(0).toHsl().h), + 0, + "Spinning 0 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(10).toHsl().h), + 10, + "Spinning 10 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(360).toHsl().h), + 0, + "Spinning 360 works" + ); + assertEquals( + Math.round(tinycolor("#f00").spin(2345).toHsl().h), + 185, + "Spinning 2345 works" + ); + + [-360, 0, 360].forEach(function (delta) { + Object.keys(tinycolor.names).forEach(function (name) { + assertEquals( + tinycolor(name).toHex(), + tinycolor(name).spin(delta).toHex(), + "Spinning " + delta.toString() + " has no effect" + ); + }); + }); +}); + +Deno.test("Mix", function () { + // amount 0 or none + assertEquals( + tinycolor.mix("#000", "#fff").toHsl().l, + 0.5, + "Mixing without amount works" + ); + assertEquals( + tinycolor.mix("#f00", "#000", 0).toHex(), + "ff0000", + "Mixing with 0 amount works" + ); + // This case checks the the problem with floating point numbers (eg 255/90) + assertEquals( + tinycolor.mix("#fff", "#000", 90).toHex(), + "1a1a1a", + "Mixing with 90 amount works correctly" + ); + + // black and white + for (var i = 0; i < 100; i++) { + assertEquals( + Math.round(tinycolor.mix("#000", "#fff", i).toHsl().l * 100) / 100, + i / 100, + "Mixing black and white with " + i + " amount works" + ); + } + + // with colors + for (var i = 0; i < 100; i++) { + var new_hex = Math.round((255 * (100 - i)) / 100).toString(16); + + if (new_hex.length === 1) { + new_hex = "0" + new_hex; + } + + assertEquals( + tinycolor.mix("#f00", "#000", i).toHex(), + new_hex + "0000", + "Mixing " + i + " (red channel)" + ); + assertEquals( + tinycolor.mix("#0f0", "#000", i).toHex(), + "00" + new_hex + "00", + "Mixing " + i + " (green channel)" + ); + assertEquals( + tinycolor.mix("#00f", "#000", i).toHex(), + "0000" + new_hex, + "Mixing " + i + " (blue channel)" + ); + assertEquals( + tinycolor.mix(tinycolor("transparent"), "#000", i).toRgb().a, + i / 100, + "Mixing " + i + " (alpha channel)" + ); + } +}); + +// The combination tests need to be expanded furthe + +function colorsToHexString(colors) { + return colors + .map(function (c) { + return c.toHex(); + }) + .join(","); +} + +Deno.test("complement", function () { + var complementDoesntModifyInstance = tinycolor("red"); + assertEquals( + complementDoesntModifyInstance.complement().toHex(), + "00ffff", + "Complement works" + ); + assertEquals( + complementDoesntModifyInstance.toHex(), + "ff0000", + "Complement did not modify this color" + ); +}); + +Deno.test("analogous", function () { + var combination = tinycolor("red").analogous(); + assertEquals( + colorsToHexString(combination), + "ff0000,ff0066,ff0033,ff0000,ff3300,ff6600", + "Correct Combination" + ); +}); + +Deno.test("monochromatic", function () { + var combination = tinycolor("red").monochromatic(); + assertEquals( + colorsToHexString(combination), + "ff0000,2a0000,550000,800000,aa0000,d40000", + "Correct Combination" + ); +}); + +Deno.test("splitcomplement", function () { + var combination = tinycolor("red").splitcomplement(); + assertEquals( + colorsToHexString(combination), + "ff0000,ccff00,0066ff", + "Correct Combination" + ); +}); + +Deno.test("triad", function () { + var combination = tinycolor("red").triad(); + assertEquals( + colorsToHexString(combination), + "ff0000,00ff00,0000ff", + "Correct Combination" + ); +}); + +Deno.test("tetrad", function () { + var combination = tinycolor("red").tetrad(); + assertEquals( + colorsToHexString(combination), + "ff0000,80ff00,00ffff,7f00ff", + "Correct Combination" + ); +}); + +Deno.test({ + name: "polyad", + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + ignore: true, + fn: function () { + assertThrows(() => { + tinycolor("red").polyad(); + }); + assertThrows(() => { + tinycolor("red").polyad(-1); + }); + assertThrows(() => { + tinycolor("red").polyad("invalid"); + }); + assertEquals(colorsToHexString(tinycolor("red").polyad(1)), "ff0000"); + assertEquals(colorsToHexString(tinycolor("red").polyad("1")), "ff0000"); + assertEquals( + colorsToHexString(tinycolor("red").polyad(2)), + "ff0000,00ffff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(3)), + "ff0000,00ff00,0000ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(4)), + "ff0000,80ff00,00ffff,7f00ff" + ); + assertEquals( + colorsToHexString(tinycolor("red").polyad(5)), + "ff0000,ccff00,00ff66,0066ff,cc00ff" + ); + }, +}); + +runDenoTests(); diff --git a/node_modules/tinycolor2/esm/test_template.js b/node_modules/tinycolor2/esm/test_template.js new file mode 100644 index 0000000000000000000000000000000000000000..84914f76ac7680cf960ab38e5ea1204b2b76c70c --- /dev/null +++ b/node_modules/tinycolor2/esm/test_template.js @@ -0,0 +1,24 @@ +// This file is autogenerated. +// Ideally it wouldn't exist, but it's here to test cjs in node +// Changes should go into ./test.js, and if new assertions are needed +// they'll need to be shimmed here as well +import tinycolor from "./tinycolor.js"; +import { Deno, testDefinitions } from "@deno/shim-deno-test"; +const { assertEquals, assert, assertThrows } = await import( + "../deno_asserts@0.168.0.mjs" +); +async function runDenoTests() { + for (const test of testDefinitions) { + if (test.ignore) { + console.log(`Ignoring ${test.name}`); + continue; + } + console.log(`Running ${test.name}`); + await test.fn(); + console.log(`> Passed ${test.name}`); + } +} + +// CONTENT_GOES_HERE + +runDenoTests(); diff --git a/node_modules/tinycolor2/esm/tinycolor.js b/node_modules/tinycolor2/esm/tinycolor.js new file mode 100644 index 0000000000000000000000000000000000000000..374f5ea993d2c069e0c103fc0e192779201b7e17 --- /dev/null +++ b/node_modules/tinycolor2/esm/tinycolor.js @@ -0,0 +1,1180 @@ +// This file is autogenerated. It's used to publish ESM to npm. +function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); +} + +// https://github.com/bgrins/TinyColor +// Brian Grinstead, MIT License + +var trimLeft = /^\s+/; +var trimRight = /\s+$/; +function tinycolor(color, opts) { + color = color ? color : ""; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } + var rgb = inputToRGB(color); + this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb.ok; +} +tinycolor.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function getLuminance() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r / 255; + GsRGB = rgb.g / 255; + BsRGB = rgb.b / 255; + if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }, + setAlpha: function setAlpha(value) { + this._a = boundAlpha(value); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), + s = Math.round(hsv.s * 100), + v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl.h * 360, + s: hsl.s, + l: hsl.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl.h * 360), + s = Math.round(hsl.s * 100), + l = Math.round(hsl.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString(format) { + var formatSet = !!format; + format = format || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone() { + return tinycolor(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } +}; + +// If input is an object, force 1 into "1.0" to handle ratios properly +// String input requires "1.0" as input, so 1 will be treated as 1 +tinycolor.fromRatio = function (color, opts) { + if (_typeof(color) == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + return tinycolor(color, opts); +}; + +// Given a string or object, convert that input to RGB +// Possible string inputs: +// +// "red" +// "#f00" or "f00" +// "#ff0000" or "ff0000" +// "#ff000000" or "ff000000" +// "rgb 255 0 0" or "rgb (255, 0, 0)" +// "rgb 1.0 0 0" or "rgb (1, 0, 0)" +// "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" +// "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" +// "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" +// "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" +// "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" +// +function inputToRGB(color) { + var rgb = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } + if (_typeof(color) == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: Math.min(255, Math.max(rgb.r, 0)), + g: Math.min(255, Math.max(rgb.g, 0)), + b: Math.min(255, Math.max(rgb.b, 0)), + a: a + }; +} + +// Conversion Functions +// -------------------- + +// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: +// + +// `rgbToRgb` +// Handle bounds / percentage checking to conform to CSS color spec +// +// *Assumes:* r, g, b in [0, 255] or [0, 1] +// *Returns:* { r, g, b } in [0, 255] +function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; +} + +// `rgbToHsl` +// Converts an RGB color value to HSL. +// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] +// *Returns:* { h, s, l } in [0,1] +function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + l = (max + min) / 2; + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + l: l + }; +} + +// `hslToRgb` +// Converts an HSL color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; +} + +// `rgbToHsv` +// Converts an RGB color value to HSV +// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] +// *Returns:* { h, s, v } in [0,1] +function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + v: v + }; +} + +// `hsvToRgb` +// Converts an HSV color value to RGB. +// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] +// *Returns:* { r, g, b } in the set [0, 255] +function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; +} + +// `rgbToHex` +// Converts an RGB color to hex +// Assumes r, g, and b are contained in the set [0, 255] +// Returns a 3 or 6 character hex +function rgbToHex(r, g, b, allow3Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + return hex.join(""); +} + +// `rgbaToHex` +// Converts an RGBA color plus alpha transparency to hex +// Assumes r, g, b are contained in the set [0, 255] and +// a in [0, 1]. Returns a 4 or 8 character rgba hex +function rgbaToHex(r, g, b, a, allow4Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); + } + return hex.join(""); +} + +// `rgbaToArgbHex` +// Converts an RGBA color to an ARGB Hex8 string +// Rarely used, but required for "toFilter()" +function rgbaToArgbHex(r, g, b, a) { + var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex.join(""); +} + +// `equals` +// Can be called with any tinycolor input +tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) return false; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); +}; +tinycolor.random = function () { + return tinycolor.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); +}; + +// Modification Functions +// ---------------------- +// Thanks to less.js for some of the basics here +// + +function _desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); +} +function _saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); +} +function _greyscale(color) { + return tinycolor(color).desaturate(100); +} +function _lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} +function _brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); + rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); + rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); + return tinycolor(rgb); +} +function _darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); +} + +// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. +// Values outside of this range will be wrapped into this range. +function _spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); +} + +// Combination Functions +// --------------------- +// Thanks to jQuery xColor for some of the ideas behind these +// + +function _complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); +} +function polyad(color, number) { + if (isNaN(number) || number <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl = tinycolor(color).toHsl(); + var result = [tinycolor(color)]; + var step = 360 / number; + for (var i = 1; i < number; i++) { + result.push(tinycolor({ + h: (hsl.h + i * step) % 360, + s: hsl.s, + l: hsl.l + })); + } + return result; +} +function _splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [tinycolor(color), tinycolor({ + h: (h + 72) % 360, + s: hsl.s, + l: hsl.l + }), tinycolor({ + h: (h + 216) % 360, + s: hsl.s, + l: hsl.l + })]; +} +function _analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; +} +function _monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor({ + h: h, + s: s, + v: v + })); + v = (v + modification) % 1; + } + return ret; +} + +// Utility Functions +// --------------------- + +tinycolor.mix = function (color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + var p = amount / 100; + var rgba = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor(rgba); +}; + +// Readability Functions +// --------------------- +// false +// tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false +tinycolor.isReadable = function (color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; +}; + +// `mostReadable` +// Given a base color and a list of possible foreground or background +// colors for that base, returns the most readable color. +// Optionally returns Black or White if the most readable color is unreadable. +// *Example* +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" +// tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" +// tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" +tinycolor.mostReadable = function (baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } + if (tinycolor.isReadable(baseColor, bestColor, { + level: level, + size: size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); + } +}; + +// Big List of Colors +// ------------------ +// +var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" +}; + +// Make it easy to access colors via `hexNames[hex]` +var hexNames = tinycolor.hexNames = flip(names); + +// Utilities +// --------- + +// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` +function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; +} + +// Return a valid alpha value [0,1] with all invalid values being set to 1 +function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; +} + +// Take input from [0, n] and return it as [0, 1] +function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if (Math.abs(n - max) < 0.000001) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return n % max / parseFloat(max); +} + +// Force a number between 0 and 1 +function clamp01(val) { + return Math.min(1, Math.max(0, val)); +} + +// Parse a base-16 hex value into a base-10 integer +function parseIntFromHex(val) { + return parseInt(val, 16); +} + +// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 +// +function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; +} + +// Check to see if string passed in is a percentage +function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; +} + +// Force a hex value to have 2 characters +function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; +} + +// Replace a decimal with it's percentage value +function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; +} + +// Converts a decimal to a hex value +function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); +} +// Converts a hex value to a decimal +function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; +} +var matchers = function () { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; +}(); + +// `isValidCSSUnit` +// Take in a single string / number and check to see if it looks like a CSS unit +// (see `matchers` above for definition). +function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); +} + +// `stringInputToObject` +// Permissive string parsing. Take in a number of formats, and output an object +// based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` +function stringInputToObject(color) { + color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if (match = matchers.rgb.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named ? "name" : "hex" + }; + } + return false; +} +function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level: level, + size: size + }; +} + +export { tinycolor as default }; diff --git a/node_modules/tinycolor2/package.json b/node_modules/tinycolor2/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5eb8c35d0f604e63c6221190fdf32ed010d8761f --- /dev/null +++ b/node_modules/tinycolor2/package.json @@ -0,0 +1,35 @@ +{ + "version": "1.6.0", + "name": "tinycolor2", + "description": "Fast Color Parsing and Manipulation", + "url": "http://bgrins.github.com/TinyColor", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/bgrins/TinyColor.git" + }, + "keywords": [ + "color", + "parser", + "tinycolor" + ], + "author": "Brian Grinstead (http://briangrinstead.com)", + "bugs": { + "url": "https://github.com/bgrins/TinyColor/issues" + }, + "module": "./esm/tinycolor.js", + "main": "./cjs/tinycolor.js", + "browser": "./cjs/tinycolor.js", + "exports": { + ".": { + "import": "./esm/tinycolor.js", + "require": "./cjs/tinycolor.js" + } + }, + "scripts": { + "test": "node cjs/test.js && node esm/test.js" + }, + "devDependencies": { + "@deno/shim-deno-test": "^0.4.0" + } +} diff --git a/node_modules/tinycolor2/tinycolor.js b/node_modules/tinycolor2/tinycolor.js new file mode 100644 index 0000000000000000000000000000000000000000..52601dfe40262bb793b7c2b8c9bba93e1ca0003e --- /dev/null +++ b/node_modules/tinycolor2/tinycolor.js @@ -0,0 +1,1191 @@ +// This file is autogenerated. +// It's here at this path for backwards compatibility for links to it +// but the npm package now exports both CJS and ESM. +// See https://github.com/bgrins/TinyColor/ for instructions. + (function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.tinycolor = factory()); +})(this, (function () { 'use strict'; + + function _typeof(obj) { + "@babel/helpers - typeof"; + + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { + return typeof obj; + } : function (obj) { + return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }, _typeof(obj); + } + + // https://github.com/bgrins/TinyColor + // Brian Grinstead, MIT License + + var trimLeft = /^\s+/; + var trimRight = /\s+$/; + function tinycolor(color, opts) { + color = color ? color : ""; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } + var rgb = inputToRGB(color); + this._originalInput = color, this._r = rgb.r, this._g = rgb.g, this._b = rgb.b, this._a = rgb.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb.format; + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb.ok; + } + tinycolor.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + //http://www.w3.org/TR/AERT#color-contrast + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + getLuminance: function getLuminance() { + //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef + var rgb = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R, G, B; + RsRGB = rgb.r / 255; + GsRGB = rgb.g / 255; + BsRGB = rgb.b / 255; + if (RsRGB <= 0.03928) R = RsRGB / 12.92;else R = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92;else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B = BsRGB / 12.92;else B = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R + 0.7152 * G + 0.0722 * B; + }, + setAlpha: function setAlpha(value) { + this._a = boundAlpha(value); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), + s = Math.round(hsv.s * 100), + v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl.h * 360, + s: hsl.s, + l: hsl.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl.h * 360), + s = Math.round(hsl.s * 100), + l = Math.round(hsl.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString(format) { + var formatSet = !!format; + format = format || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name"); + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "hex4") { + formattedString = this.toHex8String(true); + } + if (format === "hex8") { + formattedString = this.toHex8String(); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone() { + return tinycolor(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } + }; + + // If input is an object, force 1 into "1.0" to handle ratios properly + // String input requires "1.0" as input, so 1 will be treated as 1 + tinycolor.fromRatio = function (color, opts) { + if (_typeof(color) == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + return tinycolor(color, opts); + }; + + // Given a string or object, convert that input to RGB + // Possible string inputs: + // + // "red" + // "#f00" or "f00" + // "#ff0000" or "ff0000" + // "#ff000000" or "ff000000" + // "rgb 255 0 0" or "rgb (255, 0, 0)" + // "rgb 1.0 0 0" or "rgb (1, 0, 0)" + // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" + // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" + // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" + // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" + // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" + // + function inputToRGB(color) { + var rgb = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format = false; + if (typeof color == "string") { + color = stringInputToObject(color); + } + if (_typeof(color) == "object") { + if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) { + s = convertToPercentage(color.s); + v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, s, v); + ok = true; + format = "hsv"; + } else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) { + s = convertToPercentage(color.s); + l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, s, l); + ok = true; + format = "hsl"; + } + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + a = boundAlpha(a); + return { + ok: ok, + format: color.format || format, + r: Math.min(255, Math.max(rgb.r, 0)), + g: Math.min(255, Math.max(rgb.g, 0)), + b: Math.min(255, Math.max(rgb.b, 0)), + a: a + }; + } + + // Conversion Functions + // -------------------- + + // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: + // + + // `rgbToRgb` + // Handle bounds / percentage checking to conform to CSS color spec + // + // *Assumes:* r, g, b in [0, 255] or [0, 1] + // *Returns:* { r, g, b } in [0, 255] + function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + + // `rgbToHsl` + // Converts an RGB color value to HSL. + // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] + // *Returns:* { h, s, l } in [0,1] + function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + l = (max + min) / 2; + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + l: l + }; + } + + // `hslToRgb` + // Converts an HSL color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + } + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHsv` + // Converts an RGB color value to HSV + // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] + // *Returns:* { h, s, v } in [0,1] + function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), + min = Math.min(r, g, b); + var h, + s, + v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h: h, + s: s, + v: v + }; + } + + // `hsvToRgb` + // Converts an HSV color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + + // `rgbToHex` + // Converts an RGB color to hex + // Assumes r, g, and b are contained in the set [0, 255] + // Returns a 3 or 6 character hex + function rgbToHex(r, g, b, allow3Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + return hex.join(""); + } + + // `rgbaToHex` + // Converts an RGBA color plus alpha transparency to hex + // Assumes r, g, b are contained in the set [0, 255] and + // a in [0, 1]. Returns a 4 or 8 character rgba hex + function rgbaToHex(r, g, b, a, allow4Char) { + var hex = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + + // Return a 4 character hex if possible + if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0); + } + return hex.join(""); + } + + // `rgbaToArgbHex` + // Converts an RGBA color to an ARGB Hex8 string + // Rarely used, but required for "toFilter()" + function rgbaToArgbHex(r, g, b, a) { + var hex = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex.join(""); + } + + // `equals` + // Can be called with any tinycolor input + tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) return false; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); + }; + tinycolor.random = function () { + return tinycolor.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); + }; + + // Modification Functions + // ---------------------- + // Thanks to less.js for some of the basics here + // + + function _desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + function _greyscale(color) { + return tinycolor(color).desaturate(100); + } + function _lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + function _brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = Math.max(0, Math.min(255, rgb.r - Math.round(255 * -(amount / 100)))); + rgb.g = Math.max(0, Math.min(255, rgb.g - Math.round(255 * -(amount / 100)))); + rgb.b = Math.max(0, Math.min(255, rgb.b - Math.round(255 * -(amount / 100)))); + return tinycolor(rgb); + } + function _darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + + // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. + // Values outside of this range will be wrapped into this range. + function _spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (hsl.h + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); + } + + // Combination Functions + // --------------------- + // Thanks to jQuery xColor for some of the ideas behind these + // + + function _complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); + } + function polyad(color, number) { + if (isNaN(number) || number <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl = tinycolor(color).toHsl(); + var result = [tinycolor(color)]; + var step = 360 / number; + for (var i = 1; i < number; i++) { + result.push(tinycolor({ + h: (hsl.h + i * step) % 360, + s: hsl.s, + l: hsl.l + })); + } + return result; + } + function _splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [tinycolor(color), tinycolor({ + h: (h + 72) % 360, + s: hsl.s, + l: hsl.l + }), tinycolor({ + h: (h + 216) % 360, + s: hsl.s, + l: hsl.l + })]; + } + function _analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + for (hsl.h = (hsl.h - (part * results >> 1) + 720) % 360; --results;) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; + } + function _monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor({ + h: h, + s: s, + v: v + })); + v = (v + modification) % 1; + } + return ret; + } + + // Utility Functions + // --------------------- + + tinycolor.mix = function (color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); + var p = amount / 100; + var rgba = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor(rgba); + }; + + // Readability Functions + // --------------------- + // false + // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false + tinycolor.isReadable = function (color1, color2, wcag2) { + var readability = tinycolor.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; + }; + + // `mostReadable` + // Given a base color and a list of possible foreground or background + // colors for that base, returns the most readable color. + // Optionally returns Black or White if the most readable color is unreadable. + // *Example* + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255" + // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3" + // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff" + tinycolor.mostReadable = function (baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor(colorList[i]); + } + } + if (tinycolor.isReadable(baseColor, bestColor, { + level: level, + size: size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor.mostReadable(baseColor, ["#fff", "#000"], args); + } + }; + + // Big List of Colors + // ------------------ + // + var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" + }; + + // Make it easy to access colors via `hexNames[hex]` + var hexNames = tinycolor.hexNames = flip(names); + + // Utilities + // --------- + + // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` + function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } + + // Return a valid alpha value [0,1] with all invalid values being set to 1 + function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; + } + + // Take input from [0, n] and return it as [0, 1] + function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if (Math.abs(n - max) < 0.000001) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return n % max / parseFloat(max); + } + + // Force a number between 0 and 1 + function clamp01(val) { + return Math.min(1, Math.max(0, val)); + } + + // Parse a base-16 hex value into a base-10 integer + function parseIntFromHex(val) { + return parseInt(val, 16); + } + + // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 + // + function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; + } + + // Check to see if string passed in is a percentage + function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; + } + + // Force a hex value to have 2 characters + function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; + } + + // Replace a decimal with it's percentage value + function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; + } + + // Converts a decimal to a hex value + function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); + } + // Converts a hex value to a decimal + function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; + } + var matchers = function () { + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + }(); + + // `isValidCSSUnit` + // Take in a single string / number and check to see if it looks like a CSS unit + // (see `matchers` above for definition). + function isValidCSSUnit(color) { + return !!matchers.CSS_UNIT.exec(color); + } + + // `stringInputToObject` + // Permissive string parsing. Take in a number of formats, and output an object + // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` + function stringInputToObject(color) { + color = color.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if (match = matchers.rgb.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named ? "name" : "hex" + }; + } + return false; + } + function validateWCAG2Parms(parms) { + // return valid WCAG2 parms for isReadable. + // If input parms are invalid, return {"level":"AA", "size":"small"} + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level: level, + size: size + }; + } + + return tinycolor; + +})); diff --git a/node_modules/tinyglobby/LICENSE b/node_modules/tinyglobby/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8657364bb085e0b193c66673fd4826d03a0bc01d --- /dev/null +++ b/node_modules/tinyglobby/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Madeline Gurriarán + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/tinyglobby/README.md b/node_modules/tinyglobby/README.md new file mode 100644 index 0000000000000000000000000000000000000000..15695e668a2c16064ae26eee1378618df9a4db90 --- /dev/null +++ b/node_modules/tinyglobby/README.md @@ -0,0 +1,25 @@ +# tinyglobby + +[![npm version](https://img.shields.io/npm/v/tinyglobby.svg?maxAge=3600)](https://npmjs.com/package/tinyglobby) +[![monthly downloads](https://img.shields.io/npm/dm/tinyglobby.svg?maxAge=3600)](https://npmjs.com/package/tinyglobby) + +A fast and minimal alternative to globby and fast-glob, meant to behave the same way. + +Both globby and fast-glob present some behavior no other globbing lib has, +which makes it hard to manually replace with something smaller and better. + +This library uses only two subdependencies, compared to `globby`'s [23](https://npmgraph.js.org/?q=globby@14.1.0) +and `fast-glob`'s [17](https://npmgraph.js.org/?q=fast-glob@3.3.3). + +## Usage + +```js +import { glob, globSync } from 'tinyglobby'; + +await glob(['files/*.ts', '!**/*.d.ts'], { cwd: 'src' }); +globSync('src/**/*.ts', { ignore: '**/*.d.ts' }); +``` + +## Documentation + +Visit https://superchupu.dev/tinyglobby to read the full documentation. diff --git a/node_modules/tinyglobby/dist/index.cjs b/node_modules/tinyglobby/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..e5cb03ccec9ac91a3f3d089fa48b666e211eb8a7 --- /dev/null +++ b/node_modules/tinyglobby/dist/index.cjs @@ -0,0 +1,350 @@ +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion +let fs = require("fs"); +fs = __toESM(fs); +let path = require("path"); +path = __toESM(path); +let url = require("url"); +url = __toESM(url); +let fdir = require("fdir"); +fdir = __toESM(fdir); +let picomatch = require("picomatch"); +picomatch = __toESM(picomatch); + +//#region src/utils.ts +const isReadonlyArray = Array.isArray; +const isWin = process.platform === "win32"; +const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/; +function getPartialMatcher(patterns, options = {}) { + const patternsCount = patterns.length; + const patternsParts = Array(patternsCount); + const matchers = Array(patternsCount); + const globstarEnabled = !options.noglobstar; + for (let i = 0; i < patternsCount; i++) { + const parts = splitPattern(patterns[i]); + patternsParts[i] = parts; + const partsCount = parts.length; + const partMatchers = Array(partsCount); + for (let j = 0; j < partsCount; j++) partMatchers[j] = (0, picomatch.default)(parts[j], options); + matchers[i] = partMatchers; + } + return (input) => { + const inputParts = input.split("/"); + if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true; + for (let i = 0; i < patterns.length; i++) { + const patternParts = patternsParts[i]; + const matcher = matchers[i]; + const inputPatternCount = inputParts.length; + const minParts = Math.min(inputPatternCount, patternParts.length); + let j = 0; + while (j < minParts) { + const part = patternParts[j]; + if (part.includes("/")) return true; + const match = matcher[j](inputParts[j]); + if (!match) break; + if (globstarEnabled && part === "**") return true; + j++; + } + if (j === inputPatternCount) return true; + } + return false; + }; +} +/* node:coverage ignore next 2 */ +const WIN32_ROOT_DIR = /^[A-Z]:\/$/i; +const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/"; +function buildFormat(cwd, root, absolute) { + if (cwd === root || root.startsWith(`${cwd}/`)) { + if (absolute) { + const start = isRoot(cwd) ? cwd.length : cwd.length + 1; + return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || "."; + } + const prefix = root.slice(cwd.length + 1); + if (prefix) return (p, isDir) => { + if (p === ".") return prefix; + const result = `${prefix}/${p}`; + return isDir ? result.slice(0, -1) : result; + }; + return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p; + } + if (absolute) return (p) => path.posix.relative(cwd, p) || "."; + return (p) => path.posix.relative(cwd, `${root}/${p}`) || "."; +} +function buildRelative(cwd, root) { + if (root.startsWith(`${cwd}/`)) { + const prefix = root.slice(cwd.length + 1); + return (p) => `${prefix}/${p}`; + } + return (p) => { + const result = path.posix.relative(cwd, `${root}/${p}`); + if (p.endsWith("/") && result !== "") return `${result}/`; + return result || "."; + }; +} +const splitPatternOptions = { parts: true }; +function splitPattern(path$2) { + var _result$parts; + const result = picomatch.default.scan(path$2, splitPatternOptions); + return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$2]; +} +const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g; +function convertPosixPathToPattern(path$2) { + return escapePosixPath(path$2); +} +function convertWin32PathToPattern(path$2) { + return escapeWin32Path(path$2).replace(ESCAPED_WIN32_BACKSLASHES, "/"); +} +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +/* node:coverage ignore next 3 */ +const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern; +const POSIX_UNESCAPED_GLOB_SYMBOLS = /(? path$2.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +const escapeWin32Path = (path$2) => path$2.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +/* node:coverage ignore next */ +const escapePath = isWin ? escapeWin32Path : escapePosixPath; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +function isDynamicPattern(pattern, options) { + if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true; + const scan = picomatch.default.scan(pattern); + return scan.isGlob || scan.negated; +} +function log(...tasks) { + console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks); +} + +//#endregion +//#region src/index.ts +const PARENT_DIRECTORY = /^(\/?\.\.)+/; +const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g; +const BACKSLASHES = /\\/g; +function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) { + let result = pattern; + if (pattern.endsWith("/")) result = pattern.slice(0, -1); + if (!result.endsWith("*") && expandDirectories) result += "/**"; + const escapedCwd = escapePath(cwd); + if (path.default.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = path.posix.relative(escapedCwd, result); + else result = path.posix.normalize(result); + const parentDirectoryMatch = PARENT_DIRECTORY.exec(result); + const parts = splitPattern(result); + if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) { + const n = (parentDirectoryMatch[0].length + 1) / 3; + let i = 0; + const cwdParts = escapedCwd.split("/"); + while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) { + result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || "."; + i++; + } + const potentialRoot = path.posix.join(cwd, parentDirectoryMatch[0].slice(i * 3)); + if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) { + props.root = potentialRoot; + props.depthOffset = -n + i; + } + } + if (!isIgnore && props.depthOffset >= 0) { + var _props$commonPath; + (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts); + const newCommonPath = []; + const length = Math.min(props.commonPath.length, parts.length); + for (let i = 0; i < length; i++) { + const part = parts[i]; + if (part === "**" && !parts[i + 1]) { + newCommonPath.pop(); + break; + } + if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break; + newCommonPath.push(part); + } + props.depthOffset = newCommonPath.length; + props.commonPath = newCommonPath; + props.root = newCommonPath.length > 0 ? path.posix.join(cwd, ...newCommonPath) : cwd; + } + return result; +} +function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) { + if (typeof patterns === "string") patterns = [patterns]; + if (typeof ignore === "string") ignore = [ignore]; + const matchPatterns = []; + const ignorePatterns = []; + for (const pattern of ignore) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true)); + } + for (const pattern of patterns) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false)); + else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true)); + } + return { + match: matchPatterns, + ignore: ignorePatterns + }; +} +function formatPaths(paths, relative) { + for (let i = paths.length - 1; i >= 0; i--) { + const path$2 = paths[i]; + paths[i] = relative(path$2); + } + return paths; +} +function normalizeCwd(cwd) { + if (!cwd) return process.cwd().replace(BACKSLASHES, "/"); + if (cwd instanceof URL) return (0, url.fileURLToPath)(cwd).replace(BACKSLASHES, "/"); + return path.default.resolve(cwd).replace(BACKSLASHES, "/"); +} +function getCrawler(patterns, inputOptions = {}) { + const options = process.env.TINYGLOBBY_DEBUG ? { + ...inputOptions, + debug: true + } : inputOptions; + const cwd = normalizeCwd(options.cwd); + if (options.debug) log("globbing with:", { + patterns, + options, + cwd + }); + if (Array.isArray(patterns) && patterns.length === 0) return [{ + sync: () => [], + withPromise: async () => [] + }, false]; + const props = { + root: cwd, + commonPath: null, + depthOffset: 0 + }; + const processed = processPatterns({ + ...options, + patterns + }, cwd, props); + if (options.debug) log("internal processing patterns:", processed); + const matchOptions = { + dot: options.dot, + nobrace: options.braceExpansion === false, + nocase: options.caseSensitiveMatch === false, + noextglob: options.extglob === false, + noglobstar: options.globstar === false, + posix: true + }; + const matcher = (0, picomatch.default)(processed.match, { + ...matchOptions, + ignore: processed.ignore + }); + const ignore = (0, picomatch.default)(processed.ignore, matchOptions); + const partialMatcher = getPartialMatcher(processed.match, matchOptions); + const format = buildFormat(cwd, props.root, options.absolute); + const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true); + const fdirOptions = { + filters: [options.debug ? (p, isDirectory) => { + const path$2 = format(p, isDirectory); + const matches = matcher(path$2); + if (matches) log(`matched ${path$2}`); + return matches; + } : (p, isDirectory) => matcher(format(p, isDirectory))], + exclude: options.debug ? (_, p) => { + const relativePath = formatExclude(p, true); + const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); + if (skipped) log(`skipped ${p}`); + else log(`crawling ${p}`); + return skipped; + } : (_, p) => { + const relativePath = formatExclude(p, true); + return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); + }, + fs: options.fs ? { + readdir: options.fs.readdir || fs.default.readdir, + readdirSync: options.fs.readdirSync || fs.default.readdirSync, + realpath: options.fs.realpath || fs.default.realpath, + realpathSync: options.fs.realpathSync || fs.default.realpathSync, + stat: options.fs.stat || fs.default.stat, + statSync: options.fs.statSync || fs.default.statSync + } : void 0, + pathSeparator: "/", + relativePaths: true, + resolveSymlinks: true, + signal: options.signal + }; + if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset); + if (options.absolute) { + fdirOptions.relativePaths = false; + fdirOptions.resolvePaths = true; + fdirOptions.includeBasePath = true; + } + if (options.followSymbolicLinks === false) { + fdirOptions.resolveSymlinks = false; + fdirOptions.excludeSymlinks = true; + } + if (options.onlyDirectories) { + fdirOptions.excludeFiles = true; + fdirOptions.includeDirs = true; + } else if (options.onlyFiles === false) fdirOptions.includeDirs = true; + props.root = props.root.replace(BACKSLASHES, ""); + const root = props.root; + if (options.debug) log("internal properties:", props); + const relative = cwd !== root && !options.absolute && buildRelative(cwd, props.root); + return [new fdir.fdir(fdirOptions).crawl(root), relative]; +} +async function glob(patternsOrOptions, options) { + if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); + const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string"; + const opts = isModern ? options : patternsOrOptions; + const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns; + const [crawler, relative] = getCrawler(patterns, opts); + if (!relative) return crawler.withPromise(); + return formatPaths(await crawler.withPromise(), relative); +} +function globSync(patternsOrOptions, options) { + if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); + const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string"; + const opts = isModern ? options : patternsOrOptions; + const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns; + const [crawler, relative] = getCrawler(patterns, opts); + if (!relative) return crawler.sync(); + return formatPaths(crawler.sync(), relative); +} + +//#endregion +exports.convertPathToPattern = convertPathToPattern; +exports.escapePath = escapePath; +exports.glob = glob; +exports.globSync = globSync; +exports.isDynamicPattern = isDynamicPattern; \ No newline at end of file diff --git a/node_modules/tinyglobby/dist/index.d.cts b/node_modules/tinyglobby/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..9d67dae260a76a6aa817a310390687becbc1eee6 --- /dev/null +++ b/node_modules/tinyglobby/dist/index.d.cts @@ -0,0 +1,147 @@ +import { FSLike } from "fdir"; + +//#region src/utils.d.ts + +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +declare const convertPathToPattern: (path: string) => string; +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +declare const escapePath: (path: string) => string; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +declare function isDynamicPattern(pattern: string, options?: { + caseSensitiveMatch: boolean; +}): boolean; +//#endregion +//#region src/index.d.ts +interface GlobOptions { + /** + * Whether to return absolute paths. Disable to have relative paths. + * @default false + */ + absolute?: boolean; + /** + * Enables support for brace expansion syntax, like `{a,b}` or `{1..9}`. + * @default true + */ + braceExpansion?: boolean; + /** + * Whether to match in case-sensitive mode. + * @default true + */ + caseSensitiveMatch?: boolean; + /** + * The working directory in which to search. Results will be returned relative to this directory, unless + * {@link absolute} is set. + * + * It is important to avoid globbing outside this directory when possible, even with absolute paths enabled, + * as doing so can harm performance due to having to recalculate relative paths. + * @default process.cwd() + */ + cwd?: string | URL; + /** + * Logs useful debug information. Meant for development purposes. Logs can change at any time. + * @default false + */ + debug?: boolean; + /** + * Maximum directory depth to crawl. + * @default Infinity + */ + deep?: number; + /** + * Whether to return entries that start with a dot, like `.gitignore` or `.prettierrc`. + * @default false + */ + dot?: boolean; + /** + * Whether to automatically expand directory patterns. + * + * Important to disable if migrating from [`fast-glob`](https://github.com/mrmlnc/fast-glob). + * @default true + */ + expandDirectories?: boolean; + /** + * Enables support for extglobs, like `+(pattern)`. + * @default true + */ + extglob?: boolean; + /** + * Whether to traverse and include symbolic links. Can slightly affect performance. + * @default true + */ + followSymbolicLinks?: boolean; + /** + * An object that overrides `node:fs` functions. + * @default import('node:fs') + */ + fs?: FileSystemAdapter; + /** + * Enables support for matching nested directories with globstars (`**`). + * If `false`, `**` behaves exactly like `*`. + * @default true + */ + globstar?: boolean; + /** + * Glob patterns to exclude from the results. + * @default [] + */ + ignore?: string | readonly string[]; + /** + * Enable to only return directories. + * If `true`, disables {@link onlyFiles}. + * @default false + */ + onlyDirectories?: boolean; + /** + * Enable to only return files. + * @default true + */ + onlyFiles?: boolean; + /** + * @deprecated Provide patterns as the first argument instead. + */ + patterns?: string | readonly string[]; + /** + * An `AbortSignal` to abort crawling the file system. + * @default undefined + */ + signal?: AbortSignal; +} +type FileSystemAdapter = Partial; +/** +* Asynchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#glob} +*/ +declare function glob(patterns: string | readonly string[], options?: Omit): Promise; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function glob(options: GlobOptions): Promise; +/** +* Synchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#globSync} +*/ +declare function globSync(patterns: string | readonly string[], options?: Omit): string[]; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function globSync(options: GlobOptions): string[]; +//#endregion +export { FileSystemAdapter, GlobOptions, convertPathToPattern, escapePath, glob, globSync, isDynamicPattern }; \ No newline at end of file diff --git a/node_modules/tinyglobby/dist/index.d.mts b/node_modules/tinyglobby/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9d67dae260a76a6aa817a310390687becbc1eee6 --- /dev/null +++ b/node_modules/tinyglobby/dist/index.d.mts @@ -0,0 +1,147 @@ +import { FSLike } from "fdir"; + +//#region src/utils.d.ts + +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +declare const convertPathToPattern: (path: string) => string; +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +declare const escapePath: (path: string) => string; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +declare function isDynamicPattern(pattern: string, options?: { + caseSensitiveMatch: boolean; +}): boolean; +//#endregion +//#region src/index.d.ts +interface GlobOptions { + /** + * Whether to return absolute paths. Disable to have relative paths. + * @default false + */ + absolute?: boolean; + /** + * Enables support for brace expansion syntax, like `{a,b}` or `{1..9}`. + * @default true + */ + braceExpansion?: boolean; + /** + * Whether to match in case-sensitive mode. + * @default true + */ + caseSensitiveMatch?: boolean; + /** + * The working directory in which to search. Results will be returned relative to this directory, unless + * {@link absolute} is set. + * + * It is important to avoid globbing outside this directory when possible, even with absolute paths enabled, + * as doing so can harm performance due to having to recalculate relative paths. + * @default process.cwd() + */ + cwd?: string | URL; + /** + * Logs useful debug information. Meant for development purposes. Logs can change at any time. + * @default false + */ + debug?: boolean; + /** + * Maximum directory depth to crawl. + * @default Infinity + */ + deep?: number; + /** + * Whether to return entries that start with a dot, like `.gitignore` or `.prettierrc`. + * @default false + */ + dot?: boolean; + /** + * Whether to automatically expand directory patterns. + * + * Important to disable if migrating from [`fast-glob`](https://github.com/mrmlnc/fast-glob). + * @default true + */ + expandDirectories?: boolean; + /** + * Enables support for extglobs, like `+(pattern)`. + * @default true + */ + extglob?: boolean; + /** + * Whether to traverse and include symbolic links. Can slightly affect performance. + * @default true + */ + followSymbolicLinks?: boolean; + /** + * An object that overrides `node:fs` functions. + * @default import('node:fs') + */ + fs?: FileSystemAdapter; + /** + * Enables support for matching nested directories with globstars (`**`). + * If `false`, `**` behaves exactly like `*`. + * @default true + */ + globstar?: boolean; + /** + * Glob patterns to exclude from the results. + * @default [] + */ + ignore?: string | readonly string[]; + /** + * Enable to only return directories. + * If `true`, disables {@link onlyFiles}. + * @default false + */ + onlyDirectories?: boolean; + /** + * Enable to only return files. + * @default true + */ + onlyFiles?: boolean; + /** + * @deprecated Provide patterns as the first argument instead. + */ + patterns?: string | readonly string[]; + /** + * An `AbortSignal` to abort crawling the file system. + * @default undefined + */ + signal?: AbortSignal; +} +type FileSystemAdapter = Partial; +/** +* Asynchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#glob} +*/ +declare function glob(patterns: string | readonly string[], options?: Omit): Promise; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function glob(options: GlobOptions): Promise; +/** +* Synchronously match files following a glob pattern. +* @see {@link https://superchupu.dev/tinyglobby/documentation#globSync} +*/ +declare function globSync(patterns: string | readonly string[], options?: Omit): string[]; +/** +* @deprecated Provide patterns as the first argument instead. +*/ +declare function globSync(options: GlobOptions): string[]; +//#endregion +export { FileSystemAdapter, GlobOptions, convertPathToPattern, escapePath, glob, globSync, isDynamicPattern }; \ No newline at end of file diff --git a/node_modules/tinyglobby/dist/index.mjs b/node_modules/tinyglobby/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4f41787d8bc4b72d4108dbcf477e9d861dd01cd2 --- /dev/null +++ b/node_modules/tinyglobby/dist/index.mjs @@ -0,0 +1,318 @@ +import nativeFs from "fs"; +import path, { posix } from "path"; +import { fileURLToPath } from "url"; +import { fdir } from "fdir"; +import picomatch from "picomatch"; + +//#region src/utils.ts +const isReadonlyArray = Array.isArray; +const isWin = process.platform === "win32"; +const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/; +function getPartialMatcher(patterns, options = {}) { + const patternsCount = patterns.length; + const patternsParts = Array(patternsCount); + const matchers = Array(patternsCount); + const globstarEnabled = !options.noglobstar; + for (let i = 0; i < patternsCount; i++) { + const parts = splitPattern(patterns[i]); + patternsParts[i] = parts; + const partsCount = parts.length; + const partMatchers = Array(partsCount); + for (let j = 0; j < partsCount; j++) partMatchers[j] = picomatch(parts[j], options); + matchers[i] = partMatchers; + } + return (input) => { + const inputParts = input.split("/"); + if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true; + for (let i = 0; i < patterns.length; i++) { + const patternParts = patternsParts[i]; + const matcher = matchers[i]; + const inputPatternCount = inputParts.length; + const minParts = Math.min(inputPatternCount, patternParts.length); + let j = 0; + while (j < minParts) { + const part = patternParts[j]; + if (part.includes("/")) return true; + const match = matcher[j](inputParts[j]); + if (!match) break; + if (globstarEnabled && part === "**") return true; + j++; + } + if (j === inputPatternCount) return true; + } + return false; + }; +} +/* node:coverage ignore next 2 */ +const WIN32_ROOT_DIR = /^[A-Z]:\/$/i; +const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/"; +function buildFormat(cwd, root, absolute) { + if (cwd === root || root.startsWith(`${cwd}/`)) { + if (absolute) { + const start = isRoot(cwd) ? cwd.length : cwd.length + 1; + return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || "."; + } + const prefix = root.slice(cwd.length + 1); + if (prefix) return (p, isDir) => { + if (p === ".") return prefix; + const result = `${prefix}/${p}`; + return isDir ? result.slice(0, -1) : result; + }; + return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p; + } + if (absolute) return (p) => posix.relative(cwd, p) || "."; + return (p) => posix.relative(cwd, `${root}/${p}`) || "."; +} +function buildRelative(cwd, root) { + if (root.startsWith(`${cwd}/`)) { + const prefix = root.slice(cwd.length + 1); + return (p) => `${prefix}/${p}`; + } + return (p) => { + const result = posix.relative(cwd, `${root}/${p}`); + if (p.endsWith("/") && result !== "") return `${result}/`; + return result || "."; + }; +} +const splitPatternOptions = { parts: true }; +function splitPattern(path$1) { + var _result$parts; + const result = picomatch.scan(path$1, splitPatternOptions); + return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1]; +} +const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g; +function convertPosixPathToPattern(path$1) { + return escapePosixPath(path$1); +} +function convertWin32PathToPattern(path$1) { + return escapeWin32Path(path$1).replace(ESCAPED_WIN32_BACKSLASHES, "/"); +} +/** +* Converts a path to a pattern depending on the platform. +* Identical to {@link escapePath} on POSIX systems. +* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern} +*/ +/* node:coverage ignore next 3 */ +const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern; +const POSIX_UNESCAPED_GLOB_SYMBOLS = /(? path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +const escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"); +/** +* Escapes a path's special characters depending on the platform. +* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath} +*/ +/* node:coverage ignore next */ +const escapePath = isWin ? escapeWin32Path : escapePosixPath; +/** +* Checks if a pattern has dynamic parts. +* +* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy: +* +* - Doesn't necessarily return `false` on patterns that include `\`. +* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not. +* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`. +* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`. +* +* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern} +*/ +function isDynamicPattern(pattern, options) { + if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true; + const scan = picomatch.scan(pattern); + return scan.isGlob || scan.negated; +} +function log(...tasks) { + console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks); +} + +//#endregion +//#region src/index.ts +const PARENT_DIRECTORY = /^(\/?\.\.)+/; +const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g; +const BACKSLASHES = /\\/g; +function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) { + let result = pattern; + if (pattern.endsWith("/")) result = pattern.slice(0, -1); + if (!result.endsWith("*") && expandDirectories) result += "/**"; + const escapedCwd = escapePath(cwd); + if (path.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result); + else result = posix.normalize(result); + const parentDirectoryMatch = PARENT_DIRECTORY.exec(result); + const parts = splitPattern(result); + if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) { + const n = (parentDirectoryMatch[0].length + 1) / 3; + let i = 0; + const cwdParts = escapedCwd.split("/"); + while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) { + result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || "."; + i++; + } + const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3)); + if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) { + props.root = potentialRoot; + props.depthOffset = -n + i; + } + } + if (!isIgnore && props.depthOffset >= 0) { + var _props$commonPath; + (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts); + const newCommonPath = []; + const length = Math.min(props.commonPath.length, parts.length); + for (let i = 0; i < length; i++) { + const part = parts[i]; + if (part === "**" && !parts[i + 1]) { + newCommonPath.pop(); + break; + } + if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break; + newCommonPath.push(part); + } + props.depthOffset = newCommonPath.length; + props.commonPath = newCommonPath; + props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd; + } + return result; +} +function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) { + if (typeof patterns === "string") patterns = [patterns]; + if (typeof ignore === "string") ignore = [ignore]; + const matchPatterns = []; + const ignorePatterns = []; + for (const pattern of ignore) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true)); + } + for (const pattern of patterns) { + if (!pattern) continue; + if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false)); + else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true)); + } + return { + match: matchPatterns, + ignore: ignorePatterns + }; +} +function formatPaths(paths, relative) { + for (let i = paths.length - 1; i >= 0; i--) { + const path$1 = paths[i]; + paths[i] = relative(path$1); + } + return paths; +} +function normalizeCwd(cwd) { + if (!cwd) return process.cwd().replace(BACKSLASHES, "/"); + if (cwd instanceof URL) return fileURLToPath(cwd).replace(BACKSLASHES, "/"); + return path.resolve(cwd).replace(BACKSLASHES, "/"); +} +function getCrawler(patterns, inputOptions = {}) { + const options = process.env.TINYGLOBBY_DEBUG ? { + ...inputOptions, + debug: true + } : inputOptions; + const cwd = normalizeCwd(options.cwd); + if (options.debug) log("globbing with:", { + patterns, + options, + cwd + }); + if (Array.isArray(patterns) && patterns.length === 0) return [{ + sync: () => [], + withPromise: async () => [] + }, false]; + const props = { + root: cwd, + commonPath: null, + depthOffset: 0 + }; + const processed = processPatterns({ + ...options, + patterns + }, cwd, props); + if (options.debug) log("internal processing patterns:", processed); + const matchOptions = { + dot: options.dot, + nobrace: options.braceExpansion === false, + nocase: options.caseSensitiveMatch === false, + noextglob: options.extglob === false, + noglobstar: options.globstar === false, + posix: true + }; + const matcher = picomatch(processed.match, { + ...matchOptions, + ignore: processed.ignore + }); + const ignore = picomatch(processed.ignore, matchOptions); + const partialMatcher = getPartialMatcher(processed.match, matchOptions); + const format = buildFormat(cwd, props.root, options.absolute); + const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true); + const fdirOptions = { + filters: [options.debug ? (p, isDirectory) => { + const path$1 = format(p, isDirectory); + const matches = matcher(path$1); + if (matches) log(`matched ${path$1}`); + return matches; + } : (p, isDirectory) => matcher(format(p, isDirectory))], + exclude: options.debug ? (_, p) => { + const relativePath = formatExclude(p, true); + const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); + if (skipped) log(`skipped ${p}`); + else log(`crawling ${p}`); + return skipped; + } : (_, p) => { + const relativePath = formatExclude(p, true); + return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath); + }, + fs: options.fs ? { + readdir: options.fs.readdir || nativeFs.readdir, + readdirSync: options.fs.readdirSync || nativeFs.readdirSync, + realpath: options.fs.realpath || nativeFs.realpath, + realpathSync: options.fs.realpathSync || nativeFs.realpathSync, + stat: options.fs.stat || nativeFs.stat, + statSync: options.fs.statSync || nativeFs.statSync + } : void 0, + pathSeparator: "/", + relativePaths: true, + resolveSymlinks: true, + signal: options.signal + }; + if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset); + if (options.absolute) { + fdirOptions.relativePaths = false; + fdirOptions.resolvePaths = true; + fdirOptions.includeBasePath = true; + } + if (options.followSymbolicLinks === false) { + fdirOptions.resolveSymlinks = false; + fdirOptions.excludeSymlinks = true; + } + if (options.onlyDirectories) { + fdirOptions.excludeFiles = true; + fdirOptions.includeDirs = true; + } else if (options.onlyFiles === false) fdirOptions.includeDirs = true; + props.root = props.root.replace(BACKSLASHES, ""); + const root = props.root; + if (options.debug) log("internal properties:", props); + const relative = cwd !== root && !options.absolute && buildRelative(cwd, props.root); + return [new fdir(fdirOptions).crawl(root), relative]; +} +async function glob(patternsOrOptions, options) { + if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); + const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string"; + const opts = isModern ? options : patternsOrOptions; + const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns; + const [crawler, relative] = getCrawler(patterns, opts); + if (!relative) return crawler.withPromise(); + return formatPaths(await crawler.withPromise(), relative); +} +function globSync(patternsOrOptions, options) { + if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option"); + const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string"; + const opts = isModern ? options : patternsOrOptions; + const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns; + const [crawler, relative] = getCrawler(patterns, opts); + if (!relative) return crawler.sync(); + return formatPaths(crawler.sync(), relative); +} + +//#endregion +export { convertPathToPattern, escapePath, glob, globSync, isDynamicPattern }; \ No newline at end of file diff --git a/node_modules/tinyglobby/package.json b/node_modules/tinyglobby/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d0247c25ae3a1edddcd9ae2eba9888aca5a604f0 --- /dev/null +++ b/node_modules/tinyglobby/package.json @@ -0,0 +1,73 @@ +{ + "name": "tinyglobby", + "version": "0.2.15", + "description": "A fast and minimal alternative to globby and fast-glob", + "type": "module", + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.cts", + "exports": { + ".": { + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist" + ], + "author": "Superchupu", + "license": "MIT", + "keywords": [ + "glob", + "patterns", + "fast", + "implementation" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/SuperchupuDev/tinyglobby.git" + }, + "bugs": { + "url": "https://github.com/SuperchupuDev/tinyglobby/issues" + }, + "homepage": "https://superchupu.dev/tinyglobby", + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + }, + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "devDependencies": { + "@biomejs/biome": "^2.2.3", + "@types/node": "^24.3.1", + "@types/picomatch": "^4.0.2", + "fast-glob": "^3.3.3", + "fs-fixture": "^2.8.1", + "glob": "^11.0.3", + "tinybench": "^5.0.1", + "tsdown": "^0.14.2", + "typescript": "^5.9.2" + }, + "engines": { + "node": ">=12.0.0" + }, + "publishConfig": { + "provenance": true + }, + "scripts": { + "bench": "node benchmark/bench.ts", + "bench:setup": "node benchmark/setup.ts", + "build": "tsdown", + "check": "biome check", + "check:fix": "biome check --write --unsafe", + "format": "biome format --write", + "lint": "biome lint", + "test": "node --test \"test/**/*.ts\"", + "test:coverage": "node --test --experimental-test-coverage \"test/**/*.ts\"", + "test:only": "node --test --test-only \"test/**/*.ts\"", + "typecheck": "tsc --noEmit" + } +} \ No newline at end of file diff --git a/node_modules/tinyqueue/LICENSE b/node_modules/tinyqueue/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2b7cd9d34ce49efe275c407edad891f7db085052 --- /dev/null +++ b/node_modules/tinyqueue/LICENSE @@ -0,0 +1,15 @@ +ISC License + +Copyright (c) 2017, Vladimir Agafonkin + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/tinyqueue/README.md b/node_modules/tinyqueue/README.md new file mode 100644 index 0000000000000000000000000000000000000000..32843f59c1d254fcafa129738d39048a1dfb1a94 --- /dev/null +++ b/node_modules/tinyqueue/README.md @@ -0,0 +1,59 @@ +## tinyqueue + +The smallest and simplest binary heap priority queue in JavaScript. + +```js +// create an empty priority queue +var queue = new TinyQueue(); + +// add some items +queue.push(7); +queue.push(5); +queue.push(10); + +// remove the top item +var top = queue.pop(); // returns 5 + +// return the top item (without removal) +top = queue.peek(); // returns 7 + +// get queue length +queue.length; // returns 2 + +// create a priority queue from an existing array (modifies the array) +queue = new TinyQueue([7, 5, 10]); + +// pass a custom item comparator as a second argument +queue = new TinyQueue([{value: 5}, {value: 7}], function (a, b) { + return a.value - b.value; +}); + +// turn a queue into a sorted array +var array = []; +while (queue.length) array.push(queue.pop()); +``` + +For a faster number-based queue, see [flatqueue](https://github.com/mourner/flatqueue). + +### Install + +Install using NPM (`npm install tinyqueue`) or Yarn (`yarn add tinyqueue`), then: + +```js +// import as an ES module +import TinyQueue from 'tinyqueue'; + +// or require in Node / Browserify +const TinyQueue = require('tinyqueue'); +``` + +Or use a browser build directly: + +```html + +``` + +### Thanks + +Inspired by [js-priority-queue](https://github.com/adamhooper/js-priority-queue) +by [Adam Hooper](https://github.com/adamhooper). diff --git a/node_modules/tinyqueue/index.d.ts b/node_modules/tinyqueue/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..89b562abca3b6272b5a7ca7568a93ef912db3f11 --- /dev/null +++ b/node_modules/tinyqueue/index.d.ts @@ -0,0 +1,11 @@ +export declare type Item = any; +export declare type Comparator = (a: Item, b: Item) => number; + +export default class TinyQueue { + public data : Item[]; + public length : number; + constructor (items? : Item[], compare? : Comparator); + peek () : Item | undefined; + pop () : Item | undefined; + push (item: Item) : void; +} diff --git a/node_modules/tinyqueue/index.js b/node_modules/tinyqueue/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d1a4ae7e4ea47f17673853bd09bd27cb0c6cb499 --- /dev/null +++ b/node_modules/tinyqueue/index.js @@ -0,0 +1,79 @@ + +export default class TinyQueue { + constructor(data = [], compare = defaultCompare) { + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i); + } + } + + push(item) { + this.data.push(item); + this.length++; + this._up(this.length - 1); + } + + pop() { + if (this.length === 0) return undefined; + + const top = this.data[0]; + const bottom = this.data.pop(); + this.length--; + + if (this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; + } + + peek() { + return this.data[0]; + } + + _up(pos) { + const {data, compare} = this; + const item = data[pos]; + + while (pos > 0) { + const parent = (pos - 1) >> 1; + const current = data[parent]; + if (compare(item, current) >= 0) break; + data[pos] = current; + pos = parent; + } + + data[pos] = item; + } + + _down(pos) { + const {data, compare} = this; + const halfLength = this.length >> 1; + const item = data[pos]; + + while (pos < halfLength) { + let left = (pos << 1) + 1; + let best = data[left]; + const right = left + 1; + + if (right < this.length && compare(data[right], best) < 0) { + left = right; + best = data[right]; + } + if (compare(best, item) >= 0) break; + + data[pos] = best; + pos = left; + } + + data[pos] = item; + } +} + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} diff --git a/node_modules/tinyqueue/package.json b/node_modules/tinyqueue/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d731affd6bfb76fb7312b861315b36bcb01b62a9 --- /dev/null +++ b/node_modules/tinyqueue/package.json @@ -0,0 +1,53 @@ +{ + "name": "tinyqueue", + "version": "2.0.3", + "description": "The smallest and simplest JavaScript priority queue", + "main": "tinyqueue.js", + "module": "index.js", + "jsdelivr": "tinyqueue.min.js", + "unpkg": "tinyqueue.min.js", + "types": "index.d.ts", + "scripts": { + "lint": "eslint index.js test.js bench.js rollup.config.js", + "pretest": "npm run lint", + "test": "tape -r esm test.js", + "bench": "node -r esm bench.js", + "build": "rollup -c", + "watch": "rollup -cw", + "prepublishOnly": "npm test" + }, + "files": [ + "index.js", + "tinyqueue.js", + "tinyqueue.min.js", + "index.d.ts" + ], + "repository": { + "type": "git", + "url": "https://github.com/mourner/tinyqueue.git" + }, + "keywords": [ + "queue", + "priority", + "binary heap", + "data structures" + ], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/mourner/tinyqueue/issues" + }, + "homepage": "https://github.com/mourner/tinyqueue", + "devDependencies": { + "eslint": "^5.16.0", + "eslint-config-mourner": "^3.0.0", + "esm": "^3.2.25", + "rollup": "^1.15.4", + "rollup-plugin-buble": "^0.19.6", + "rollup-plugin-terser": "^5.0.0", + "tape": "^4.10.2" + }, + "eslintConfig": { + "extends": "mourner" + } +} diff --git a/node_modules/tinyqueue/tinyqueue.js b/node_modules/tinyqueue/tinyqueue.js new file mode 100644 index 0000000000000000000000000000000000000000..0d4171643ae99fa072b5d892ab67620369a7f5ad --- /dev/null +++ b/node_modules/tinyqueue/tinyqueue.js @@ -0,0 +1,93 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : +typeof define === 'function' && define.amd ? define(factory) : +(global = global || self, global.TinyQueue = factory()); +}(this, function () { 'use strict'; + +var TinyQueue = function TinyQueue(data, compare) { + if ( data === void 0 ) data = []; + if ( compare === void 0 ) compare = defaultCompare; + + this.data = data; + this.length = this.data.length; + this.compare = compare; + + if (this.length > 0) { + for (var i = (this.length >> 1) - 1; i >= 0; i--) { this._down(i); } + } +}; + +TinyQueue.prototype.push = function push (item) { + this.data.push(item); + this.length++; + this._up(this.length - 1); +}; + +TinyQueue.prototype.pop = function pop () { + if (this.length === 0) { return undefined; } + + var top = this.data[0]; + var bottom = this.data.pop(); + this.length--; + + if (this.length > 0) { + this.data[0] = bottom; + this._down(0); + } + + return top; +}; + +TinyQueue.prototype.peek = function peek () { + return this.data[0]; +}; + +TinyQueue.prototype._up = function _up (pos) { + var ref = this; + var data = ref.data; + var compare = ref.compare; + var item = data[pos]; + + while (pos > 0) { + var parent = (pos - 1) >> 1; + var current = data[parent]; + if (compare(item, current) >= 0) { break; } + data[pos] = current; + pos = parent; + } + + data[pos] = item; +}; + +TinyQueue.prototype._down = function _down (pos) { + var ref = this; + var data = ref.data; + var compare = ref.compare; + var halfLength = this.length >> 1; + var item = data[pos]; + + while (pos < halfLength) { + var left = (pos << 1) + 1; + var best = data[left]; + var right = left + 1; + + if (right < this.length && compare(data[right], best) < 0) { + left = right; + best = data[right]; + } + if (compare(best, item) >= 0) { break; } + + data[pos] = best; + pos = left; + } + + data[pos] = item; +}; + +function defaultCompare(a, b) { + return a < b ? -1 : a > b ? 1 : 0; +} + +return TinyQueue; + +})); diff --git a/node_modules/tinyqueue/tinyqueue.min.js b/node_modules/tinyqueue/tinyqueue.min.js new file mode 100644 index 0000000000000000000000000000000000000000..a15a796c7acb6913285e58e720c462c5194b7ed1 --- /dev/null +++ b/node_modules/tinyqueue/tinyqueue.min.js @@ -0,0 +1 @@ +!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t=t||self).TinyQueue=i()}(this,function(){"use strict";var t=function(t,e){if(void 0===t&&(t=[]),void 0===e&&(e=i),this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(var n=(this.length>>1)-1;n>=0;n--)this._down(n)};function i(t,i){return ti?1:0}return t.prototype.push=function(t){this.data.push(t),this.length++,this._up(this.length-1)},t.prototype.pop=function(){if(0!==this.length){var t=this.data[0],i=this.data.pop();return this.length--,this.length>0&&(this.data[0]=i,this._down(0)),t}},t.prototype.peek=function(){return this.data[0]},t.prototype._up=function(t){for(var i=this.data,e=this.compare,n=i[t];t>0;){var o=t-1>>1,h=i[o];if(e(n,h)>=0)break;i[t]=h,t=o}i[t]=n},t.prototype._down=function(t){for(var i=this.data,e=this.compare,n=this.length>>1,o=i[t];t=0)break;i[t]=s,t=h}i[t]=o},t}); diff --git a/node_modules/to-buffer/.github/FUNDING.yml b/node_modules/to-buffer/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..4a0079cbc96a3fae3a193fc52b7ab0073493bc14 --- /dev/null +++ b/node_modules/to-buffer/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb, mafintosh] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/to-buffer +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/to-buffer/CHANGELOG.md b/node_modules/to-buffer/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..71a18729d85a46bceb700be23c356f59a06a0e70 --- /dev/null +++ b/node_modules/to-buffer/CHANGELOG.md @@ -0,0 +1,81 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.2](https://github.com/browserify/to-buffer/compare/v1.2.1...v1.2.2) - 2025-09-24 + +### Commits + +- [Fix] handle SlowBuffers in node 0.10 [`ca20eaa`](https://github.com/browserify/to-buffer/commit/ca20eaad8c9cbd6e3e6e99880b2b1c95abe62566) +- [Refactor] use `SafeBuffer.isBuffer` instead of `instanceof` [`81283c1`](https://github.com/browserify/to-buffer/commit/81283c14b585c0e921e04f327381e975cc8561bb) +- [Dev Deps] update `@ljharb/eslint-config` [`c7bc986`](https://github.com/browserify/to-buffer/commit/c7bc986d378ce4bdf2dac75612b45b0f618f26d6) +- [meta] since tests are npmignored, also npmignore test config files [`866639c`](https://github.com/browserify/to-buffer/commit/866639cf294799f8c0397153e5876ae1e6992a57) + +## [v1.2.1](https://github.com/browserify/to-buffer/compare/v1.2.0...v1.2.1) - 2025-06-19 + +### Commits + +- [Fix] handle non-Uint8Arrays in node < 3 [`7f8a881`](https://github.com/browserify/to-buffer/commit/7f8a881929133935f8e15ffd60d6dbbc513b2c5f) +- [Tests] add coverage [`286c96a`](https://github.com/browserify/to-buffer/commit/286c96a52cfeee14a2ba974d78071bdd667e9360) +- [Fix] provide a fallback for engines without `ArrayBuffer.isView` [`e336166`](https://github.com/browserify/to-buffer/commit/e336166b8f4bf13860bafa191ee1ec53fca2e331) +- [Fix] correct error message [`b45247e`](https://github.com/browserify/to-buffer/commit/b45247ed337fb44b2c8d74a14e8f86d985119fb9) + +## [v1.2.0](https://github.com/browserify/to-buffer/compare/v1.1.1...v1.2.0) - 2025-06-17 + +### Commits + +- [New] replace with implementation from cipher-base [`970adb5`](https://github.com/browserify/to-buffer/commit/970adb5523efdaa13f5ecb82967fc9f617865549) +- [Tests] migrate from travis to GHA [`8084393`](https://github.com/browserify/to-buffer/commit/808439337ca9ac3dbb8399079aaa2a4cb738627c) +- [eslint] fix whitespace [`a62e651`](https://github.com/browserify/to-buffer/commit/a62e651b661adf98c17e9e486b55bb8ff0ffb8c9) +- [eslint] fix semicolon usage [`4d85c63`](https://github.com/browserify/to-buffer/commit/4d85c6318c72feae8d19037937154f9b99ba266f) +- [meta] add `auto-changelog` [`aa0279c`](https://github.com/browserify/to-buffer/commit/aa0279c5199ca7fe39acfb950a4c824e97f06232) +- [readme] update URLs, add badges [`ff77d90`](https://github.com/browserify/to-buffer/commit/ff77d90b89de7b02538ecb2d6a89da086093bed8) +- [lint] switch to eslint [`e45f467`](https://github.com/browserify/to-buffer/commit/e45f467c7229e632cd3c10fc02895ba4d3204bbe) +- [Fix] validate that arrays contain valid byte values [`c2fb75e`](https://github.com/browserify/to-buffer/commit/c2fb75edf2fb113d58599e990f86574b4dfa62d8) +- [Fix] restore previous implementation Array behavior [`cb93b75`](https://github.com/browserify/to-buffer/commit/cb93b75a79caa9897f6c29ecde91f4ae35f704fe) +- [Tests] add nyc for coverage [`ab7026e`](https://github.com/browserify/to-buffer/commit/ab7026e36e3716c8101229f426e7f4571e55794b) +- [Refactor] use `safe-buffer`.from instead of `buffer-from` [`8e01307`](https://github.com/browserify/to-buffer/commit/8e01307191245044469e47695c5c2675b85e84e9) +- [Fix] Replace Buffer.from with `buffer-from` [`d652e54`](https://github.com/browserify/to-buffer/commit/d652e54e2396a47358a553c447e0f338b4c2dc67) +- [Tests] use `deepEqual` over `same` alias [`66a5548`](https://github.com/browserify/to-buffer/commit/66a55480258011bb5d81c5aad1360468f418d0b4) +- [meta] add `npmignore` [`90ce602`](https://github.com/browserify/to-buffer/commit/90ce6023737d50521aff44d87063db1e3f7e352a) +- [Tests] move into a test dir, update tape [`08aea81`](https://github.com/browserify/to-buffer/commit/08aea81b61b90d1fcb7e9275b5b0ba718531d9a8) +- Only apps should have lockfiles [`16ccceb`](https://github.com/browserify/to-buffer/commit/16ccceb23f350be16e80111188c90a3492916f5d) +- [Tests] add coverage [`d2cba2e`](https://github.com/browserify/to-buffer/commit/d2cba2ec76ed43c83e2a7a91f58fa7640aeb61e9) +- [meta] update description [`2cf2a20`](https://github.com/browserify/to-buffer/commit/2cf2a200a31f9543d2e8a24b5ea0e8bd843166c3) +- [Fix] add `safe-buffer`, missing from 970adb5 [`d9a0dea`](https://github.com/browserify/to-buffer/commit/d9a0dead7c638d188f8b48cdf2b5fd6cfa886071) +- [meta] temporarily limit support to node v0.10 [`8dca458`](https://github.com/browserify/to-buffer/commit/8dca458bd9a2c6b84d6e3a1996e41b242fe1c49a) +- [meta] add missing `engines.node` [`35bdfcb`](https://github.com/browserify/to-buffer/commit/35bdfcb3a71dfbd5b35d35250c9dac19c99f4197) +- [Dev Deps] add missing peer dep [`220143f`](https://github.com/browserify/to-buffer/commit/220143f1f6e47154380c27a2d88ce300104007fa) +- [meta] add `sideEffects` flag [`cd37473`](https://github.com/browserify/to-buffer/commit/cd374738d24b22b029862b3c27b9e247d4e62daf) + +## [v1.1.1](https://github.com/browserify/to-buffer/compare/v1.1.0...v1.1.1) - 2018-04-26 + +### Commits + +- use Buffer.from when avail [`eebe20e`](https://github.com/browserify/to-buffer/commit/eebe20e0603e2c6a542b00316f1661741fdf1124) + +## [v1.1.0](https://github.com/browserify/to-buffer/compare/v1.0.1...v1.1.0) - 2017-04-12 + +### Merged + +- Fix typo [`#2`](https://github.com/browserify/to-buffer/pull/2) + +### Commits + +- support arrays as well [`ef98c82`](https://github.com/browserify/to-buffer/commit/ef98c82791d71601077577e84c4614ec2d05f086) + +## [v1.0.1](https://github.com/browserify/to-buffer/compare/v1.0.0...v1.0.1) - 2016-02-15 + +### Commits + +- fix desc [`7d50a7c`](https://github.com/browserify/to-buffer/commit/7d50a7c69c3eef77448893744ada16601c44af6a) + +## v1.0.0 - 2016-02-15 + +### Commits + +- first commit [`8361941`](https://github.com/browserify/to-buffer/commit/8361941d7acb3b82c732ecd10bdb047da5af2028) +- add travis [`de911b5`](https://github.com/browserify/to-buffer/commit/de911b5364558561d84b4ec9e43c6a0fe1c8e904) diff --git a/node_modules/to-buffer/LICENSE b/node_modules/to-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..bae9da7bfae2b5e22cfb0945b362b23ca822c8bb --- /dev/null +++ b/node_modules/to-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Mathias Buus + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/to-buffer/README.md b/node_modules/to-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c7ff8bf98e5a253de7e48cff7387ac06e8717e21 --- /dev/null +++ b/node_modules/to-buffer/README.md @@ -0,0 +1,44 @@ +# to-buffer [![Version Badge][2]][1] + +Pass in a string, array, Buffer, Data View, or Uint8Array, and get a Buffer back. + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + + +``` +npm install to-buffer +``` + +## Usage + +``` js +var toBuffer = require('to-buffer'); + +console.log(toBuffer('hi')); // +console.log(toBuffer(Buffer('hi'))); // +console.log(toBuffer('6869', 'hex')); // +console.log(toBuffer(43)); // throws +``` + +[1]: https://npmjs.org/package/to-buffer +[2]: https://versionbadg.es/browserify/to-buffer.svg +[5]: https://david-dm.org/browserify/to-buffer.svg +[6]: https://david-dm.org/browserify/to-buffer +[7]: https://david-dm.org/browserify/to-buffer/dev-status.svg +[8]: https://david-dm.org/browserify/to-buffer#info=devDependencies +[11]: https://nodei.co/npm/to-buffer.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/to-buffer.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/to-buffer.svg +[downloads-url]: https://npm-stat.com/charts.html?package=to-buffer +[codecov-image]: https://codecov.io/gh/browserify/to-buffer/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/browserify/to-buffer/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/browserify/to-buffer +[actions-url]: https://github.com/browserify/to-buffer/actions diff --git a/node_modules/to-buffer/index.js b/node_modules/to-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c4a348ceb110ad0fb2b0b44c1b31a4abfecc9027 --- /dev/null +++ b/node_modules/to-buffer/index.js @@ -0,0 +1,109 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; +var isArray = require('isarray'); +var typedArrayBuffer = require('typed-array-buffer'); + +var isView = ArrayBuffer.isView || function isView(obj) { + try { + typedArrayBuffer(obj); + return true; + } catch (e) { + return false; + } +}; + +var useUint8Array = typeof Uint8Array !== 'undefined'; +var useArrayBuffer = typeof ArrayBuffer !== 'undefined' + && typeof Uint8Array !== 'undefined'; +var useFromArrayBuffer = useArrayBuffer && (Buffer.prototype instanceof Uint8Array || Buffer.TYPED_ARRAY_SUPPORT); + +module.exports = function toBuffer(data, encoding) { + if (Buffer.isBuffer(data)) { + if (data.constructor && !('isBuffer' in data)) { + // probably a SlowBuffer + return Buffer.from(data); + } + return data; + } + + if (typeof data === 'string') { + return Buffer.from(data, encoding); + } + + /* + * Wrap any TypedArray instances and DataViews + * Makes sense only on engines with full TypedArray support -- let Buffer detect that + */ + if (useArrayBuffer && isView(data)) { + // Bug in Node.js <6.3.1, which treats this as out-of-bounds + if (data.byteLength === 0) { + return Buffer.alloc(0); + } + + // When Buffer is based on Uint8Array, we can just construct it from ArrayBuffer + if (useFromArrayBuffer) { + var res = Buffer.from(data.buffer, data.byteOffset, data.byteLength); + /* + * Recheck result size, as offset/length doesn't work on Node.js <5.10 + * We just go to Uint8Array case if this fails + */ + if (res.byteLength === data.byteLength) { + return res; + } + } + + // Convert to Uint8Array bytes and then to Buffer + var uint8 = data instanceof Uint8Array ? data : new Uint8Array(data.buffer, data.byteOffset, data.byteLength); + var result = Buffer.from(uint8); + + /* + * Let's recheck that conversion succeeded + * We have .length but not .byteLength when useFromArrayBuffer is false + */ + if (result.length === data.byteLength) { + return result; + } + } + + /* + * Uint8Array in engines where Buffer.from might not work with ArrayBuffer, just copy over + * Doesn't make sense with other TypedArray instances + */ + if (useUint8Array && data instanceof Uint8Array) { + return Buffer.from(data); + } + + var isArr = isArray(data); + if (isArr) { + for (var i = 0; i < data.length; i += 1) { + var x = data[i]; + if ( + typeof x !== 'number' + || x < 0 + || x > 255 + || ~~x !== x // NaN and integer check + ) { + throw new RangeError('Array items must be numbers in the range 0-255.'); + } + } + } + + /* + * Old Buffer polyfill on an engine that doesn't have TypedArray support + * Also, this is from a different Buffer polyfill implementation then we have, as instanceof check failed + * Convert to our current Buffer implementation + */ + if ( + isArr || ( + Buffer.isBuffer(data) + && data.constructor + && typeof data.constructor.isBuffer === 'function' + && data.constructor.isBuffer(data) + ) + ) { + return Buffer.from(data); + } + + throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.'); +}; diff --git a/node_modules/to-buffer/package.json b/node_modules/to-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..55847c80f3a7140a2336c98f618850c4abb6a5e4 --- /dev/null +++ b/node_modules/to-buffer/package.json @@ -0,0 +1,62 @@ +{ + "name": "to-buffer", + "version": "1.2.2", + "description": "Pass in a string, array, Buffer, Data View, or Uint8Array, and get a Buffer back.", + "main": "index.js", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*'", + "test": "npm run tests-only", + "posttest": "npx npm@\">= 10.2\" audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "https://github.com/browserify/to-buffer.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/browserify/to-buffer/issues" + }, + "homepage": "https://github.com/browserify/to-buffer", + "dependencies": { + "isarray": "^2.0.5", + "safe-buffer": "^5.2.1", + "typed-array-buffer": "^1.0.3" + }, + "devDependencies": { + "@ljharb/eslint-config": "^21.2.0", + "auto-changelog": "^2.5.0", + "available-typed-arrays": "^1.0.7", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "for-each": "^0.3.5", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "tape": "^5.9.0" + }, + "engines": { + "node": ">= 0.4" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + ".eslintrc", + ".nycrc", + "test" + ] + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + } +} diff --git a/node_modules/to-float32/.eslintrc.json b/node_modules/to-float32/.eslintrc.json new file mode 100644 index 0000000000000000000000000000000000000000..aaddba5b39068c80de411f77eb6cb292221d69c7 --- /dev/null +++ b/node_modules/to-float32/.eslintrc.json @@ -0,0 +1,44 @@ +{ + "env": { + "browser": true, + "node": true, + "commonjs": true, + "es6": true + }, + "extends": "eslint:recommended", + "rules": { + "strict": 2, + "indent": 0, + "linebreak-style": 0, + "quotes": 0, + "semi": 0, + "no-cond-assign": 1, + "no-constant-condition": 1, + "no-duplicate-case": 1, + "no-empty": 1, + "no-ex-assign": 1, + "no-extra-boolean-cast": 1, + "no-extra-semi": 1, + "no-fallthrough": 1, + "no-func-assign": 1, + "no-global-assign": 1, + "no-implicit-globals": 2, + "no-inner-declarations": ["error", "functions"], + "no-irregular-whitespace": 2, + "no-loop-func": 1, + "no-magic-numbers": ["warn", { "ignore": [1, 0, -1], "ignoreArrayIndexes": true}], + "no-multi-str": 1, + "no-mixed-spaces-and-tabs": 1, + "no-proto": 1, + "no-sequences": 1, + "no-throw-literal": 1, + "no-unmodified-loop-condition": 1, + "no-useless-call": 1, + "no-void": 1, + "no-with": 2, + "wrap-iife": 1, + "no-redeclare": 1, + "no-unused-vars": ["error", { "vars": "all", "args": "none" }], + "no-sparse-arrays": 1 + } +} diff --git a/node_modules/to-float32/.travis.yml b/node_modules/to-float32/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..c8cd2d2da23a6906ace23c3074a843962557033f --- /dev/null +++ b/node_modules/to-float32/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - '6' + - '5' + - '4' diff --git a/node_modules/to-float32/index.js b/node_modules/to-float32/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1dca46477edcbad43e841178b8b01ddc2de1c8b7 --- /dev/null +++ b/node_modules/to-float32/index.js @@ -0,0 +1,38 @@ +/* @module to-float32 */ + +'use strict' + +module.exports = float32 +module.exports.float32 = +module.exports.float = float32 +module.exports.fract32 = +module.exports.fract = fract32 + +var narr = new Float32Array(1) + +// Returns fractional part of float32 array +function fract32 (arr, fract) { + if (arr.length) { + if (arr instanceof Float32Array) return new Float32Array(arr.length); + if (!(fract instanceof Float32Array)) fract = float32(arr) + for (var i = 0, l = fract.length; i < l; i++) { + fract[i] = arr[i] - fract[i] + } + return fract + } + + // number + return float32(arr - float32(arr)) +} + +// Make sure data is float32 array +function float32 (arr) { + if (arr.length) { + if (arr instanceof Float32Array) return arr + return new Float32Array(arr); + } + + // number + narr[0] = arr + return narr[0] +} diff --git a/node_modules/to-float32/license b/node_modules/to-float32/license new file mode 100644 index 0000000000000000000000000000000000000000..fb2315440d1b16cfeb3eb2d46152c8bd110280c2 --- /dev/null +++ b/node_modules/to-float32/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/to-float32/package.json b/node_modules/to-float32/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4b02c1f28c171b90280f8bfbce88ad6443202e7d --- /dev/null +++ b/node_modules/to-float32/package.json @@ -0,0 +1,25 @@ +{ + "name": "to-float32", + "version": "1.1.0", + "description": "Convert data to float32 array or get float32 fractions", + "main": "index.js", + "scripts": { + "test": "node test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/dy/to-float32.git" + }, + "keywords": [ + "float32", + "fract32", + "webgl" + ], + "author": "Dmitry Yv. ", + "license": "MIT", + "bugs": { + "url": "https://github.com/dy/to-float32/issues" + }, + "homepage": "https://github.com/dy/to-float32#readme", + "dependencies": {} +} diff --git a/node_modules/to-float32/readme.md b/node_modules/to-float32/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9c2dd0f042106257d72428f6ec5f6a92c7dd232a --- /dev/null +++ b/node_modules/to-float32/readme.md @@ -0,0 +1,29 @@ +# to-float32 [![unstable](https://img.shields.io/badge/stability-unstable-green.svg)](http://github.com/badges/stability-badges) [![Build Status](https://travis-ci.org/dy/to-uint8.svg?branch=master)](https://travis-ci.org/dy/to-uint8) + +Dirty little helper to convert array to float32 array or return round remainder of converting to float32. Useful for sending data to webgl buffers. + +[![npm install to-float32](https://nodei.co/npm/to-float32.png?mini=true)](https://npmjs.org/package/to-float32/) + +```js +let {float32, fract32} = require('to-float32') + +let data = Array.from({length: 1024}, Math.random) + +// create float32 data +let buffer = float(data) + +// get float32 remainders +let fractBuffer = fract32(data) + +// convert number to float32 +let f32 = float32(0.1) // 0.10000000149011612 + +// get float32 number remainder +let rem32 = fract32(0.1) // +``` + +Fract data is _Float32Array_ with values calculated as `origValue - float32value` + +## License + +(c) 2017 Dmitry Yv. MIT License