diff --git a/.circleci/config.yml b/.circleci/config.yml index fca7761e..895b716e 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,39 +1,19 @@ -# Javascript Node CircleCI 2.0 configuration file -# -# Check https://circleci.com/docs/2.0/language-javascript/ for more details -# -version: 2 +version: 2.1 +orbs: + node: circleci/node@1.1.6 jobs: - build: - docker: - # specify the version you desire here - - image: circleci/node:10.3 - - # Specify service dependencies here if necessary - # CircleCI maintains a library of pre-built images - # documented at https://circleci.com/docs/2.0/circleci-images/ - # - image: circleci/mongo:3.4.4 - - working_directory: ~/repo - + build-and-test: + executor: + name: node/default steps: - checkout - - # Download and cache dependencies - - restore_cache: - keys: - - v1-dependencies-{{ checksum "package.json" }} - # fallback to using the latest cache if no exact match is found - - v1-dependencies- - - - run: yarn install - - - save_cache: - paths: - - node_modules - key: v1-dependencies-{{ checksum "package.json" }} - - # run tests! - - run: yarn test + - node/with-cache: + steps: + - run: npm install + - run: npm test +workflows: + build-and-test: + jobs: + - build-and-test diff --git a/assets/Feature Branch Diagram.png b/assets/Feature Branch Diagram.png new file mode 100644 index 00000000..8bdb4077 Binary files /dev/null and b/assets/Feature Branch Diagram.png differ diff --git a/assets/GitHub Diagram.png b/assets/GitHub Diagram.png new file mode 100644 index 00000000..51331baf Binary files /dev/null and b/assets/GitHub Diagram.png differ diff --git a/assets/Jobs Screenshot.png b/assets/Jobs Screenshot.png new file mode 100644 index 00000000..e2264d7a Binary files /dev/null and b/assets/Jobs Screenshot.png differ diff --git a/labreports/LAB_Willnew98.md b/labreports/LAB_Willnew98.md new file mode 100644 index 00000000..0ff3e77a --- /dev/null +++ b/labreports/LAB_Willnew98.md @@ -0,0 +1,124 @@ +Course: Messiah College CIS 411, Spring 2020
+Instructors: [Joel Worrall](https://github.com/tangollama) & [Trevor Bunch](https://github.com/trevordbunch)
+Name: Will Newcomb
+GitHub: [Willnew98](https://github.com/Willnew98)
+ +# Step 1: Fork this repository +- https://github.com/Willnew98/cis411_lab0 +- https://github.com/Willnew98/cis411_lab0/blob/labreport/assets/GitHub%20Diagram.png + +# Step 2: Clone your forked repository from the command line +- My GraphQL response from adding myself as an account on the test project +``` +{ + "data": { + "mutateAccount": { + "id": "9e6928b4-cadf-4d1b-b927-836234b913af", + "name": "Will Newcomb", + "email": "wn1154@messiah.edu" + } + } +} +``` + +# Step 3: Creating a feature branch +- The output of my git commit log +``` +dabceca (origin/master, origin/HEAD, master) Merge pull request #24 from tangollama/circleci +a4096db Create README.md +2f01bf4 Update LAB_INSTRUCTIONS.md +347bd50 Update LAB_INSTRUCTIONS.md +7aaa9f3 Update LAB_INSTRUCTIONS.md +37393ae Bug fixed +1949d2a Update LAB_INSTRUCTIONS.md +d36ad90 Update LAB.md +59ef18a Update LAB_INSTRUCTIONS.md +37be3c8 Update LAB_INSTRUCTIONS.md +97da547 Update LAB.md +0bd6244 (origin/purelab) updated Step 0 title +4562cd8 added npm and node install repreq +255051e adding template +13a09b7 Adding the LAB.md and correcting some instructions. +d2ddea5 Version 0.0.1 of the lab isntructions +ab312fc more progress +62fb0a5 more progress +fe1937b more in the lab instructions +3e807fb first section + +``` +- The accompanying diagram of what my feature branch precisely and conceptually represents + + https://github.com/Willnew98/cis411_lab0/blob/labreport/assets/Feature%20Branch%20Diagram.png + + +# Step 4: Setup a Continuous Integration configuration +- What is the .circleci/config.yml doing? + + - It's building and testing my committed code with the master branch automatically, so I don't keep building the feature branch that might not work with the master. +- What do the various sections on the config file do? + + - The orbs seem to be packages that you can add to your script that come with certain tests build in so you don't have to reinvent anything. For instance, the reason I can use npm install and npm test is because I have the node orb incorperated. + + - The jobs tell you what job is being done. The first job is a build-and-test, which is precisely what it is doing. Inside the job it also will tell you the steps that need to be taken to complete this job, and it will run those steps automatically for you. + + - The workflow is just the order in which the jobs are ran. Since there's only one job, though, the order doesn't really matter. +- When a CI build is successful, what does that philosophically and practically/precisely indicate about the build? + + - When a build is successful that means that it passed all of the tests built to inspect the code, and it is now ready to be integrated into the master branch. +- If you were to take the next step and ready this project for Continuous Delivery, what additional changes might you make in this configuration (conceptual, not code)? + + - If I were to deploy it to something like Heroku, I think I could just add an orb for Heroku, and then use the workflow to deploy to Heroku after running some tests. + +# Step 5: Merging the feature branch +* The output of my git commit log +``` +0cad8aa (HEAD -> master, origin/master, origin/labreport, origin/HEAD, labreport) Answered CircleCI questions @tangollama +57a4434 added feature branch diagram to assets folder @tangollama +25911b1 added jobs screenshot to assets folder @tangollama +9253245 added jobs screenshot to assets folder @tangollama +0c5aeb4 updated labreport @tangollama +332d09f adding diagram to assets folder @tangollama +928d0f0 updated circleci @tangollama +22b7652 Copy the content for the setup instructions into config.yml @tangollama +3d56731 Added my git commit log @tangollama +ee20f12 hopefully this works @tangollama +6c23264 restarting the lab @tangollama +dabceca Merge pull request #24 from tangollama/circleci +a4096db Create README.md +2f01bf4 Update LAB_INSTRUCTIONS.md +347bd50 Update LAB_INSTRUCTIONS.md +7aaa9f3 Update LAB_INSTRUCTIONS.md +37393ae Bug fixed +1949d2a Update LAB_INSTRUCTIONS.md +d36ad90 Update LAB.md +59ef18a Update LAB_INSTRUCTIONS.md +37be3c8 Update LAB_INSTRUCTIONS.md +97da547 Update LAB.md +0bd6244 (origin/purelab) updated Step 0 title +4562cd8 added npm and node install repreq +255051e adding template +13a09b7 Adding the LAB.md and correcting some instructions. +d2ddea5 Version 0.0.1 of the lab isntructions +ab312fc more progress +62fb0a5 more progress +fe1937b more in the lab instructions +3e807fb first section +9ae6b83 remove LAB.md +e429c1a lab instructions +ce1fcea circleci default config +80bbdbb circleci default config +968099e remove test db +7362cd1 working +44ce6ae Initial commit +``` +* https://github.com/Willnew98/cis411_lab0/blob/labreport/assets/Jobs%20Screenshot.png + + +# Step 6: Submitting a Pull Request +_Remember to reference at least one other student in the PR content via their GitHub handle._ + +# Step 7: [EXTRA CREDIT] Augment the core project +PR reference in the report to one of the following: +1. Add one or more unit tests to the core assignment project. +2. Configure the CircleCI config.yml to automatically build a Docker image of the project. +3. Configure an automatic deployment of the successful CircleCI build to an Amazon EC2 instance. diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 100644 index 00000000..0dbddf07 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../mime/cli.js" "$@" + ret=$? +else + node "$basedir/../mime/cli.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/mime.cmd b/node_modules/.bin/mime.cmd new file mode 100644 index 00000000..81695620 --- /dev/null +++ b/node_modules/.bin/mime.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\mime\cli.js" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\mime\cli.js" %* +) \ No newline at end of file diff --git a/node_modules/.bin/uuid b/node_modules/.bin/uuid new file mode 100644 index 00000000..f3bfcf46 --- /dev/null +++ b/node_modules/.bin/uuid @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../uuid/bin/uuid" "$@" + ret=$? +else + node "$basedir/../uuid/bin/uuid" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/uuid.cmd b/node_modules/.bin/uuid.cmd new file mode 100644 index 00000000..da52d68a --- /dev/null +++ b/node_modules/.bin/uuid.cmd @@ -0,0 +1,7 @@ +@IF EXIST "%~dp0\node.exe" ( + "%~dp0\node.exe" "%~dp0\..\uuid\bin\uuid" %* +) ELSE ( + @SETLOCAL + @SET PATHEXT=%PATHEXT:;.JS;=;% + node "%~dp0\..\uuid\bin\uuid" %* +) \ No newline at end of file diff --git a/node_modules/accepts/HISTORY.md b/node_modules/accepts/HISTORY.md new file mode 100644 index 00000000..f16c17a5 --- /dev/null +++ b/node_modules/accepts/HISTORY.md @@ -0,0 +1,224 @@ +1.3.5 / 2018-02-28 +================== + + * deps: mime-types@~2.1.18 + - deps: mime-db@~1.33.0 + +1.3.4 / 2017-08-22 +================== + + * deps: mime-types@~2.1.16 + - deps: mime-db@~1.29.0 + +1.3.3 / 2016-05-02 +================== + + * deps: mime-types@~2.1.11 + - deps: mime-db@~1.23.0 + * deps: negotiator@0.6.1 + - perf: improve `Accept` parsing speed + - perf: improve `Accept-Charset` parsing speed + - perf: improve `Accept-Encoding` parsing speed + - perf: improve `Accept-Language` parsing speed + +1.3.2 / 2016-03-08 +================== + + * deps: mime-types@~2.1.10 + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + - deps: mime-db@~1.22.0 + +1.3.1 / 2016-01-19 +================== + + * deps: mime-types@~2.1.9 + - deps: mime-db@~1.21.0 + +1.3.0 / 2015-09-29 +================== + + * deps: mime-types@~2.1.7 + - deps: mime-db@~1.19.0 + * deps: negotiator@0.6.0 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Lazy-load modules from main entry point + - perf: delay type concatenation until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove closures getting spec properties + - perf: remove a closure from media type parsing + - perf: remove property delete from media type parsing + +1.2.13 / 2015-09-06 +=================== + + * deps: mime-types@~2.1.6 + - deps: mime-db@~1.18.0 + +1.2.12 / 2015-07-30 +=================== + + * deps: mime-types@~2.1.4 + - deps: mime-db@~1.16.0 + +1.2.11 / 2015-07-16 +=================== + + * deps: mime-types@~2.1.3 + - deps: mime-db@~1.15.0 + +1.2.10 / 2015-07-01 +=================== + + * deps: mime-types@~2.1.2 + - deps: mime-db@~1.14.0 + +1.2.9 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - perf: fix deopt during mapping + +1.2.8 / 2015-06-07 +================== + + * deps: mime-types@~2.1.0 + - deps: mime-db@~1.13.0 + * perf: avoid argument reassignment & argument slice + * perf: avoid negotiator recursive construction + * perf: enable strict mode + * perf: remove unnecessary bitwise operator + +1.2.7 / 2015-05-10 +================== + + * deps: negotiator@0.5.3 + - Fix media type parameter matching to be case-insensitive + +1.2.6 / 2015-05-07 +================== + + * deps: mime-types@~2.0.11 + - deps: mime-db@~1.9.1 + * deps: negotiator@0.5.2 + - Fix comparing media types with quoted values + - Fix splitting media types with quoted commas + +1.2.5 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - deps: mime-db@~1.8.0 + +1.2.4 / 2015-02-14 +================== + + * Support Node.js 0.6 + * deps: mime-types@~2.0.9 + - deps: mime-db@~1.7.0 + * deps: negotiator@0.5.1 + - Fix preference sorting to be stable for long acceptable lists + +1.2.3 / 2015-01-31 +================== + + * deps: mime-types@~2.0.8 + - deps: mime-db@~1.6.0 + +1.2.2 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - deps: mime-db@~1.5.0 + +1.2.1 / 2014-12-30 +================== + + * deps: mime-types@~2.0.5 + - deps: mime-db@~1.3.1 + +1.2.0 / 2014-12-19 +================== + + * deps: negotiator@0.5.0 + - Fix list return order when large accepted list + - Fix missing identity encoding when q=0 exists + - Remove dynamic building of Negotiator class + +1.1.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - deps: mime-db@~1.3.0 + +1.1.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - deps: mime-db@~1.2.0 + +1.1.2 / 2014-10-14 +================== + + * deps: negotiator@0.4.9 + - Fix error when media type has invalid parameter + +1.1.1 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - deps: mime-db@~1.1.0 + * deps: negotiator@0.4.8 + - Fix all negotiations to be case-insensitive + - Stable sort preferences of same quality according to client order + +1.1.0 / 2014-09-02 +================== + + * update `mime-types` + +1.0.7 / 2014-07-04 +================== + + * Fix wrong type returned from `type` when match after unknown extension + +1.0.6 / 2014-06-24 +================== + + * deps: negotiator@0.4.7 + +1.0.5 / 2014-06-20 +================== + + * fix crash when unknown extension given + +1.0.4 / 2014-06-19 +================== + + * use `mime-types` + +1.0.3 / 2014-06-11 +================== + + * deps: negotiator@0.4.6 + - Order by specificity when quality is the same + +1.0.2 / 2014-05-29 +================== + + * Fix interpretation when header not in request + * deps: pin negotiator@0.4.5 + +1.0.1 / 2014-01-18 +================== + + * Identity encoding isn't always acceptable + * deps: negotiator@~0.4.0 + +1.0.0 / 2013-12-27 +================== + + * Genesis diff --git a/node_modules/accepts/LICENSE b/node_modules/accepts/LICENSE new file mode 100644 index 00000000..06166077 --- /dev/null +++ b/node_modules/accepts/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/accepts/README.md b/node_modules/accepts/README.md new file mode 100644 index 00000000..6a2749a1 --- /dev/null +++ b/node_modules/accepts/README.md @@ -0,0 +1,143 @@ +# accepts + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). +Extracted from [koa](https://www.npmjs.com/package/koa) for general use. + +In addition to negotiator, it allows: + +- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` + as well as `('text/html', 'application/json')`. +- Allows type shorthands such as `json`. +- Returns `false` when no types match +- Treats non-existent headers as `*` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install accepts +``` + +## API + + + +```js +var accepts = require('accepts') +``` + +### accepts(req) + +Create a new `Accepts` object for the given `req`. + +#### .charset(charsets) + +Return the first accepted charset. If nothing in `charsets` is accepted, +then `false` is returned. + +#### .charsets() + +Return the charsets that the request accepts, in the order of the client's +preference (most preferred first). + +#### .encoding(encodings) + +Return the first accepted encoding. If nothing in `encodings` is accepted, +then `false` is returned. + +#### .encodings() + +Return the encodings that the request accepts, in the order of the client's +preference (most preferred first). + +#### .language(languages) + +Return the first accepted language. If nothing in `languages` is accepted, +then `false` is returned. + +#### .languages() + +Return the languages that the request accepts, in the order of the client's +preference (most preferred first). + +#### .type(types) + +Return the first accepted type (and it is returned as the same text as what +appears in the `types` array). If nothing in `types` is accepted, then `false` +is returned. + +The `types` array can contain full MIME types or file extensions. Any value +that is not a full MIME types is passed to `require('mime-types').lookup`. + +#### .types() + +Return the types that the request accepts, in the order of the client's +preference (most preferred first). + +## Examples + +### Simple type negotiation + +This simple example shows how to use `accepts` to return a different typed +respond body based on what the client wants to accept. The server lists it's +preferences in order and will get back the best match between the client and +server. + +```js +var accepts = require('accepts') +var http = require('http') + +function app (req, res) { + var accept = accepts(req) + + // the order of this list is significant; should be server preferred order + switch (accept.type(['json', 'html'])) { + case 'json': + res.setHeader('Content-Type', 'application/json') + res.write('{"hello":"world!"}') + break + case 'html': + res.setHeader('Content-Type', 'text/html') + res.write('hello, world!') + break + default: + // the fallback is text/plain, so no need to specify it above + res.setHeader('Content-Type', 'text/plain') + res.write('hello, world!') + break + } + + res.end() +} + +http.createServer(app).listen(3000) +``` + +You can test this out with the cURL program: +```sh +curl -I -H'Accept: text/html' http://localhost:3000/ +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/accepts.svg +[npm-url]: https://npmjs.org/package/accepts +[node-version-image]: https://img.shields.io/node/v/accepts.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg +[travis-url]: https://travis-ci.org/jshttp/accepts +[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/accepts +[downloads-image]: https://img.shields.io/npm/dm/accepts.svg +[downloads-url]: https://npmjs.org/package/accepts diff --git a/node_modules/accepts/index.js b/node_modules/accepts/index.js new file mode 100644 index 00000000..e9b2f63f --- /dev/null +++ b/node_modules/accepts/index.js @@ -0,0 +1,238 @@ +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var Negotiator = require('negotiator') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = Accepts + +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ + +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } + + this.headers = req.headers + this.negotiator = new Negotiator(req) +} + +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ + +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } + + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } + + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } + + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] + + return first + ? types[mimes.indexOf(first)] + : false +} + +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ + +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } + + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } + + return this.negotiator.encodings(encodings)[0] || false +} + +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ + +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ + + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } + + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } + + return this.negotiator.charsets(charsets)[0] || false +} + +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ + +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ + + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } + + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } + + return this.negotiator.languages(languages)[0] || false +} + +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ + +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ + +function validMime (type) { + return typeof type === 'string' +} diff --git a/node_modules/accepts/package.json b/node_modules/accepts/package.json new file mode 100644 index 00000000..642a01b1 --- /dev/null +++ b/node_modules/accepts/package.json @@ -0,0 +1,89 @@ +{ + "_args": [ + [ + "accepts@1.3.5", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "accepts@1.3.5", + "_id": "accepts@1.3.5", + "_inBundle": false, + "_integrity": "sha1-63d99gEXI6OxTopywIBcjoZ0a9I=", + "_location": "/accepts", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "accepts@1.3.5", + "name": "accepts", + "escapedName": "accepts", + "rawSpec": "1.3.5", + "saveSpec": null, + "fetchSpec": "1.3.5" + }, + "_requiredBy": [ + "/express", + "/express-graphql" + ], + "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.5.tgz", + "_spec": "1.3.5", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/accepts/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "dependencies": { + "mime-types": "~2.1.18", + "negotiator": "0.6.1" + }, + "description": "Higher-level content negotiation", + "devDependencies": { + "eslint": "4.18.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/accepts#readme", + "keywords": [ + "content", + "negotiation", + "accept", + "accepts" + ], + "license": "MIT", + "name": "accepts", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/accepts.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.3.5" +} diff --git a/node_modules/array-flatten/LICENSE b/node_modules/array-flatten/LICENSE new file mode 100644 index 00000000..983fbe8a --- /dev/null +++ b/node_modules/array-flatten/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/array-flatten/README.md b/node_modules/array-flatten/README.md new file mode 100644 index 00000000..91fa5b63 --- /dev/null +++ b/node_modules/array-flatten/README.md @@ -0,0 +1,43 @@ +# Array Flatten + +[![NPM version][npm-image]][npm-url] +[![NPM downloads][downloads-image]][downloads-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. + +## Installation + +``` +npm install array-flatten --save +``` + +## Usage + +```javascript +var flatten = require('array-flatten') + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) +//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] + +flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) +//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] + +(function () { + flatten(arguments) //=> [1, 2, 3] +})(1, [2, 3]) +``` + +## License + +MIT + +[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat +[npm-url]: https://npmjs.org/package/array-flatten +[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat +[downloads-url]: https://npmjs.org/package/array-flatten +[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat +[travis-url]: https://travis-ci.org/blakeembrey/array-flatten +[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat +[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/node_modules/array-flatten/array-flatten.js b/node_modules/array-flatten/array-flatten.js new file mode 100644 index 00000000..089117b3 --- /dev/null +++ b/node_modules/array-flatten/array-flatten.js @@ -0,0 +1,64 @@ +'use strict' + +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten + +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } + + return result +} + +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] + + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } + + return result +} + +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } + + return flattenWithDepth(array, [], depth) +} diff --git a/node_modules/array-flatten/package.json b/node_modules/array-flatten/package.json new file mode 100644 index 00000000..4dff2152 --- /dev/null +++ b/node_modules/array-flatten/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "array-flatten@1.1.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "array-flatten@1.1.1", + "_id": "array-flatten@1.1.1", + "_inBundle": false, + "_integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", + "_location": "/array-flatten", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "array-flatten@1.1.1", + "name": "array-flatten", + "escapedName": "array-flatten", + "rawSpec": "1.1.1", + "saveSpec": null, + "fetchSpec": "1.1.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "_spec": "1.1.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Blake Embrey", + "email": "hello@blakeembrey.com", + "url": "http://blakeembrey.me" + }, + "bugs": { + "url": "https://github.com/blakeembrey/array-flatten/issues" + }, + "description": "Flatten an array of nested arrays into a single flat array", + "devDependencies": { + "istanbul": "^0.3.13", + "mocha": "^2.2.4", + "pre-commit": "^1.0.7", + "standard": "^3.7.3" + }, + "files": [ + "array-flatten.js", + "LICENSE" + ], + "homepage": "https://github.com/blakeembrey/array-flatten", + "keywords": [ + "array", + "flatten", + "arguments", + "depth" + ], + "license": "MIT", + "main": "array-flatten.js", + "name": "array-flatten", + "repository": { + "type": "git", + "url": "git://github.com/blakeembrey/array-flatten.git" + }, + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "version": "1.1.1" +} diff --git a/node_modules/body-parser/HISTORY.md b/node_modules/body-parser/HISTORY.md new file mode 100644 index 00000000..6ab747bb --- /dev/null +++ b/node_modules/body-parser/HISTORY.md @@ -0,0 +1,568 @@ +1.18.2 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: remove argument reassignment + +1.18.1 / 2017-09-12 +=================== + + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1 regression + - Update Windows-1255 + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: raw-body@2.3.2 + - deps: iconv-lite@0.4.19 + +1.18.0 / 2017-09-08 +=================== + + * Fix JSON strict violation error to match native parse error + * Include the `body` property on verify errors + * Include the `type` property on all generated errors + * Use `http-errors` to set status code on errors + * deps: bytes@3.0.0 + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + * deps: qs@6.5.0 + * deps: raw-body@2.3.1 + - Use `http-errors` for standard emitted errors + - deps: bytes@3.0.0 + - deps: iconv-lite@0.4.18 + - perf: skip buffer decoding on overage chunk + * perf: prevent internal `throw` when missing charset + +1.17.2 / 2017-05-17 +=================== + + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + +1.17.1 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +1.17.0 / 2017-03-01 +=================== + + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + * deps: qs@6.3.1 + - Fix compacting nested arrays + +1.16.1 / 2017-02-10 +=================== + + * deps: debug@2.6.1 + - Fix deprecation messages in WebStorm and other editors + - Undeprecate `DEBUG_FD` set to `1` or `2` + +1.16.0 / 2017-01-17 +=================== + + * deps: debug@2.6.0 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + * deps: qs@6.2.1 + - Fix array parsing from skipping empty values + * deps: raw-body@~2.2.0 + - deps: iconv-lite@0.4.15 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +1.15.2 / 2016-06-19 +=================== + + * deps: bytes@2.4.0 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: http-errors@~1.5.0 + - Use `setprototypeof` module to replace `__proto__` setting + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: qs@6.2.0 + * deps: raw-body@~2.1.7 + - deps: bytes@2.4.0 + - perf: remove double-cleanup on happy path + * deps: type-is@~1.6.13 + - deps: mime-types@~2.1.11 + +1.15.1 / 2016-05-05 +=================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + * deps: raw-body@~2.1.6 + - deps: bytes@2.3.0 + * deps: type-is@~1.6.12 + - deps: mime-types@~2.1.10 + +1.15.0 / 2016-02-10 +=================== + + * deps: http-errors@~1.4.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.2.1 < 2' + * deps: qs@6.1.0 + * deps: type-is@~1.6.11 + - deps: mime-types@~2.1.9 + +1.14.2 / 2015-12-16 +=================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + * deps: qs@5.2.0 + * deps: raw-body@~2.1.5 + - deps: bytes@2.2.0 + - deps: iconv-lite@0.4.13 + * deps: type-is@~1.6.10 + - deps: mime-types@~2.1.8 + +1.14.1 / 2015-09-27 +=================== + + * Fix issue where invalid charset results in 400 when `verify` used + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + * deps: raw-body@~2.1.4 + - Fix masking critical errors from `iconv-lite` + - deps: iconv-lite@0.4.12 + * deps: type-is@~1.6.9 + - deps: mime-types@~2.1.7 + +1.14.0 / 2015-09-16 +=================== + + * Fix JSON strict parse error to match syntax errors + * Provide static `require` analysis in `urlencoded` parser + * deps: depd@~1.1.0 + - Support web browser loading + * deps: qs@5.1.0 + * deps: raw-body@~2.1.3 + - Fix sync callback when attaching data listener causes sync read + * deps: type-is@~1.6.8 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.6 + +1.13.3 / 2015-07-31 +=================== + + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +1.13.2 / 2015-07-05 +=================== + + * deps: iconv-lite@0.4.11 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix user-visible incompatibilities from 3.1.0 + - Fix various parsing edge cases + * deps: raw-body@~2.1.2 + - Fix error stack traces to skip `makeError` + - deps: iconv-lite@0.4.11 + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +1.13.1 / 2015-06-16 +=================== + + * deps: qs@2.4.2 + - Downgraded from 3.1.0 because of user-visible incompatibilities + +1.13.0 / 2015-06-14 +=================== + + * Add `statusCode` property on `Error`s, in addition to `status` + * Change `type` default to `application/json` for JSON parser + * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser + * Provide static `require` analysis + * Use the `http-errors` module to generate errors + * deps: bytes@2.1.0 + - Slight optimizations + * deps: iconv-lite@0.4.10 + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + - Leading BOM is now removed when decoding + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: qs@3.1.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + - Parsed object now has `null` prototype + * deps: raw-body@~2.1.1 + - Use `unpipe` module for unpiping requests + - deps: iconv-lite@0.4.10 + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: remove argument reassignment + * perf: remove delete call + +1.12.4 / 2015-05-10 +=================== + + * deps: debug@~2.2.0 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: on-finished@~2.2.1 + * deps: raw-body@~2.0.1 + - Fix a false-positive when unpiping in Node.js 0.8 + - deps: bytes@2.0.1 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +1.12.3 / 2015-04-15 +=================== + + * Slight efficiency improvement when not debugging + * deps: depd@~1.0.1 + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + * deps: raw-body@1.3.4 + - Fix hanging callback if request aborts during read + - deps: iconv-lite@0.4.8 + +1.12.2 / 2015-03-16 +=================== + + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + +1.12.1 / 2015-03-15 +=================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +1.12.0 / 2015-02-13 +=================== + + * add `debug` messages + * accept a function for the `type` option + * use `content-type` to parse `Content-Type` headers + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + * deps: raw-body@1.3.3 + - deps: iconv-lite@0.4.7 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +1.11.0 / 2015-01-30 +=================== + + * make internal `extended: true` depth limit infinity + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +1.10.2 / 2015-01-20 +=================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + * deps: raw-body@1.3.2 + - deps: iconv-lite@0.4.6 + +1.10.1 / 2015-01-01 +=================== + + * deps: on-finished@~2.2.0 + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +1.10.0 / 2014-12-02 +=================== + + * make internal `extended: true` array limit dynamic + +1.9.3 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + * deps: raw-body@1.3.1 + - deps: iconv-lite@0.4.5 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +1.9.2 / 2014-10-27 +================== + + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +1.9.1 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +1.9.0 / 2014-09-24 +================== + + * include the charset in "unsupported charset" error message + * include the encoding in "unsupported content encoding" error message + * deps: depd@~1.0.0 + +1.8.4 / 2014-09-23 +================== + + * fix content encoding to be case-insensitive + +1.8.3 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +1.8.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + +1.8.1 / 2014-09-07 +================== + + * deps: media-typer@0.3.0 + * deps: type-is@~1.5.1 + +1.8.0 / 2014-09-05 +================== + + * make empty-body-handling consistent between chunked requests + - empty `json` produces `{}` + - empty `raw` produces `new Buffer(0)` + - empty `text` produces `''` + - empty `urlencoded` produces `{}` + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: type-is@~1.5.0 + - fix `hasbody` to be true for `content-length: 0` + +1.7.0 / 2014-09-01 +================== + + * add `parameterLimit` option to `urlencoded` parser + * change `urlencoded` extended array limit to 100 + * respond with 413 when over `parameterLimit` in `urlencoded` + +1.6.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +1.6.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +1.6.5 / 2014-08-16 +================== + + * deps: on-finished@2.1.0 + +1.6.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + +1.6.3 / 2014-08-10 +================== + + * deps: qs@1.2.1 + +1.6.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +1.6.1 / 2014-08-06 +================== + + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +1.6.0 / 2014-08-05 +================== + + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + +1.5.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +1.5.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +1.5.0 / 2014-07-20 +================== + + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + * deps: raw-body@1.3.0 + - deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + - Fix `Cannot switch to old mode now` error on Node.js 0.10+ + * deps: type-is@~1.3.2 + +1.4.3 / 2014-06-19 +================== + + * deps: type-is@1.3.1 + - fix global variable leak + +1.4.2 / 2014-06-19 +================== + + * deps: type-is@1.3.0 + - improve type parsing + +1.4.1 / 2014-06-19 +================== + + * fix urlencoded extended deprecation message + +1.4.0 / 2014-06-19 +================== + + * add `text` parser + * add `raw` parser + * check accepted charset in content-type (accepts utf-8) + * check accepted encoding in content-encoding (accepts identity) + * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed + * deprecate `urlencoded()` without provided `extended` option + * lazy-load urlencoded parsers + * parsers split into files for reduced mem usage + * support gzip and deflate bodies + - set `inflate: false` to turn off + * deps: raw-body@1.2.2 + - Support all encodings from `iconv-lite` + +1.3.1 / 2014-06-11 +================== + + * deps: type-is@1.2.1 + - Switch dependency from mime to mime-types@1.0.0 + +1.3.0 / 2014-05-31 +================== + + * add `extended` option to urlencoded parser + +1.2.2 / 2014-05-27 +================== + + * deps: raw-body@1.1.6 + - assert stream encoding on node.js 0.8 + - assert stream encoding on node.js < 0.10.6 + - deps: bytes@1 + +1.2.1 / 2014-05-26 +================== + + * invoke `next(err)` after request fully read + - prevents hung responses and socket hang ups + +1.2.0 / 2014-05-11 +================== + + * add `verify` option + * deps: type-is@1.2.0 + - support suffix matching + +1.1.2 / 2014-05-11 +================== + + * improve json parser speed + +1.1.1 / 2014-05-11 +================== + + * fix repeated limit parsing with every request + +1.1.0 / 2014-05-10 +================== + + * add `type` option + * deps: pin for safety and consistency + +1.0.2 / 2014-04-14 +================== + + * use `type-is` module + +1.0.1 / 2014-03-20 +================== + + * lower default limits to 100kb diff --git a/node_modules/body-parser/LICENSE b/node_modules/body-parser/LICENSE new file mode 100644 index 00000000..386b7b69 --- /dev/null +++ b/node_modules/body-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/body-parser/README.md b/node_modules/body-parser/README.md new file mode 100644 index 00000000..62221e47 --- /dev/null +++ b/node_modules/body-parser/README.md @@ -0,0 +1,438 @@ +# body-parser + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Node.js body parsing middleware. + +Parse incoming request bodies in a middleware before your handlers, available +under the `req.body` property. + +[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). + +_This does not handle multipart bodies_, due to their complex and typically +large nature. For multipart bodies, you may be interested in the following +modules: + + * [busboy](https://www.npmjs.org/package/busboy#readme) and + [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) + * [multiparty](https://www.npmjs.org/package/multiparty#readme) and + [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) + * [formidable](https://www.npmjs.org/package/formidable#readme) + * [multer](https://www.npmjs.org/package/multer#readme) + +This module provides the following parsers: + + * [JSON body parser](#bodyparserjsonoptions) + * [Raw body parser](#bodyparserrawoptions) + * [Text body parser](#bodyparsertextoptions) + * [URL-encoded form body parser](#bodyparserurlencodedoptions) + +Other body parsers you might be interested in: + +- [body](https://www.npmjs.org/package/body#readme) +- [co-body](https://www.npmjs.org/package/co-body#readme) + +## Installation + +```sh +$ npm install body-parser +``` + +## API + + + +```js +var bodyParser = require('body-parser') +``` + +The `bodyParser` object exposes various factories to create middlewares. All +middlewares will populate the `req.body` property with the parsed body when +the `Content-Type` request header matches the `type` option, or an empty +object (`{}`) if there was no body to parse, the `Content-Type` was not matched, +or an error occurred. + +The various errors returned by this module are described in the +[errors section](#errors). + +### bodyParser.json([options]) + +Returns middleware that only parses `json` and only looks at requests where +the `Content-Type` header matches the `type` option. This parser accepts any +Unicode encoding of the body and supports automatic inflation of `gzip` and +`deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). + +#### Options + +The `json` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### reviver + +The `reviver` option is passed directly to `JSON.parse` as the second +argument. You can find more information on this argument +[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). + +##### strict + +When set to `true`, will only accept arrays and objects; when `false` will +accept anything `JSON.parse` accepts. Defaults to `true`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `json`), a mime type (like +`application/json`), or a mime type with a wildcard (like `*/*` or `*/json`). +If a function, the `type` option is called as `fn(req)` and the request is +parsed if it returns a truthy value. Defaults to `application/json`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.raw([options]) + +Returns middleware that parses all bodies as a `Buffer` and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a `Buffer` object +of the body. + +#### Options + +The `raw` function takes an optional `options` object that may contain any of +the following keys: + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `bin`), a mime type (like +`application/octet-stream`), or a mime type with a wildcard (like `*/*` or +`application/*`). If a function, the `type` option is called as `fn(req)` +and the request is parsed if it returns a truthy value. Defaults to +`application/octet-stream`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.text([options]) + +Returns middleware that parses all bodies as a string and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser supports automatic inflation of `gzip` and `deflate` encodings. + +A new `body` string containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This will be a string of the +body. + +#### Options + +The `text` function takes an optional `options` object that may contain any of +the following keys: + +##### defaultCharset + +Specify the default character set for the text content if the charset is not +specified in the `Content-Type` header of the request. Defaults to `utf-8`. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `txt`), a mime type (like +`text/plain`), or a mime type with a wildcard (like `*/*` or `text/*`). +If a function, the `type` option is called as `fn(req)` and the request is +parsed if it returns a truthy value. Defaults to `text/plain`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +### bodyParser.urlencoded([options]) + +Returns middleware that only parses `urlencoded` bodies and only looks at +requests where the `Content-Type` header matches the `type` option. This +parser accepts only UTF-8 encoding of the body and supports automatic +inflation of `gzip` and `deflate` encodings. + +A new `body` object containing the parsed data is populated on the `request` +object after the middleware (i.e. `req.body`). This object will contain +key-value pairs, where the value can be a string or array (when `extended` is +`false`), or any type (when `extended` is `true`). + +#### Options + +The `urlencoded` function takes an optional `options` object that may contain +any of the following keys: + +##### extended + +The `extended` option allows to choose between parsing the URL-encoded data +with the `querystring` library (when `false`) or the `qs` library (when +`true`). The "extended" syntax allows for rich objects and arrays to be +encoded into the URL-encoded format, allowing for a JSON-like experience +with URL-encoded. For more information, please +[see the qs library](https://www.npmjs.org/package/qs#readme). + +Defaults to `true`, but using the default has been deprecated. Please +research into the difference between `qs` and `querystring` and choose the +appropriate setting. + +##### inflate + +When set to `true`, then deflated (compressed) bodies will be inflated; when +`false`, deflated bodies are rejected. Defaults to `true`. + +##### limit + +Controls the maximum request body size. If this is a number, then the value +specifies the number of bytes; if it is a string, the value is passed to the +[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults +to `'100kb'`. + +##### parameterLimit + +The `parameterLimit` option controls the maximum number of parameters that +are allowed in the URL-encoded data. If a request contains more parameters +than this value, a 413 will be returned to the client. Defaults to `1000`. + +##### type + +The `type` option is used to determine what media type the middleware will +parse. This option can be a function or a string. If a string, `type` option +is passed directly to the [type-is](https://www.npmjs.org/package/type-is#readme) +library and this can be an extension name (like `urlencoded`), a mime type (like +`application/x-www-form-urlencoded`), or a mime type with a wildcard (like +`*/x-www-form-urlencoded`). If a function, the `type` option is called as +`fn(req)` and the request is parsed if it returns a truthy value. Defaults +to `application/x-www-form-urlencoded`. + +##### verify + +The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, +where `buf` is a `Buffer` of the raw request body and `encoding` is the +encoding of the request. The parsing can be aborted by throwing an error. + +## Errors + +The middlewares provided by this module create errors depending on the error +condition during parsing. The errors will typically have a `status`/`statusCode` +property that contains the suggested HTTP response code, an `expose` property +to determine if the `message` property should be displayed to the client, a +`type` property to determine the type of error without matching against the +`message`, and a `body` property containing the read body, if available. + +The following are the common errors emitted, though any error can come through +for various reasons. + +### content encoding unsupported + +This error will occur when the request had a `Content-Encoding` header that +contained an encoding but the "inflation" option was set to `false`. The +`status` property is set to `415`, the `type` property is set to +`'encoding.unsupported'`, and the `charset` property will be set to the +encoding that is unsupported. + +### request aborted + +This error will occur when the request is aborted by the client before reading +the body has finished. The `received` property will be set to the number of +bytes received before the request was aborted and the `expected` property is +set to the number of expected bytes. The `status` property is set to `400` +and `type` property is set to `'request.aborted'`. + +### request entity too large + +This error will occur when the request body's size is larger than the "limit" +option. The `limit` property will be set to the byte limit and the `length` +property will be set to the request body's length. The `status` property is +set to `413` and the `type` property is set to `'entity.too.large'`. + +### request size did not match content length + +This error will occur when the request's length did not match the length from +the `Content-Length` header. This typically occurs when the request is malformed, +typically when the `Content-Length` header was calculated based on characters +instead of bytes. The `status` property is set to `400` and the `type` property +is set to `'request.size.invalid'`. + +### stream encoding should not be set + +This error will occur when something called the `req.setEncoding` method prior +to this middleware. This module operates directly on bytes only and you cannot +call `req.setEncoding` when using this module. The `status` property is set to +`500` and the `type` property is set to `'stream.encoding.set'`. + +### too many parameters + +This error will occur when the content of the request exceeds the configured +`parameterLimit` for the `urlencoded` parser. The `status` property is set to +`413` and the `type` property is set to `'parameters.too.many'`. + +### unsupported charset "BOGUS" + +This error will occur when the request had a charset parameter in the +`Content-Type` header, but the `iconv-lite` module does not support it OR the +parser does not support it. The charset is contained in the message as well +as in the `charset` property. The `status` property is set to `415`, the +`type` property is set to `'charset.unsupported'`, and the `charset` property +is set to the charset that is unsupported. + +### unsupported content encoding "bogus" + +This error will occur when the request had a `Content-Encoding` header that +contained an unsupported encoding. The encoding is contained in the message +as well as in the `encoding` property. The `status` property is set to `415`, +the `type` property is set to `'encoding.unsupported'`, and the `encoding` +property is set to the encoding that is unsupported. + +## Examples + +### Express/Connect top-level generic + +This example demonstrates adding a generic JSON and URL-encoded parser as a +top-level middleware, which will parse the bodies of all incoming requests. +This is the simplest setup. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: false })) + +// parse application/json +app.use(bodyParser.json()) + +app.use(function (req, res) { + res.setHeader('Content-Type', 'text/plain') + res.write('you posted:\n') + res.end(JSON.stringify(req.body, null, 2)) +}) +``` + +### Express route-specific + +This example demonstrates adding body parsers specifically to the routes that +need them. In general, this is the most recommended way to use body-parser with +Express. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// create application/json parser +var jsonParser = bodyParser.json() + +// create application/x-www-form-urlencoded parser +var urlencodedParser = bodyParser.urlencoded({ extended: false }) + +// POST /login gets urlencoded bodies +app.post('/login', urlencodedParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + res.send('welcome, ' + req.body.username) +}) + +// POST /api/users gets JSON bodies +app.post('/api/users', jsonParser, function (req, res) { + if (!req.body) return res.sendStatus(400) + // create user in req.body +}) +``` + +### Change accepted type for parsers + +All the parsers accept a `type` option which allows you to change the +`Content-Type` that the middleware will parse. + +```js +var express = require('express') +var bodyParser = require('body-parser') + +var app = express() + +// parse various different custom JSON types as JSON +app.use(bodyParser.json({ type: 'application/*+json' })) + +// parse some custom thing into a Buffer +app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) + +// parse an HTML body into a string +app.use(bodyParser.text({ type: 'text/html' })) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/body-parser.svg +[npm-url]: https://npmjs.org/package/body-parser +[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg +[travis-url]: https://travis-ci.org/expressjs/body-parser +[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master +[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg +[downloads-url]: https://npmjs.org/package/body-parser +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/node_modules/body-parser/index.js b/node_modules/body-parser/index.js new file mode 100644 index 00000000..93c3a1ff --- /dev/null +++ b/node_modules/body-parser/index.js @@ -0,0 +1,157 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('body-parser') + +/** + * Cache of loaded parsers. + * @private + */ + +var parsers = Object.create(null) + +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ + +/** + * Module exports. + * @type {Parsers} + */ + +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') + +/** + * JSON parser. + * @public + */ + +Object.defineProperty(exports, 'json', { + configurable: true, + enumerable: true, + get: createParserGetter('json') +}) + +/** + * Raw parser. + * @public + */ + +Object.defineProperty(exports, 'raw', { + configurable: true, + enumerable: true, + get: createParserGetter('raw') +}) + +/** + * Text parser. + * @public + */ + +Object.defineProperty(exports, 'text', { + configurable: true, + enumerable: true, + get: createParserGetter('text') +}) + +/** + * URL-encoded parser. + * @public + */ + +Object.defineProperty(exports, 'urlencoded', { + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +}) + +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ + +function bodyParser (options) { + var opts = {} + + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] + } + } + } + + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) + + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} + +/** + * Create a getter for loading a parser. + * @private + */ + +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} + +/** + * Load a parser module. + * @private + */ + +function loadParser (parserName) { + var parser = parsers[parserName] + + if (parser !== undefined) { + return parser + } + + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = require('./lib/types/json') + break + case 'raw': + parser = require('./lib/types/raw') + break + case 'text': + parser = require('./lib/types/text') + break + case 'urlencoded': + parser = require('./lib/types/urlencoded') + break + } + + // store to prevent invoking require() + return (parsers[parserName] = parser) +} diff --git a/node_modules/body-parser/lib/read.js b/node_modules/body-parser/lib/read.js new file mode 100644 index 00000000..c1026095 --- /dev/null +++ b/node_modules/body-parser/lib/read.js @@ -0,0 +1,181 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var getBody = require('raw-body') +var iconv = require('iconv-lite') +var onFinished = require('on-finished') +var zlib = require('zlib') + +/** + * Module exports. + */ + +module.exports = read + +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ + +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream + + // flag as parsed + req._body = true + + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify + + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) + } + + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error + + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } + + // read off entire request + stream.resume() + onFinished(req, function onfinished () { + next(createError(400, _error)) + }) + return + } + + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } + + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + + next() + }) +} + +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ + +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream + + debug('content-encoding "%s"', encoding) + + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } + + return stream +} diff --git a/node_modules/body-parser/lib/types/json.js b/node_modules/body-parser/lib/types/json.js new file mode 100644 index 00000000..a7bc838c --- /dev/null +++ b/node_modules/body-parser/lib/types/json.js @@ -0,0 +1,232 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:json') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = json + +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ + +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex + +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function json (options) { + var opts = options || {} + + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } + + if (strict) { + var first = firstchar(body) + + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } + } + + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + stack: e.stack + }) + } + } + + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ + +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = str.substring(0, index) + '#' + + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace('#', char), + stack: e.stack + }) + } +} + +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ + +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ + +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } + } + + var props = Object.keys(obj) + + for (var j = 0; j < props.length; j++) { + var prop = props[j] + error[prop] = obj[prop] + } + + return error +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/raw.js b/node_modules/body-parser/lib/types/raw.js new file mode 100644 index 00000000..f5d1b674 --- /dev/null +++ b/node_modules/body-parser/lib/types/raw.js @@ -0,0 +1,101 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var debug = require('debug')('body-parser:raw') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = raw + +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/text.js b/node_modules/body-parser/lib/types/text.js new file mode 100644 index 00000000..083a0090 --- /dev/null +++ b/node_modules/body-parser/lib/types/text.js @@ -0,0 +1,121 @@ +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var debug = require('debug')('body-parser:text') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = text + +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function text (options) { + var opts = options || {} + + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf + } + + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // get charset + var charset = getCharset(req) || defaultCharset + + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/lib/types/urlencoded.js b/node_modules/body-parser/lib/types/urlencoded.js new file mode 100644 index 00000000..5ccda218 --- /dev/null +++ b/node_modules/body-parser/lib/types/urlencoded.js @@ -0,0 +1,284 @@ +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var contentType = require('content-type') +var createError = require('http-errors') +var debug = require('debug')('body-parser:urlencoded') +var deprecate = require('depd')('body-parser') +var read = require('../read') +var typeis = require('type-is') + +/** + * Module exports. + */ + +module.exports = urlencoded + +/** + * Cache of parser modules. + */ + +var parsers = Object.create(null) + +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ + +function urlencoded (options) { + var opts = options || {} + + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') + } + + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } + + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) + + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (body) { + return body.length + ? queryparse(body) + : {} + } + + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } + + req.body = req.body || {} + + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } + + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } + + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } + + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} + +/** + * Get the extended query parser. + * + * @param {object} options + */ + +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + var arrayLimit = Math.max(100, paramCount) + + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) + } +} + +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ + +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} + +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ + +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } + } + + return count +} + +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ + +function parser (name) { + var mod = parsers[name] + + if (mod !== undefined) { + return mod.parse + } + + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = require('qs') + break + case 'querystring': + mod = require('querystring') + break + } + + // store to prevent invoking require() + parsers[name] = mod + + return mod.parse +} + +/** + * Get the simple query parser. + * + * @param {object} options + */ + +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') + + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } + + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } + + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) + + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, {maxKeys: parameterLimit}) + } +} + +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) + } +} diff --git a/node_modules/body-parser/package.json b/node_modules/body-parser/package.json new file mode 100644 index 00000000..444f2db1 --- /dev/null +++ b/node_modules/body-parser/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "body-parser@1.18.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "body-parser@1.18.2", + "_id": "body-parser@1.18.2", + "_inBundle": false, + "_integrity": "sha1-h2eKGdhLR9hZuDGZvVm84iKxBFQ=", + "_location": "/body-parser", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "body-parser@1.18.2", + "name": "body-parser", + "escapedName": "body-parser", + "rawSpec": "1.18.2", + "saveSpec": null, + "fetchSpec": "1.18.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.18.2.tgz", + "_spec": "1.18.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/expressjs/body-parser/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "dependencies": { + "bytes": "3.0.0", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "~1.1.1", + "http-errors": "~1.6.2", + "iconv-lite": "0.4.19", + "on-finished": "~2.3.0", + "qs": "6.5.1", + "raw-body": "2.3.2", + "type-is": "~1.6.15" + }, + "description": "Node.js body parsing middleware", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "methods": "1.1.2", + "mocha": "2.5.3", + "safe-buffer": "5.1.1", + "supertest": "1.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "lib/", + "LICENSE", + "HISTORY.md", + "index.js" + ], + "homepage": "https://github.com/expressjs/body-parser#readme", + "license": "MIT", + "name": "body-parser", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/body-parser.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" + }, + "version": "1.18.2" +} diff --git a/node_modules/bytes/History.md b/node_modules/bytes/History.md new file mode 100644 index 00000000..13d463ab --- /dev/null +++ b/node_modules/bytes/History.md @@ -0,0 +1,82 @@ +3.0.0 / 2017-08-31 +================== + + * Change "kB" to "KB" in format output + * Remove support for Node.js 0.6 + * Remove support for ComponentJS + +2.5.0 / 2017-03-24 +================== + + * Add option "unit" + +2.4.0 / 2016-06-01 +================== + + * Add option "unitSeparator" + +2.3.0 / 2016-02-15 +================== + + * Drop partial bytes on all parsed units + * Fix non-finite numbers to `.format` to return `null` + * Fix parsing byte string that looks like hex + * perf: hoist regular expressions + +2.2.0 / 2015-11-13 +================== + + * add option "decimalPlaces" + * add option "fixedDecimals" + +2.1.0 / 2015-05-21 +================== + + * add `.format` export + * add `.parse` export + +2.0.2 / 2015-05-20 +================== + + * remove map recreation + * remove unnecessary object construction + +2.0.1 / 2015-05-07 +================== + + * fix browserify require + * remove node.extend dependency + +2.0.0 / 2015-04-12 +================== + + * add option "case" + * add option "thousandsSeparator" + * return "null" on invalid parse input + * support proper round-trip: bytes(bytes(num)) === num + * units no longer case sensitive when parsing + +1.0.0 / 2014-05-05 +================== + + * add negative support. fixes #6 + +0.3.0 / 2014-03-19 +================== + + * added terabyte support + +0.2.1 / 2013-04-01 +================== + + * add .component + +0.2.0 / 2012-10-28 +================== + + * bytes(200).should.eql('200b') + +0.1.0 / 2012-07-04 +================== + + * add bytes to string conversion [yields] diff --git a/node_modules/bytes/LICENSE b/node_modules/bytes/LICENSE new file mode 100644 index 00000000..63e95a96 --- /dev/null +++ b/node_modules/bytes/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015 Jed Watson + +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/bytes/Readme.md b/node_modules/bytes/Readme.md new file mode 100644 index 00000000..9b53745d --- /dev/null +++ b/node_modules/bytes/Readme.md @@ -0,0 +1,125 @@ +# Bytes utility + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install bytes +``` + +## Usage + +```js +var bytes = require('bytes'); +``` + +#### bytes.format(number value, [options]): string|null + +Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is + rounded. + +**Arguments** + +| Name | Type | Description | +|---------|----------|--------------------| +| value | `number` | Value in bytes | +| options | `Object` | Conversion options | + +**Options** + +| Property | Type | Description | +|-------------------|--------|-----------------------------------------------------------------------------------------| +| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | +| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | +| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `''`. | +| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | +| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | + +**Returns** + +| Name | Type | Description | +|---------|------------------|-------------------------------------------------| +| results | `string`|`null` | Return null upon error. String value otherwise. | + +**Example** + +```js +bytes(1024); +// output: '1KB' + +bytes(1000); +// output: '1000B' + +bytes(1000, {thousandsSeparator: ' '}); +// output: '1 000B' + +bytes(1024 * 1.7, {decimalPlaces: 0}); +// output: '2KB' + +bytes(1024, {unitSeparator: ' '}); +// output: '1 KB' + +``` + +#### bytes.parse(string|number value): number|null + +Parse the string value into an integer in bytes. If no unit is given, or `value` +is a number, it is assumed the value is in bytes. + +Supported units and abbreviations are as follows and are case-insensitive: + + * `b` for bytes + * `kb` for kilobytes + * `mb` for megabytes + * `gb` for gigabytes + * `tb` for terabytes + +The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. + +**Arguments** + +| Name | Type | Description | +|---------------|--------|--------------------| +| value | `string`|`number` | String to parse, or number in bytes. | + +**Returns** + +| Name | Type | Description | +|---------|-------------|-------------------------| +| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | + +**Example** + +```js +bytes('1KB'); +// output: 1024 + +bytes('1024'); +// output: 1024 + +bytes(1024); +// output: 1024 +``` + +## License + +[MIT](LICENSE) + +[downloads-image]: https://img.shields.io/npm/dm/bytes.svg +[downloads-url]: https://npmjs.org/package/bytes +[npm-image]: https://img.shields.io/npm/v/bytes.svg +[npm-url]: https://npmjs.org/package/bytes +[travis-image]: https://img.shields.io/travis/visionmedia/bytes.js/master.svg +[travis-url]: https://travis-ci.org/visionmedia/bytes.js +[coveralls-image]: https://img.shields.io/coveralls/visionmedia/bytes.js/master.svg +[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master diff --git a/node_modules/bytes/index.js b/node_modules/bytes/index.js new file mode 100644 index 00000000..1e39afd1 --- /dev/null +++ b/node_modules/bytes/index.js @@ -0,0 +1,159 @@ +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; + +/** + * Module variables. + * @private + */ + +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; + +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; + +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: ((1 << 30) * 1024) +}; + +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i; + +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ + +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } + + if (typeof value === 'number') { + return format(value, options); + } + + return null; +} + +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ + +function format(value, options) { + if (!Number.isFinite(value)) { + return null; + } + + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; + + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; + } + } + + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); + + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); + } + + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); + } + + return str + unitSeparator + unit; +} + +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ + +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; + } + + if (typeof val !== 'string') { + return null; + } + + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; + + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); + } + + return Math.floor(map[unit] * floatValue); +} diff --git a/node_modules/bytes/package.json b/node_modules/bytes/package.json new file mode 100644 index 00000000..5d1c74f0 --- /dev/null +++ b/node_modules/bytes/package.json @@ -0,0 +1,85 @@ +{ + "_args": [ + [ + "bytes@3.0.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "bytes@3.0.0", + "_id": "bytes@3.0.0", + "_inBundle": false, + "_integrity": "sha1-0ygVQE1olpn4Wk6k+odV3ROpYEg=", + "_location": "/bytes", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "bytes@3.0.0", + "name": "bytes", + "escapedName": "bytes", + "rawSpec": "3.0.0", + "saveSpec": null, + "fetchSpec": "3.0.0" + }, + "_requiredBy": [ + "/body-parser", + "/raw-body" + ], + "_resolved": "https://registry.npmjs.org/bytes/-/bytes-3.0.0.tgz", + "_spec": "3.0.0", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "bugs": { + "url": "https://github.com/visionmedia/bytes.js/issues" + }, + "contributors": [ + { + "name": "Jed Watson", + "email": "jed.watson@me.com" + }, + { + "name": "Théo FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "description": "Utility to parse a string bytes to bytes and vice-versa", + "devDependencies": { + "mocha": "2.5.3", + "nyc": "10.3.2" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "History.md", + "LICENSE", + "Readme.md", + "index.js" + ], + "homepage": "https://github.com/visionmedia/bytes.js#readme", + "keywords": [ + "byte", + "bytes", + "utility", + "parse", + "parser", + "convert", + "converter" + ], + "license": "MIT", + "name": "bytes", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/bytes.js.git" + }, + "scripts": { + "test": "mocha --check-leaks --reporter spec", + "test-ci": "nyc --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + }, + "version": "3.0.0" +} diff --git a/node_modules/content-disposition/HISTORY.md b/node_modules/content-disposition/HISTORY.md new file mode 100644 index 00000000..53849b61 --- /dev/null +++ b/node_modules/content-disposition/HISTORY.md @@ -0,0 +1,50 @@ +0.5.2 / 2016-12-08 +================== + + * Fix `parse` to accept any linear whitespace character + +0.5.1 / 2016-01-17 +================== + + * perf: enable strict mode + +0.5.0 / 2014-10-11 +================== + + * Add `parse` function + +0.4.0 / 2014-09-21 +================== + + * Expand non-Unicode `filename` to the full ISO-8859-1 charset + +0.3.0 / 2014-09-20 +================== + + * Add `fallback` option + * Add `type` option + +0.2.0 / 2014-09-19 +================== + + * Reduce ambiguity of file names with hex escape in buggy browsers + +0.1.2 / 2014-09-19 +================== + + * Fix periodic invalid Unicode filename header + +0.1.1 / 2014-09-19 +================== + + * Fix invalid characters appearing in `filename*` parameter + +0.1.0 / 2014-09-18 +================== + + * Make the `filename` argument optional + +0.0.0 / 2014-09-18 +================== + + * Initial release diff --git a/node_modules/content-disposition/LICENSE b/node_modules/content-disposition/LICENSE new file mode 100644 index 00000000..b7dce6cf --- /dev/null +++ b/node_modules/content-disposition/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/content-disposition/README.md b/node_modules/content-disposition/README.md new file mode 100644 index 00000000..992d19a6 --- /dev/null +++ b/node_modules/content-disposition/README.md @@ -0,0 +1,141 @@ +# content-disposition + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP `Content-Disposition` header + +## Installation + +```sh +$ npm install content-disposition +``` + +## API + +```js +var contentDisposition = require('content-disposition') +``` + +### contentDisposition(filename, options) + +Create an attachment `Content-Disposition` header value using the given file name, +if supplied. The `filename` is optional and if no file name is desired, but you +want to specify `options`, set `filename` to `undefined`. + +```js +res.setHeader('Content-Disposition', contentDisposition('∫ maths.pdf')) +``` + +**note** HTTP headers are of the ISO-8859-1 character set. If you are writing this +header through a means different from `setHeader` in Node.js, you'll want to specify +the `'binary'` encoding in Node.js. + +#### Options + +`contentDisposition` accepts these properties in the options object. + +##### fallback + +If the `filename` option is outside ISO-8859-1, then the file name is actually +stored in a supplemental field for clients that support Unicode file names and +a ISO-8859-1 version of the file name is automatically generated. + +This specifies the ISO-8859-1 file name to override the automatic generation or +disables the generation all together, defaults to `true`. + + - A string will specify the ISO-8859-1 file name to use in place of automatic + generation. + - `false` will disable including a ISO-8859-1 file name and only include the + Unicode version (unless the file name is already ISO-8859-1). + - `true` will enable automatic generation if the file name is outside ISO-8859-1. + +If the `filename` option is ISO-8859-1 and this option is specified and has a +different value, then the `filename` option is encoded in the extended field +and this set as the fallback field, even though they are both ISO-8859-1. + +##### type + +Specifies the disposition type, defaults to `"attachment"`. This can also be +`"inline"`, or any other value (all values except inline are treated like +`attachment`, but can convey additional information if both parties agree to +it). The type is normalized to lower-case. + +### contentDisposition.parse(string) + +```js +var disposition = contentDisposition.parse('attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'); +``` + +Parse a `Content-Disposition` header string. This automatically handles extended +("Unicode") parameters by decoding them and providing them under the standard +parameter name. This will return an object with the following properties (examples +are shown for the string `'attachment; filename="EURO rates.txt"; filename*=UTF-8\'\'%e2%82%ac%20rates.txt'`): + + - `type`: The disposition type (always lower case). Example: `'attachment'` + + - `parameters`: An object of the parameters in the disposition (name of parameter + always lower case and extended versions replace non-extended versions). Example: + `{filename: "€ rates.txt"}` + +## Examples + +### Send a file for download + +```js +var contentDisposition = require('content-disposition') +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +var filePath = '/path/to/public/plans.pdf' + +http.createServer(function onRequest(req, res) { + // set headers + res.setHeader('Content-Type', 'application/pdf') + res.setHeader('Content-Disposition', contentDisposition(filePath)) + + // send file + var stream = fs.createReadStream(filePath) + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## Testing + +```sh +$ npm test +``` + +## References + +- [RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1][rfc-2616] +- [RFC 5987: Character Set and Language Encoding for Hypertext Transfer Protocol (HTTP) Header Field Parameters][rfc-5987] +- [RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)][rfc-6266] +- [Test Cases for HTTP Content-Disposition header field (RFC 6266) and the Encodings defined in RFCs 2047, 2231 and 5987][tc-2231] + +[rfc-2616]: https://tools.ietf.org/html/rfc2616 +[rfc-5987]: https://tools.ietf.org/html/rfc5987 +[rfc-6266]: https://tools.ietf.org/html/rfc6266 +[tc-2231]: http://greenbytes.de/tech/tc2231/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-disposition.svg?style=flat +[npm-url]: https://npmjs.org/package/content-disposition +[node-version-image]: https://img.shields.io/node/v/content-disposition.svg?style=flat +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/content-disposition.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/content-disposition +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-disposition.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/content-disposition?branch=master +[downloads-image]: https://img.shields.io/npm/dm/content-disposition.svg?style=flat +[downloads-url]: https://npmjs.org/package/content-disposition diff --git a/node_modules/content-disposition/index.js b/node_modules/content-disposition/index.js new file mode 100644 index 00000000..88a0d0a2 --- /dev/null +++ b/node_modules/content-disposition/index.js @@ -0,0 +1,445 @@ +/*! + * content-disposition + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = contentDisposition +module.exports.parse = parse + +/** + * Module dependencies. + */ + +var basename = require('path').basename + +/** + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") + */ + +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex + +/** + * RegExp to match percent encoding escape. + */ + +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + +/** + * RegExp to match non-latin1 characters. + */ + +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ + +var QESC_REGEXP = /\\([\u0000-\u007f])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ + +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = + */ + +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ + +/** + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + */ + +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ + +/** + * RegExp for various RFC 6266 grammar + * + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + */ + +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + +/** + * Create an attachment Content-Disposition header. + * + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @api public + */ + +function contentDisposition (filename, options) { + var opts = options || {} + + // get type + var type = opts.type || 'attachment' + + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) +} + +/** + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} + * @api private + */ + +function createparams (filename, fallback) { + if (filename === undefined) { + return + } + + var params = {} + + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } + + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } + + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } + + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } + + // restrict to file base name + var name = basename(filename) + + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) + + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } + + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } + + return params +} + +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @api private + */ + +function format (obj) { + var parameters = obj.parameters + var type = obj.type + + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + // start with normalized type + var string = String(type).toLowerCase() + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) + + string += '; ' + param + '=' + val + } + } + + return string +} + +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @api private + */ + +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + + if (!match) { + throw new TypeError('invalid extended field value') + } + + var charset = match[1].toLowerCase() + var encoded = match[2] + var value + + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) + + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = new Buffer(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } + + return value +} + +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @api private + */ + +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') +} + +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @api private + */ + +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } + + var match = DISPOSITION_TYPE_REGEXP.exec(string) + + if (!match) { + throw new TypeError('invalid type format') + } + + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() + + var key + var names = [] + var params = {} + var value + + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index + + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } + + names.push(key) + + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) + + // overwrite existing value + params[key] = value + continue + } + + if (typeof params[key] === 'string') { + continue + } + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + return new ContentDisposition(type, params) +} + +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @api private + */ + +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) +} + +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @api private + */ + +function pencode (char) { + var hex = String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() + return hex.length === 1 + ? '%0' + hex + : '%' + hex +} + +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring (val) { + var str = String(val) + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @api private + */ + +function ustring (val) { + var str = String(val) + + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + + return 'UTF-8\'\'' + encoded +} + +/** + * Class for parsed Content-Disposition header for v8 optimization + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} diff --git a/node_modules/content-disposition/package.json b/node_modules/content-disposition/package.json new file mode 100644 index 00000000..6b159797 --- /dev/null +++ b/node_modules/content-disposition/package.json @@ -0,0 +1,77 @@ +{ + "_args": [ + [ + "content-disposition@0.5.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "content-disposition@0.5.2", + "_id": "content-disposition@0.5.2", + "_inBundle": false, + "_integrity": "sha1-DPaLud318r55YcOoUXjLhdunjLQ=", + "_location": "/content-disposition", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "content-disposition@0.5.2", + "name": "content-disposition", + "escapedName": "content-disposition", + "rawSpec": "0.5.2", + "saveSpec": null, + "fetchSpec": "0.5.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.2.tgz", + "_spec": "0.5.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/content-disposition/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "description": "Create and parse Content-Disposition header", + "devDependencies": { + "eslint": "3.11.1", + "eslint-config-standard": "6.2.1", + "eslint-plugin-promise": "3.3.0", + "eslint-plugin-standard": "2.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/content-disposition#readme", + "keywords": [ + "content-disposition", + "http", + "rfc6266", + "res" + ], + "license": "MIT", + "name": "content-disposition", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-disposition.git" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "0.5.2" +} diff --git a/node_modules/content-type/HISTORY.md b/node_modules/content-type/HISTORY.md new file mode 100644 index 00000000..8f5cb703 --- /dev/null +++ b/node_modules/content-type/HISTORY.md @@ -0,0 +1,24 @@ +1.0.4 / 2017-09-11 +================== + + * perf: skip parameter parsing when no parameters + +1.0.3 / 2017-09-10 +================== + + * perf: remove argument reassignment + +1.0.2 / 2016-05-09 +================== + + * perf: enable strict mode + +1.0.1 / 2015-02-13 +================== + + * Improve missing `Content-Type` header error message + +1.0.0 / 2015-02-01 +================== + + * Initial implementation, derived from `media-typer@0.3.0` diff --git a/node_modules/content-type/LICENSE b/node_modules/content-type/LICENSE new file mode 100644 index 00000000..34b1a2de --- /dev/null +++ b/node_modules/content-type/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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/content-type/README.md b/node_modules/content-type/README.md new file mode 100644 index 00000000..3ed67413 --- /dev/null +++ b/node_modules/content-type/README.md @@ -0,0 +1,92 @@ +# content-type + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create and parse HTTP Content-Type header according to RFC 7231 + +## Installation + +```sh +$ npm install content-type +``` + +## API + +```js +var contentType = require('content-type') +``` + +### contentType.parse(string) + +```js +var obj = contentType.parse('image/svg+xml; charset=utf-8') +``` + +Parse a content type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (the type and subtype, always lower case). + Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter + always lower case). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the string is missing or invalid. + +### contentType.parse(req) + +```js +var obj = contentType.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`contentType.parse(req.headers['content-type'])`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.parse(res) + +```js +var obj = contentType.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`contentType.parse(res.getHeader('content-type'))`. + +Throws a `TypeError` if the `Content-Type` header is missing or invalid. + +### contentType.format(obj) + +```js +var str = contentType.format({type: 'image/svg+xml'}) +``` + +Format an object into a content type string. This will return a string of the +content type for the given object with the following properties (examples are +shown that produce the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The media type (will be lower-cased). Example: `'image/svg+xml'` + + - `parameters`: An object of the parameters in the media type (name of the + parameter will be lower-cased). Example: `{charset: 'utf-8'}` + +Throws a `TypeError` if the object contains an invalid type or parameter names. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/content-type.svg +[npm-url]: https://npmjs.org/package/content-type +[node-version-image]: https://img.shields.io/node/v/content-type.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/content-type/master.svg +[travis-url]: https://travis-ci.org/jshttp/content-type +[coveralls-image]: https://img.shields.io/coveralls/jshttp/content-type/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/content-type +[downloads-image]: https://img.shields.io/npm/dm/content-type.svg +[downloads-url]: https://npmjs.org/package/content-type diff --git a/node_modules/content-type/index.js b/node_modules/content-type/index.js new file mode 100644 index 00000000..6ce03f20 --- /dev/null +++ b/node_modules/content-type/index.js @@ -0,0 +1,222 @@ +/*! + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * Module exports. + * @public + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @public + */ + +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var type = obj.type + + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } + + var string = type + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') + } + } + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] + } + + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } + + return header +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @private + */ + +function qstring (val) { + var str = String(val) + + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } + + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type +} diff --git a/node_modules/content-type/package.json b/node_modules/content-type/package.json new file mode 100644 index 00000000..d8ed1311 --- /dev/null +++ b/node_modules/content-type/package.json @@ -0,0 +1,80 @@ +{ + "_args": [ + [ + "content-type@1.0.4", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "content-type@1.0.4", + "_id": "content-type@1.0.4", + "_inBundle": false, + "_integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "_location": "/content-type", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "content-type@1.0.4", + "name": "content-type", + "escapedName": "content-type", + "rawSpec": "1.0.4", + "saveSpec": null, + "fetchSpec": "1.0.4" + }, + "_requiredBy": [ + "/body-parser", + "/express", + "/express-graphql" + ], + "_resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "_spec": "1.0.4", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/jshttp/content-type/issues" + }, + "description": "Create and parse HTTP Content-Type header", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/content-type#readme", + "keywords": [ + "content-type", + "http", + "req", + "res", + "rfc7231" + ], + "license": "MIT", + "name": "content-type", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/content-type.git" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + }, + "version": "1.0.4" +} diff --git a/node_modules/cookie-signature/.npmignore b/node_modules/cookie-signature/.npmignore new file mode 100644 index 00000000..f1250e58 --- /dev/null +++ b/node_modules/cookie-signature/.npmignore @@ -0,0 +1,4 @@ +support +test +examples +*.sock diff --git a/node_modules/cookie-signature/History.md b/node_modules/cookie-signature/History.md new file mode 100644 index 00000000..78513cc3 --- /dev/null +++ b/node_modules/cookie-signature/History.md @@ -0,0 +1,38 @@ +1.0.6 / 2015-02-03 +================== + +* use `npm test` instead of `make test` to run tests +* clearer assertion messages when checking input + + +1.0.5 / 2014-09-05 +================== + +* add license to package.json + +1.0.4 / 2014-06-25 +================== + + * corrected avoidance of timing attacks (thanks @tenbits!) + +1.0.3 / 2014-01-28 +================== + + * [incorrect] fix for timing attacks + +1.0.2 / 2014-01-28 +================== + + * fix missing repository warning + * fix typo in test + +1.0.1 / 2013-04-15 +================== + + * Revert "Changed underlying HMAC algo. to sha512." + * Revert "Fix for timing attacks on MAC verification." + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/cookie-signature/Readme.md b/node_modules/cookie-signature/Readme.md new file mode 100644 index 00000000..2559e841 --- /dev/null +++ b/node_modules/cookie-signature/Readme.md @@ -0,0 +1,42 @@ + +# cookie-signature + + Sign and unsign cookies. + +## Example + +```js +var cookie = require('cookie-signature'); + +var val = cookie.sign('hello', 'tobiiscool'); +val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); + +var val = cookie.sign('hello', 'tobiiscool'); +cookie.unsign(val, 'tobiiscool').should.equal('hello'); +cookie.unsign(val, 'luna').should.be.false; +``` + +## License + +(The MIT License) + +Copyright (c) 2012 LearnBoost <tj@learnboost.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/cookie-signature/index.js b/node_modules/cookie-signature/index.js new file mode 100644 index 00000000..b8c9463a --- /dev/null +++ b/node_modules/cookie-signature/index.js @@ -0,0 +1,51 @@ +/** + * Module dependencies. + */ + +var crypto = require('crypto'); + +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; +}; + +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} diff --git a/node_modules/cookie-signature/package.json b/node_modules/cookie-signature/package.json new file mode 100644 index 00000000..889d8d1c --- /dev/null +++ b/node_modules/cookie-signature/package.json @@ -0,0 +1,60 @@ +{ + "_args": [ + [ + "cookie-signature@1.0.6", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "cookie-signature@1.0.6", + "_id": "cookie-signature@1.0.6", + "_inBundle": false, + "_integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=", + "_location": "/cookie-signature", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "cookie-signature@1.0.6", + "name": "cookie-signature", + "escapedName": "cookie-signature", + "rawSpec": "1.0.6", + "saveSpec": null, + "fetchSpec": "1.0.6" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "_spec": "1.0.6", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@learnboost.com" + }, + "bugs": { + "url": "https://github.com/visionmedia/node-cookie-signature/issues" + }, + "dependencies": {}, + "description": "Sign and unsign cookies", + "devDependencies": { + "mocha": "*", + "should": "*" + }, + "homepage": "https://github.com/visionmedia/node-cookie-signature#readme", + "keywords": [ + "cookie", + "sign", + "unsign" + ], + "license": "MIT", + "main": "index", + "name": "cookie-signature", + "repository": { + "type": "git", + "url": "git+https://github.com/visionmedia/node-cookie-signature.git" + }, + "scripts": { + "test": "mocha --require should --reporter spec" + }, + "version": "1.0.6" +} diff --git a/node_modules/cookie/HISTORY.md b/node_modules/cookie/HISTORY.md new file mode 100644 index 00000000..5bd64854 --- /dev/null +++ b/node_modules/cookie/HISTORY.md @@ -0,0 +1,118 @@ +0.3.1 / 2016-05-26 +================== + + * Fix `sameSite: true` to work with draft-7 clients + - `true` now sends `SameSite=Strict` instead of `SameSite` + +0.3.0 / 2016-05-26 +================== + + * Add `sameSite` option + - Replaces `firstPartyOnly` option, never implemented by browsers + * Improve error message when `encode` is not a function + * Improve error message when `expires` is not a `Date` + +0.2.4 / 2016-05-20 +================== + + * perf: enable strict mode + * perf: use for loop in parse + * perf: use string concatination for serialization + +0.2.3 / 2015-10-25 +================== + + * Fix cookie `Max-Age` to never be a floating point number + +0.2.2 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.2.1 / 2015-09-17 +================== + + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.2.0 / 2015-08-13 +================== + + * Add `firstPartyOnly` option + * Throw better error for invalid argument to parse + * perf: hoist regular expression + +0.1.5 / 2015-09-17 +================== + + * Fix regression when setting empty cookie value + - Ease the new restriction, which is just basic header-level validation + * Fix typo in invalid value errors + +0.1.4 / 2015-09-17 +================== + + * Throw better error for invalid argument to parse + * Throw on invalid values provided to `serialize` + - Ensures the resulting string is a valid HTTP header value + +0.1.3 / 2015-05-19 +================== + + * Reduce the scope of try-catch deopt + * Remove argument reassignments + +0.1.2 / 2014-04-16 +================== + + * Remove unnecessary files from npm package + +0.1.1 / 2014-02-23 +================== + + * Fix bad parse when cookie value contained a comma + * Fix support for `maxAge` of `0` + +0.1.0 / 2013-05-01 +================== + + * Add `decode` option + * Add `encode` option + +0.0.6 / 2013-04-08 +================== + + * Ignore cookie parts missing `=` + +0.0.5 / 2012-10-29 +================== + + * Return raw cookie value if value unescape errors + +0.0.4 / 2012-06-21 +================== + + * Use encode/decodeURIComponent for cookie encoding/decoding + - Improve server/client interoperability + +0.0.3 / 2012-06-06 +================== + + * Only escape special characters per the cookie RFC + +0.0.2 / 2012-06-01 +================== + + * Fix `maxAge` option to not throw error + +0.0.1 / 2012-05-28 +================== + + * Add more tests + +0.0.0 / 2012-05-28 +================== + + * Initial release diff --git a/node_modules/cookie/LICENSE b/node_modules/cookie/LICENSE new file mode 100644 index 00000000..058b6b4e --- /dev/null +++ b/node_modules/cookie/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Roman Shtylman +Copyright (c) 2015 Douglas Christopher Wilson + +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/cookie/README.md b/node_modules/cookie/README.md new file mode 100644 index 00000000..db0d0782 --- /dev/null +++ b/node_modules/cookie/README.md @@ -0,0 +1,220 @@ +# cookie + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Basic HTTP cookie parser and serializer for HTTP servers. + +## Installation + +```sh +$ npm install cookie +``` + +## API + +```js +var cookie = require('cookie'); +``` + +### cookie.parse(str, options) + +Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs. +The `str` argument is the string representing a `Cookie` header value and `options` is an +optional object containing additional parsing options. + +```js +var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2'); +// { foo: 'bar', equation: 'E=mc^2' } +``` + +#### Options + +`cookie.parse` accepts these properties in the options object. + +##### decode + +Specifies a function that will be used to decode a cookie's value. Since the value of a cookie +has a limited character set (and must be a simple string), this function can be used to decode +a previously-encoded cookie value into a JavaScript string or other object. + +The default function is the global `decodeURIComponent`, which will decode any URL-encoded +sequences into their byte representations. + +**note** if an error is thrown from this function, the original, non-decoded cookie value will +be returned as the cookie's value. + +### cookie.serialize(name, value, options) + +Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the +name for the cookie, the `value` argument is the value to set the cookie to, and the `options` +argument is an optional object containing additional serialization options. + +```js +var setCookie = cookie.serialize('foo', 'bar'); +// foo=bar +``` + +#### Options + +`cookie.serialize` accepts these properties in the options object. + +##### domain + +Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6266-5.2.3]. By default, no +domain is set, and most clients will consider the cookie to apply to only the current domain. + +##### encode + +Specifies a function that will be used to encode a cookie's value. Since value of a cookie +has a limited character set (and must be a simple string), this function can be used to encode +a value into a string suited for a cookie's value. + +The default function is the global `ecodeURIComponent`, which will encode a JavaScript string +into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range. + +##### expires + +Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6266-5.2.1]. +By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and +will delete it on a condition like exiting a web browser application. + +**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and +`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### httpOnly + +Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6266-5.2.6]. When truthy, +the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not allow client-side +JavaScript to see the cookie in `document.cookie`. + +##### maxAge + +Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6266-5.2.2]. +The given number will be converted to an integer by rounding down. By default, no maximum age is set. + +**note** the [cookie storage model specification][rfc-6266-5.3] states that if both `expires` and +`magAge` are set, then `maxAge` takes precedence, but it is possiblke not all clients by obey this, +so if both are set, they should point to the same date and time. + +##### path + +Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6266-5.2.4]. By default, the path +is considered the ["default path"][rfc-6266-5.1.4]. By default, no maximum age is set, and most +clients will consider this a "non-persistent cookie" and will delete it on a condition like exiting +a web browser application. + +##### sameSite + +Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][draft-west-first-party-cookies-07]. + + - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + - `false` will not set the `SameSite` attribute. + - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement. + - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement. + +More information about the different enforcement levels can be found in the specification +https://tools.ietf.org/html/draft-west-first-party-cookies-07#section-4.1.1 + +**note** This is an attribute that has not yet been fully standardized, and may change in the future. +This also means many clients may ignore this attribute until they understand it. + +##### secure + +Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6266-5.2.5]. When truthy, +the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set. + +**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to +the server in the future if the browser does not have an HTTPS connection. + +## Example + +The following example uses this module in conjunction with the Node.js core HTTP server +to prompt a user for their name and display it back on future visits. + +```js +var cookie = require('cookie'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var url = require('url'); + +function onRequest(req, res) { + // Parse the query string + var query = url.parse(req.url, true, true).query; + + if (query && query.name) { + // Set a new cookie with the name + res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), { + httpOnly: true, + maxAge: 60 * 60 * 24 * 7 // 1 week + })); + + // Redirect back after setting cookie + res.statusCode = 302; + res.setHeader('Location', req.headers.referer || '/'); + res.end(); + return; + } + + // Parse the cookies on the request + var cookies = cookie.parse(req.headers.cookie || ''); + + // Get the visitor name set in the cookie + var name = cookies.name; + + res.setHeader('Content-Type', 'text/html; charset=UTF-8'); + + if (name) { + res.write('

Welcome back, ' + escapeHtml(name) + '!

'); + } else { + res.write('

Hello, new visitor!

'); + } + + res.write('
'); + res.write(' '); + res.end(' values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public + */ + +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } + + return obj; +} + +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } + + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } + + var value = enc(val); + + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } + + var str = name + '=' + value; + + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } + + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } + + str += '; Domain=' + opt.domain; + } + + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; + } + + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } + + str += '; Expires=' + opt.expires.toUTCString(); + } + + if (opt.httpOnly) { + str += '; HttpOnly'; + } + + if (opt.secure) { + str += '; Secure'; + } + + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; + + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } + + return str; +} + +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ + +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} diff --git a/node_modules/cookie/package.json b/node_modules/cookie/package.json new file mode 100644 index 00000000..82cb7dc8 --- /dev/null +++ b/node_modules/cookie/package.json @@ -0,0 +1,74 @@ +{ + "_args": [ + [ + "cookie@0.3.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "cookie@0.3.1", + "_id": "cookie@0.3.1", + "_inBundle": false, + "_integrity": "sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=", + "_location": "/cookie", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "cookie@0.3.1", + "name": "cookie", + "escapedName": "cookie", + "rawSpec": "0.3.1", + "saveSpec": null, + "fetchSpec": "0.3.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.3.1.tgz", + "_spec": "0.3.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + }, + "bugs": { + "url": "https://github.com/jshttp/cookie/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "description": "HTTP server cookie parsing and serialization", + "devDependencies": { + "istanbul": "0.4.3", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/cookie#readme", + "keywords": [ + "cookie", + "cookies" + ], + "license": "MIT", + "name": "cookie", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/cookie.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + }, + "version": "0.3.1" +} diff --git a/node_modules/debug/.coveralls.yml b/node_modules/debug/.coveralls.yml new file mode 100644 index 00000000..20a70685 --- /dev/null +++ b/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/node_modules/debug/.eslintrc b/node_modules/debug/.eslintrc new file mode 100644 index 00000000..8a37ae2c --- /dev/null +++ b/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/debug/.npmignore b/node_modules/debug/.npmignore new file mode 100644 index 00000000..5f60eecc --- /dev/null +++ b/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/node_modules/debug/.travis.yml b/node_modules/debug/.travis.yml new file mode 100644 index 00000000..6c6090c3 --- /dev/null +++ b/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/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md new file mode 100644 index 00000000..eadaa189 --- /dev/null +++ b/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/debug/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 00000000..658c933d --- /dev/null +++ b/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/debug/Makefile b/node_modules/debug/Makefile new file mode 100644 index 00000000..584da8bf --- /dev/null +++ b/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/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 00000000..f67be6b3 --- /dev/null +++ b/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/debug/component.json b/node_modules/debug/component.json new file mode 100644 index 00000000..9de26410 --- /dev/null +++ b/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/debug/karma.conf.js b/node_modules/debug/karma.conf.js new file mode 100644 index 00000000..103a82d1 --- /dev/null +++ b/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/debug/node.js b/node_modules/debug/node.js new file mode 100644 index 00000000..7fc36fe6 --- /dev/null +++ b/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 00000000..52beeb86 --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "debug@2.6.9", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "debug@2.6.9", + "_id": "debug@2.6.9", + "_inBundle": false, + "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "debug@2.6.9", + "name": "debug", + "escapedName": "debug", + "rawSpec": "2.6.9", + "saveSpec": null, + "fetchSpec": "2.6.9" + }, + "_requiredBy": [ + "/body-parser", + "/express", + "/finalhandler", + "/send" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "_spec": "2.6.9", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + } + ], + "dependencies": { + "ms": "2.0.0" + }, + "description": "small debugging utility", + "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" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "2.6.9" +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 00000000..71069249 --- /dev/null +++ b/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/debug/src/debug.js b/node_modules/debug/src/debug.js new file mode 100644 index 00000000..6a5e3fc9 --- /dev/null +++ b/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/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 00000000..e12cf4d5 --- /dev/null +++ b/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/debug/src/inspector-log.js b/node_modules/debug/src/inspector-log.js new file mode 100644 index 00000000..60ea6c04 --- /dev/null +++ b/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/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 00000000..b15109c9 --- /dev/null +++ b/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/depd/History.md b/node_modules/depd/History.md new file mode 100644 index 00000000..507ecb8d --- /dev/null +++ b/node_modules/depd/History.md @@ -0,0 +1,96 @@ +1.1.2 / 2018-01-11 +================== + + * perf: remove argument reassignment + * Support Node.js 0.6 to 9.x + +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/depd/LICENSE b/node_modules/depd/LICENSE new file mode 100644 index 00000000..84441fbb --- /dev/null +++ b/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/depd/Readme.md b/node_modules/depd/Readme.md new file mode 100644 index 00000000..77906702 --- /dev/null +++ b/node_modules/depd/Readme.md @@ -0,0 +1,280 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: https://nodejs.org/en/download/ diff --git a/node_modules/depd/index.js b/node_modules/depd/index.js new file mode 100644 index 00000000..d758d3c8 --- /dev/null +++ b/node_modules/depd/index.js @@ -0,0 +1,522 @@ +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() + + for (var i = 0; i < vals.length; i++) { + var val = vals[i] + + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/depd/lib/browser/index.js b/node_modules/depd/lib/browser/index.js new file mode 100644 index 00000000..6be45cc2 --- /dev/null +++ b/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/node_modules/depd/lib/compat/callsite-tostring.js b/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 00000000..73186dc6 --- /dev/null +++ b/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/node_modules/depd/lib/compat/event-listener-count.js b/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 00000000..3a8925d1 --- /dev/null +++ b/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} diff --git a/node_modules/depd/lib/compat/index.js b/node_modules/depd/lib/compat/index.js new file mode 100644 index 00000000..955b3336 --- /dev/null +++ b/node_modules/depd/lib/compat/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString (obj) { + return obj.toString() +} diff --git a/node_modules/depd/package.json b/node_modules/depd/package.json new file mode 100644 index 00000000..64862c5d --- /dev/null +++ b/node_modules/depd/package.json @@ -0,0 +1,82 @@ +{ + "_args": [ + [ + "depd@1.1.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "depd@1.1.2", + "_id": "depd@1.1.2", + "_inBundle": false, + "_integrity": "sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak=", + "_location": "/depd", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "depd@1.1.2", + "name": "depd", + "escapedName": "depd", + "rawSpec": "1.1.2", + "saveSpec": null, + "fetchSpec": "1.1.2" + }, + "_requiredBy": [ + "/body-parser", + "/express", + "/http-errors", + "/send" + ], + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", + "_spec": "1.1.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "browser": "lib/browser/index.js", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "description": "Deprecate all the things", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "7.1.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "homepage": "https://github.com/dougwilson/nodejs-depd#readme", + "keywords": [ + "deprecate", + "deprecated" + ], + "license": "MIT", + "name": "depd", + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" + }, + "version": "1.1.2" +} diff --git a/node_modules/destroy/LICENSE b/node_modules/destroy/LICENSE new file mode 100644 index 00000000..a7ae8ee9 --- /dev/null +++ b/node_modules/destroy/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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/destroy/README.md b/node_modules/destroy/README.md new file mode 100644 index 00000000..6474bc3c --- /dev/null +++ b/node_modules/destroy/README.md @@ -0,0 +1,60 @@ +# Destroy + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Destroy a stream. + +This module is meant to ensure a stream gets destroyed, handling different APIs +and Node.js bugs. + +## API + +```js +var destroy = require('destroy') +``` + +### destroy(stream) + +Destroy the given stream. In most cases, this is identical to a simple +`stream.destroy()` call. The rules are as follows for a given stream: + + 1. If the `stream` is an instance of `ReadStream`, then call `stream.destroy()` + and add a listener to the `open` event to call `stream.close()` if it is + fired. This is for a Node.js bug that will leak a file descriptor if + `.destroy()` is called before `open`. + 2. If the `stream` is not an instance of `Stream`, then nothing happens. + 3. If the `stream` has a `.destroy()` method, then call it. + +The function returns the `stream` passed in as the argument. + +## Example + +```js +var destroy = require('destroy') + +var fs = require('fs') +var stream = fs.createReadStream('package.json') + +// ... and later +destroy(stream) +``` + +[npm-image]: https://img.shields.io/npm/v/destroy.svg?style=flat-square +[npm-url]: https://npmjs.org/package/destroy +[github-tag]: http://img.shields.io/github/tag/stream-utils/destroy.svg?style=flat-square +[github-url]: https://github.com/stream-utils/destroy/tags +[travis-image]: https://img.shields.io/travis/stream-utils/destroy.svg?style=flat-square +[travis-url]: https://travis-ci.org/stream-utils/destroy +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/destroy.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/stream-utils/destroy?branch=master +[license-image]: http://img.shields.io/npm/l/destroy.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/destroy.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/destroy +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/destroy/index.js b/node_modules/destroy/index.js new file mode 100644 index 00000000..6da2d26e --- /dev/null +++ b/node_modules/destroy/index.js @@ -0,0 +1,75 @@ +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var ReadStream = require('fs').ReadStream +var Stream = require('stream') + +/** + * Module exports. + * @public + */ + +module.exports = destroy + +/** + * Destroy a stream. + * + * @param {object} stream + * @public + */ + +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) + } + + if (!(stream instanceof Stream)) { + return stream + } + + if (typeof stream.destroy === 'function') { + stream.destroy() + } + + return stream +} + +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ + +function destroyReadStream(stream) { + stream.destroy() + + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} + +/** + * On open handler to close stream. + * @private + */ + +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() + } +} diff --git a/node_modules/destroy/package.json b/node_modules/destroy/package.json new file mode 100644 index 00000000..f7869716 --- /dev/null +++ b/node_modules/destroy/package.json @@ -0,0 +1,74 @@ +{ + "_args": [ + [ + "destroy@1.0.4", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "destroy@1.0.4", + "_id": "destroy@1.0.4", + "_inBundle": false, + "_integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=", + "_location": "/destroy", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "destroy@1.0.4", + "name": "destroy", + "escapedName": "destroy", + "rawSpec": "1.0.4", + "saveSpec": null, + "fetchSpec": "1.0.4" + }, + "_requiredBy": [ + "/send" + ], + "_resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", + "_spec": "1.0.4", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/stream-utils/destroy/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "description": "destroy a stream if possible", + "devDependencies": { + "istanbul": "0.4.2", + "mocha": "2.3.4" + }, + "files": [ + "index.js", + "LICENSE" + ], + "homepage": "https://github.com/stream-utils/destroy#readme", + "keywords": [ + "stream", + "streams", + "destroy", + "cleanup", + "leak", + "fd" + ], + "license": "MIT", + "name": "destroy", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/destroy.git" + }, + "scripts": { + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "version": "1.0.4" +} diff --git a/node_modules/ee-first/LICENSE b/node_modules/ee-first/LICENSE new file mode 100644 index 00000000..a7ae8ee9 --- /dev/null +++ b/node_modules/ee-first/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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/ee-first/README.md b/node_modules/ee-first/README.md new file mode 100644 index 00000000..cbd2478b --- /dev/null +++ b/node_modules/ee-first/README.md @@ -0,0 +1,80 @@ +# EE First + +[![NPM version][npm-image]][npm-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] +[![Gittip][gittip-image]][gittip-url] + +Get the first event in a set of event emitters and event pairs, +then clean up after itself. + +## Install + +```sh +$ npm install ee-first +``` + +## API + +```js +var first = require('ee-first') +``` + +### first(arr, listener) + +Invoke `listener` on the first event from the list specified in `arr`. `arr` is +an array of arrays, with each array in the format `[ee, ...event]`. `listener` +will be called only once, the first time any of the given events are emitted. If +`error` is one of the listened events, then if that fires first, the `listener` +will be given the `err` argument. + +The `listener` is invoked as `listener(err, ee, event, args)`, where `err` is the +first argument emitted from an `error` event, if applicable; `ee` is the event +emitter that fired; `event` is the string event name that fired; and `args` is an +array of the arguments that were emitted on the event. + +```js +var ee1 = new EventEmitter() +var ee2 = new EventEmitter() + +first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) +``` + +#### .cancel() + +The group of listeners can be cancelled before being invoked and have all the event +listeners removed from the underlying event emitters. + +```js +var thunk = first([ + [ee1, 'close', 'end', 'error'], + [ee2, 'error'] +], function (err, ee, event, args) { + // listener invoked +}) + +// cancel and clean up +thunk.cancel() +``` + +[npm-image]: https://img.shields.io/npm/v/ee-first.svg?style=flat-square +[npm-url]: https://npmjs.org/package/ee-first +[github-tag]: http://img.shields.io/github/tag/jonathanong/ee-first.svg?style=flat-square +[github-url]: https://github.com/jonathanong/ee-first/tags +[travis-image]: https://img.shields.io/travis/jonathanong/ee-first.svg?style=flat-square +[travis-url]: https://travis-ci.org/jonathanong/ee-first +[coveralls-image]: https://img.shields.io/coveralls/jonathanong/ee-first.svg?style=flat-square +[coveralls-url]: https://coveralls.io/r/jonathanong/ee-first?branch=master +[license-image]: http://img.shields.io/npm/l/ee-first.svg?style=flat-square +[license-url]: LICENSE.md +[downloads-image]: http://img.shields.io/npm/dm/ee-first.svg?style=flat-square +[downloads-url]: https://npmjs.org/package/ee-first +[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square +[gittip-url]: https://www.gittip.com/jonathanong/ diff --git a/node_modules/ee-first/index.js b/node_modules/ee-first/index.js new file mode 100644 index 00000000..501287cd --- /dev/null +++ b/node_modules/ee-first/index.js @@ -0,0 +1,95 @@ +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = first + +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ + +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') + + var cleanups = [] + + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] + + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') + + var ee = arr[0] + + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) + + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } + } + + function callback() { + cleanup() + done.apply(null, arguments) + } + + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } + + function thunk(fn) { + done = fn + } + + thunk.cancel = cleanup + + return thunk +} + +/** + * Create the event listener. + * @private + */ + +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null + + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + done(err, ee, event, args) + } +} diff --git a/node_modules/ee-first/package.json b/node_modules/ee-first/package.json new file mode 100644 index 00000000..ea403f92 --- /dev/null +++ b/node_modules/ee-first/package.json @@ -0,0 +1,66 @@ +{ + "_args": [ + [ + "ee-first@1.1.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "ee-first@1.1.1", + "_id": "ee-first@1.1.1", + "_inBundle": false, + "_integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0=", + "_location": "/ee-first", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ee-first@1.1.1", + "name": "ee-first", + "escapedName": "ee-first", + "rawSpec": "1.1.1", + "saveSpec": null, + "fetchSpec": "1.1.1" + }, + "_requiredBy": [ + "/on-finished" + ], + "_resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "_spec": "1.1.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/jonathanong/ee-first/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "description": "return the first event in a set of ee/event pairs", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "files": [ + "index.js", + "LICENSE" + ], + "homepage": "https://github.com/jonathanong/ee-first#readme", + "license": "MIT", + "name": "ee-first", + "repository": { + "type": "git", + "url": "git+https://github.com/jonathanong/ee-first.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.1.1" +} diff --git a/node_modules/encodeurl/HISTORY.md b/node_modules/encodeurl/HISTORY.md new file mode 100644 index 00000000..41313b2b --- /dev/null +++ b/node_modules/encodeurl/HISTORY.md @@ -0,0 +1,14 @@ +1.0.2 / 2018-01-21 +================== + + * Fix encoding `%` as last character + +1.0.1 / 2016-06-09 +================== + + * Fix encoding unpaired surrogates at start/end of string + +1.0.0 / 2016-06-08 +================== + + * Initial release diff --git a/node_modules/encodeurl/LICENSE b/node_modules/encodeurl/LICENSE new file mode 100644 index 00000000..8812229b --- /dev/null +++ b/node_modules/encodeurl/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Douglas Christopher Wilson + +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/encodeurl/README.md b/node_modules/encodeurl/README.md new file mode 100644 index 00000000..127c5a0d --- /dev/null +++ b/node_modules/encodeurl/README.md @@ -0,0 +1,128 @@ +# encodeurl + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Encode a URL to a percent-encoded form, excluding already-encoded sequences + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install encodeurl +``` + +## API + +```js +var encodeUrl = require('encodeurl') +``` + +### encodeUrl(url) + +Encode a URL to a percent-encoded form, excluding already-encoded sequences. + +This function will take an already-encoded URL and encode all the non-URL +code points (as UTF-8 byte sequences). This function will not encode the +"%" character unless it is not part of a valid sequence (`%20` will be +left as-is, but `%foo` will be encoded as `%25foo`). + +This encode is meant to be "safe" and does not throw errors. It will try as +hard as it can to properly encode the given URL, including replacing any raw, +unpaired surrogate pairs with the Unicode replacement character prior to +encoding. + +This function is _similar_ to the intrinsic function `encodeURI`, except it +will not encode the `%` character if that is part of a valid sequence, will +not encode `[` and `]` (for IPv6 hostnames) and will replace raw, unpaired +surrogate pairs with the Unicode replacement character (instead of throwing). + +## Examples + +### Encode a URL containing user-controled data + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') + +http.createServer(function onRequest (req, res) { + // get encoded form of inbound url + var url = encodeUrl(req.url) + + // create html message + var body = '

Location ' + escapeHtml(url) + ' not found

' + + // send a 404 + res.statusCode = 404 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.end(body, 'utf-8') +}) +``` + +### Encode a URL for use in a header field + +```js +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var url = require('url') + +http.createServer(function onRequest (req, res) { + // parse inbound url + var href = url.parse(req) + + // set new host for redirect + href.host = 'localhost' + href.protocol = 'https:' + href.slashes = true + + // create location header + var location = encodeUrl(url.format(href)) + + // create html message + var body = '

Redirecting to new site: ' + escapeHtml(location) + '

' + + // send a 301 + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', String(Buffer.byteLength(body, 'utf-8'))) + res.setHeader('Location', location) + res.end(body, 'utf-8') +}) +``` + +## Testing + +```sh +$ npm test +$ npm run lint +``` + +## References + +- [RFC 3986: Uniform Resource Identifier (URI): Generic Syntax][rfc-3986] +- [WHATWG URL Living Standard][whatwg-url] + +[rfc-3986]: https://tools.ietf.org/html/rfc3986 +[whatwg-url]: https://url.spec.whatwg.org/ + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/encodeurl.svg +[npm-url]: https://npmjs.org/package/encodeurl +[node-version-image]: https://img.shields.io/node/v/encodeurl.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/encodeurl.svg +[travis-url]: https://travis-ci.org/pillarjs/encodeurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/encodeurl.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/encodeurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/encodeurl.svg +[downloads-url]: https://npmjs.org/package/encodeurl diff --git a/node_modules/encodeurl/index.js b/node_modules/encodeurl/index.js new file mode 100644 index 00000000..fc4906c6 --- /dev/null +++ b/node_modules/encodeurl/index.js @@ -0,0 +1,60 @@ +/*! + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = encodeUrl + +/** + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. + * @private + */ + +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g + +/** + * RegExp to match unmatched surrogate pair. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g + +/** + * String to replace unmatched surrogate pair with. + * @private + */ + +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' + +/** + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). + * + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. + * + * @param {string} url + * @return {string} + * @public + */ + +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} diff --git a/node_modules/encodeurl/package.json b/node_modules/encodeurl/package.json new file mode 100644 index 00000000..2e94164a --- /dev/null +++ b/node_modules/encodeurl/package.json @@ -0,0 +1,81 @@ +{ + "_args": [ + [ + "encodeurl@1.0.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "encodeurl@1.0.2", + "_id": "encodeurl@1.0.2", + "_inBundle": false, + "_integrity": "sha1-rT/0yG7C0CkyL1oCw6mmBslbP1k=", + "_location": "/encodeurl", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "encodeurl@1.0.2", + "name": "encodeurl", + "escapedName": "encodeurl", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/express", + "/finalhandler", + "/send", + "/serve-static" + ], + "_resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "_spec": "1.0.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/pillarjs/encodeurl/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "description": "Encode a URL to a percent-encoded form, excluding already-encoded sequences", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/pillarjs/encodeurl#readme", + "keywords": [ + "encode", + "encodeurl", + "url" + ], + "license": "MIT", + "name": "encodeurl", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/encodeurl.git" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.0.2" +} diff --git a/node_modules/escape-html/LICENSE b/node_modules/escape-html/LICENSE new file mode 100644 index 00000000..2e70de97 --- /dev/null +++ b/node_modules/escape-html/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2013 TJ Holowaychuk +Copyright (c) 2015 Andreas Lubbe +Copyright (c) 2015 Tiancheng "Timothy" Gu + +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/escape-html/Readme.md b/node_modules/escape-html/Readme.md new file mode 100644 index 00000000..653d9eaa --- /dev/null +++ b/node_modules/escape-html/Readme.md @@ -0,0 +1,43 @@ + +# escape-html + + Escape string for use in HTML + +## Example + +```js +var escape = require('escape-html'); +var html = escape('foo & bar'); +// -> foo & bar +``` + +## Benchmark + +``` +$ npm run-script bench + +> escape-html@1.0.3 bench nodejs-escape-html +> node benchmark/index.js + + + http_parser@1.0 + node@0.10.33 + v8@3.14.5.9 + ares@1.9.0-DEV + uv@0.10.29 + zlib@1.2.3 + modules@11 + openssl@1.0.1j + + 1 test completed. + 2 tests completed. + 3 tests completed. + + no special characters x 19,435,271 ops/sec ±0.85% (187 runs sampled) + single special character x 6,132,421 ops/sec ±0.67% (194 runs sampled) + many special characters x 3,175,826 ops/sec ±0.65% (193 runs sampled) +``` + +## License + + MIT \ No newline at end of file diff --git a/node_modules/escape-html/index.js b/node_modules/escape-html/index.js new file mode 100644 index 00000000..bf9e226f --- /dev/null +++ b/node_modules/escape-html/index.js @@ -0,0 +1,78 @@ +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ + +'use strict'; + +/** + * Module variables. + * @private + */ + +var matchHtmlRegExp = /["'&<>]/; + +/** + * Module exports. + * @public + */ + +module.exports = escapeHtml; + +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ + +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); + + if (!match) { + return str; + } + + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: + continue; + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } + + lastIndex = index + 1; + html += escape; + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} diff --git a/node_modules/escape-html/package.json b/node_modules/escape-html/package.json new file mode 100644 index 00000000..f3f8f73f --- /dev/null +++ b/node_modules/escape-html/package.json @@ -0,0 +1,62 @@ +{ + "_args": [ + [ + "escape-html@1.0.3", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "escape-html@1.0.3", + "_id": "escape-html@1.0.3", + "_inBundle": false, + "_integrity": "sha1-Aljq5NPQwJdN4cFpGI7wBR0dGYg=", + "_location": "/escape-html", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "escape-html@1.0.3", + "name": "escape-html", + "escapedName": "escape-html", + "rawSpec": "1.0.3", + "saveSpec": null, + "fetchSpec": "1.0.3" + }, + "_requiredBy": [ + "/express", + "/finalhandler", + "/send", + "/serve-static" + ], + "_resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "_spec": "1.0.3", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/component/escape-html/issues" + }, + "description": "Escape string for use in HTML", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "1.0.0" + }, + "files": [ + "LICENSE", + "Readme.md", + "index.js" + ], + "homepage": "https://github.com/component/escape-html#readme", + "keywords": [ + "escape", + "html", + "utility" + ], + "license": "MIT", + "name": "escape-html", + "repository": { + "type": "git", + "url": "git+https://github.com/component/escape-html.git" + }, + "scripts": { + "bench": "node benchmark/index.js" + }, + "version": "1.0.3" +} diff --git a/node_modules/etag/HISTORY.md b/node_modules/etag/HISTORY.md new file mode 100644 index 00000000..222b293d --- /dev/null +++ b/node_modules/etag/HISTORY.md @@ -0,0 +1,83 @@ +1.8.1 / 2017-09-12 +================== + + * perf: replace regular expression with substring + +1.8.0 / 2017-02-18 +================== + + * Use SHA1 instead of MD5 for ETag hashing + - Improves performance for larger entities + - Works with FIPS 140-2 OpenSSL configuration + +1.7.0 / 2015-06-08 +================== + + * Always include entity length in ETags for hash length extensions + * Generate non-Stats ETags using MD5 only (no longer CRC32) + * Improve stat performance by removing hashing + * Remove base64 padding in ETags to shorten + * Use MD5 instead of MD4 in weak ETags over 1KB + +1.6.0 / 2015-05-10 +================== + + * Improve support for JXcore + * Remove requirement of `atime` in the stats object + * Support "fake" stats objects in environments without `fs` + +1.5.1 / 2014-11-19 +================== + + * deps: crc@3.2.1 + - Minor fixes + +1.5.0 / 2014-10-14 +================== + + * Improve string performance + * Slightly improve speed for weak ETags over 1KB + +1.4.0 / 2014-09-21 +================== + + * Support "fake" stats objects + * Support Node.js 0.6 + +1.3.1 / 2014-09-14 +================== + + * Use the (new and improved) `crc` for crc32 + +1.3.0 / 2014-08-29 +================== + + * Default strings to strong ETags + * Improve speed for weak ETags over 1KB + +1.2.1 / 2014-08-29 +================== + + * Use the (much faster) `buffer-crc32` for crc32 + +1.2.0 / 2014-08-24 +================== + + * Add support for file stat objects + +1.1.0 / 2014-08-24 +================== + + * Add fast-path for empty entity + * Add weak ETag generation + * Shrink size of generated ETags + +1.0.1 / 2014-08-24 +================== + + * Fix behavior of string containing Unicode + +1.0.0 / 2014-05-18 +================== + + * Initial release diff --git a/node_modules/etag/LICENSE b/node_modules/etag/LICENSE new file mode 100644 index 00000000..cab251c2 --- /dev/null +++ b/node_modules/etag/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/etag/README.md b/node_modules/etag/README.md new file mode 100644 index 00000000..09c2169e --- /dev/null +++ b/node_modules/etag/README.md @@ -0,0 +1,159 @@ +# etag + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create simple HTTP ETags + +This module generates HTTP ETags (as defined in RFC 7232) for use in +HTTP responses. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install etag +``` + +## API + + + +```js +var etag = require('etag') +``` + +### etag(entity, [options]) + +Generate a strong ETag for the given entity. This should be the complete +body of the entity. Strings, `Buffer`s, and `fs.Stats` are accepted. By +default, a strong ETag is generated except for `fs.Stats`, which will +generate a weak ETag (this can be overwritten by `options.weak`). + + + +```js +res.setHeader('ETag', etag(body)) +``` + +#### Options + +`etag` accepts these properties in the options object. + +##### weak + +Specifies if the generated ETag will include the weak validator mark (that +is, the leading `W/`). The actual entity tag is the same. The default value +is `false`, unless the `entity` is `fs.Stats`, in which case it is `true`. + +## Testing + +```sh +$ npm test +``` + +## Benchmark + +```bash +$ npm run-script bench + +> etag@1.8.1 bench nodejs-etag +> node benchmark/index.js + + http_parser@2.7.0 + node@6.11.1 + v8@5.1.281.103 + uv@1.11.0 + zlib@1.2.11 + ares@1.10.1-DEV + icu@58.2 + modules@48 + openssl@1.0.2k + +> node benchmark/body0-100b.js + + 100B body + + 4 tests completed. + + buffer - strong x 258,647 ops/sec ±1.07% (180 runs sampled) + buffer - weak x 263,812 ops/sec ±0.61% (184 runs sampled) + string - strong x 259,955 ops/sec ±1.19% (185 runs sampled) + string - weak x 264,356 ops/sec ±1.09% (184 runs sampled) + +> node benchmark/body1-1kb.js + + 1KB body + + 4 tests completed. + + buffer - strong x 189,018 ops/sec ±1.12% (182 runs sampled) + buffer - weak x 190,586 ops/sec ±0.81% (186 runs sampled) + string - strong x 144,272 ops/sec ±0.96% (188 runs sampled) + string - weak x 145,380 ops/sec ±1.43% (187 runs sampled) + +> node benchmark/body2-5kb.js + + 5KB body + + 4 tests completed. + + buffer - strong x 92,435 ops/sec ±0.42% (188 runs sampled) + buffer - weak x 92,373 ops/sec ±0.58% (189 runs sampled) + string - strong x 48,850 ops/sec ±0.56% (186 runs sampled) + string - weak x 49,380 ops/sec ±0.56% (190 runs sampled) + +> node benchmark/body3-10kb.js + + 10KB body + + 4 tests completed. + + buffer - strong x 55,989 ops/sec ±0.93% (188 runs sampled) + buffer - weak x 56,148 ops/sec ±0.55% (190 runs sampled) + string - strong x 27,345 ops/sec ±0.43% (188 runs sampled) + string - weak x 27,496 ops/sec ±0.45% (190 runs sampled) + +> node benchmark/body4-100kb.js + + 100KB body + + 4 tests completed. + + buffer - strong x 7,083 ops/sec ±0.22% (190 runs sampled) + buffer - weak x 7,115 ops/sec ±0.26% (191 runs sampled) + string - strong x 3,068 ops/sec ±0.34% (190 runs sampled) + string - weak x 3,096 ops/sec ±0.35% (190 runs sampled) + +> node benchmark/stats.js + + stat + + 4 tests completed. + + real - strong x 871,642 ops/sec ±0.34% (189 runs sampled) + real - weak x 867,613 ops/sec ±0.39% (190 runs sampled) + fake - strong x 401,051 ops/sec ±0.40% (189 runs sampled) + fake - weak x 400,100 ops/sec ±0.47% (188 runs sampled) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/etag.svg +[npm-url]: https://npmjs.org/package/etag +[node-version-image]: https://img.shields.io/node/v/etag.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/etag/master.svg +[travis-url]: https://travis-ci.org/jshttp/etag +[coveralls-image]: https://img.shields.io/coveralls/jshttp/etag/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/etag?branch=master +[downloads-image]: https://img.shields.io/npm/dm/etag.svg +[downloads-url]: https://npmjs.org/package/etag diff --git a/node_modules/etag/index.js b/node_modules/etag/index.js new file mode 100644 index 00000000..2a585c91 --- /dev/null +++ b/node_modules/etag/index.js @@ -0,0 +1,131 @@ +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = etag + +/** + * Module dependencies. + * @private + */ + +var crypto = require('crypto') +var Stats = require('fs').Stats + +/** + * Module variables. + * @private + */ + +var toString = Object.prototype.toString + +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ + +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } + + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) + + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length + + return '"' + len.toString(16) + '-' + hash + '"' +} + +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ + +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } + + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats + + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') + } + + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) + + return weak + ? 'W/' + tag + : tag +} + +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ + +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true + } + + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} + +/** + * Generate a tag for a stat. + * + * @param {object} stat + * @return {string} + * @private + */ + +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) + + return '"' + size + '-' + mtime + '"' +} diff --git a/node_modules/etag/package.json b/node_modules/etag/package.json new file mode 100644 index 00000000..481a2e44 --- /dev/null +++ b/node_modules/etag/package.json @@ -0,0 +1,89 @@ +{ + "_args": [ + [ + "etag@1.8.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "etag@1.8.1", + "_id": "etag@1.8.1", + "_inBundle": false, + "_integrity": "sha1-Qa4u62XvpiJorr/qg6x9eSmbCIc=", + "_location": "/etag", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "etag@1.8.1", + "name": "etag", + "escapedName": "etag", + "rawSpec": "1.8.1", + "saveSpec": null, + "fetchSpec": "1.8.1" + }, + "_requiredBy": [ + "/express", + "/send" + ], + "_resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "_spec": "1.8.1", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/etag/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "David Björklund", + "email": "david.bjorklund@gmail.com" + } + ], + "description": "Create simple HTTP ETags", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "safe-buffer": "5.1.1", + "seedrandom": "2.4.3" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/etag#readme", + "keywords": [ + "etag", + "http", + "res" + ], + "license": "MIT", + "name": "etag", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/etag.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.8.1" +} diff --git a/node_modules/express-graphql/LICENSE b/node_modules/express-graphql/LICENSE new file mode 100644 index 00000000..51ba8841 --- /dev/null +++ b/node_modules/express-graphql/LICENSE @@ -0,0 +1,30 @@ +BSD License + +For GraphQL software + +Copyright (c) 2015-present, Facebook, Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name Facebook nor the names of its contributors may be used to + endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/express-graphql/PATENTS b/node_modules/express-graphql/PATENTS new file mode 100644 index 00000000..953668b0 --- /dev/null +++ b/node_modules/express-graphql/PATENTS @@ -0,0 +1,11 @@ +Additional Grant of Patent Rights Version 2 + +"Software" means the GraphQL software distributed by Facebook, Inc. + +Facebook, Inc. (“Facebook”) hereby grants to each recipient of the Software (“you”) a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (subject to the termination provision below) license under any Necessary Claims, to make, have made, use, sell, offer to sell, import, and otherwise transfer the Software. For avoidance of doubt, no license is granted under Facebook’s rights in any patent claims that are infringed by (i) modifications to the Software made by you or any third party or (ii) the Software in combination with any software or other technology. + +The license granted hereunder will terminate, automatically and without notice, if you (or any of your subsidiaries, corporate affiliates or agents) initiate directly or indirectly, or take a direct financial interest in, any Patent Assertion: (i) against Facebook or any of its subsidiaries or corporate affiliates, (ii) against any party if such Patent Assertion arises in whole or in part from any software, technology, product or service of Facebook or any of its subsidiaries or corporate affiliates, or (iii) against any party relating to the Software. Notwithstanding the foregoing, if Facebook or any of its subsidiaries or corporate affiliates files a lawsuit alleging patent infringement against you in the first instance, and you respond by filing a patent infringement counterclaim in that lawsuit against that party that is unrelated to the Software, the license granted hereunder will not terminate under section (i) of this paragraph due to such counterclaim. + +A “Necessary Claim” is a claim of a patent owned by Facebook that is necessarily infringed by the Software standing alone. + +A “Patent Assertion” is any lawsuit or other action alleging direct, indirect, or contributory infringement or inducement to infringe any patent, including a cross-claim or counterclaim. diff --git a/node_modules/express-graphql/README.md b/node_modules/express-graphql/README.md new file mode 100644 index 00000000..7245d1e5 --- /dev/null +++ b/node_modules/express-graphql/README.md @@ -0,0 +1,303 @@ +GraphQL HTTP Server Middleware +============================== + +[![Build Status](https://travis-ci.org/graphql/express-graphql.svg?branch=master)](https://travis-ci.org/graphql/express-graphql) +[![Coverage Status](https://coveralls.io/repos/graphql/express-graphql/badge.svg?branch=master&service=github)](https://coveralls.io/github/graphql/express-graphql?branch=master) + +Create a GraphQL HTTP server with any HTTP web framework that supports connect styled middleware, including [Connect](https://github.com/senchalabs/connect) itself, [Express](http://expressjs.com) and [Restify](http://restify.com/). + +## Installation + +```sh +npm install --save express-graphql +``` + + +## Simple Setup + +Just mount `express-graphql` as a route handler: + +```js +const express = require('express'); +const graphqlHTTP = require('express-graphql'); + +const app = express(); + +app.use('/graphql', graphqlHTTP({ + schema: MyGraphQLSchema, + graphiql: true +})); + +app.listen(4000); +``` + + +## Setup with Restify + +Use `.get` or `.post` (or both) rather than `.use` to configure your route handler. If you want to show GraphiQL in the browser, set `graphiql: true` on your `.get` handler. + +```js +const restify = require('restify'); +const graphqlHTTP = require('express-graphql'); + +const app = restify.createServer(); + +app.post('/graphql', graphqlHTTP({ + schema: MyGraphQLSchema, + graphiql: false +})); + +app.get('/graphql', graphqlHTTP({ + schema: MyGraphQLSchema, + graphiql: true +})); + +app.listen(4000); +``` + + +## Options + +The `graphqlHTTP` function accepts the following options: + + * **`schema`**: A `GraphQLSchema` instance from [`GraphQL.js`][]. + A `schema` *must* be provided. + + * **`graphiql`**: If `true`, presents [GraphiQL][] when the GraphQL endpoint is + loaded in a browser. We recommend that you set + `graphiql` to `true` when your app is in development, because it's + quite useful. You may or may not want it in production. + + * **`rootValue`**: A value to pass as the `rootValue` to the `graphql()` + function from [`GraphQL.js/src/execute.js`](https://github.com/graphql/graphql-js/blob/master/src/execution/execute.js#L121). + + * **`context`**: A value to pass as the `context` to the `graphql()` + function from [`GraphQL.js/src/execute.js`](https://github.com/graphql/graphql-js/blob/master/src/execution/execute.js#L122). If `context` is not provided, the + `request` object is passed as the context. + + * **`pretty`**: If `true`, any JSON response will be pretty-printed. + + * **`formatError`**: An optional function which will be used to format any + errors produced by fulfilling a GraphQL operation. If no function is + provided, GraphQL's default spec-compliant [`formatError`][] function will be used. + + * **`extensions`**: An optional function for adding additional metadata to the + GraphQL response as a key-value object. The result will be added to + `"extensions"` field in the resulting JSON. This is often a useful place to + add development time metadata such as the runtime of a query or the amount + of resources consumed. This may be an async function. The function is + given one object as an argument: `{ document, variables, operationName, result }`. + + * **`validationRules`**: Optional additional validation rules queries must + satisfy in addition to those defined by the GraphQL spec. + +In addition to an object defining each option, options can also be provided as +a function (or async function) which returns this options object. This function +is provided the arguments `(request, response, graphQLParams)` and is called +after the request has been parsed. + +The `graphQLParams` is provided as the object `{ query, variables, operationName, raw }`. + +```js +app.use('/graphql', graphqlHTTP(async (request, response, graphQLParams) => ({ + schema: MyGraphQLSchema, + rootValue: await someFunctionToGetRootValue(request) + graphiql: true +}))); +``` + + +## HTTP Usage + +Once installed at a path, `express-graphql` will accept requests with +the parameters: + + * **`query`**: A string GraphQL document to be executed. + + * **`variables`**: The runtime values to use for any GraphQL query variables + as a JSON object. + + * **`operationName`**: If the provided `query` contains multiple named + operations, this specifies which operation should be executed. If not + provided, a 400 error will be returned if the `query` contains multiple + named operations. + + * **`raw`**: If the `graphiql` option is enabled and the `raw` parameter is + provided raw JSON will always be returned instead of GraphiQL even when + loaded from a browser. + +GraphQL will first look for each parameter in the URL's query-string: + +``` +/graphql?query=query+getUser($id:ID){user(id:$id){name}}&variables={"id":"4"} +``` + +If not found in the query-string, it will look in the POST request body. + +If a previous middleware has already parsed the POST body, the `request.body` +value will be used. Use [`multer`][] or a similar middleware to add support +for `multipart/form-data` content, which may be useful for GraphQL mutations +involving uploading files. See an [example using multer](https://github.com/graphql/express-graphql/blob/304b24b993c8f16fffff8d23b0fa4088e690874b/src/__tests__/http-test.js#L674-L741). + +If the POST body has not yet been parsed, express-graphql will interpret it +depending on the provided *Content-Type* header. + + * **`application/json`**: the POST body will be parsed as a JSON + object of parameters. + + * **`application/x-www-form-urlencoded`**: this POST body will be + parsed as a url-encoded string of key-value pairs. + + * **`application/graphql`**: The POST body will be parsed as GraphQL + query string, which provides the `query` parameter. + + +## Combining with Other Express Middleware + +By default, the express request is passed as the GraphQL `context`. +Since most express middleware operates by adding extra data to the +request object, this means you can use most express middleware just by inserting it before `graphqlHTTP` is mounted. This covers scenarios such as authenticating the user, handling file uploads, or mounting GraphQL on a dynamic endpoint. + +This example uses [`express-session`][] to provide GraphQL with the currently logged-in session. + +```js +const session = require('express-session'); +const graphqlHTTP = require('express-graphql'); + +const app = express(); + +app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})); + +app.use('/graphql', graphqlHTTP({ + schema: MySessionAwareGraphQLSchema, + graphiql: true +})); +``` + +Then in your type definitions, you can access the request via the third "context" argument in your `resolve` function: + +```js +new GraphQLObjectType({ + name: 'MyType', + fields: { + myField: { + type: GraphQLString, + resolve(parentValue, args, request) { + // use `request.session` here + } + } + } +}); +``` + + +## Providing Extensions + +The GraphQL response allows for adding additional information in a response to +a GraphQL query via a field in the response called `"extensions"`. This is added +by providing an `extensions` function when using `graphqlHTTP`. The function +must return a JSON-serializable Object. + +When called, this is provided an argument which you can use to get information +about the GraphQL request: + +`{ document, variables, operationName, result }` + +This example illustrates adding the amount of time consumed by running the +provided query, which could perhaps be used by your development tools. + +```js +const graphqlHTTP = require('express-graphql'); + +const app = express(); + +app.use(session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})); + +app.use('/graphql', graphqlHTTP(request => { + const startTime = Date.now(); + return { + schema: MyGraphQLSchema, + graphiql: true, + extensions({ document, variables, operationName, result }) { + return { runTime: Date.now() - startTime }; + } + }; +})); +``` + +When querying this endpoint, it would include this information in the result, +for example: + +```js +{ + "data": { ... } + "extensions": { + "runTime": 135 + } +} +``` + + +## Additional Validation Rules + +GraphQL's [validation phase](https://facebook.github.io/graphql/#sec-Validation) checks the query to ensure that it can be successfully executed against the schema. The `validationRules` option allows for additional rules to be run during this phase. Rules are applied to each node in an AST representing the query using the Visitor pattern. + +A validation rule is a function which returns a visitor for one or more node Types. Below is an example of a validation preventing the specific fieldname `metadata` from being queried. For more examples see the [`specifiedRules`](https://github.com/graphql/graphql-js/tree/master/src/validation/rules) in the [graphql-js](https://github.com/graphql/graphql-js) package. + +```js +import { GraphQLError } from 'graphql'; + +export function DisallowMetadataQueries(context) { + return { + Field(node) { + const fieldName = node.name.value; + + if (fieldName === "metadata") { + context.reportError( + new GraphQLError( + `Validation: Requesting the field ${fieldName} is not allowed`, + ), + ); + } + } + }; +} +``` + +## Other Exports + +**`getGraphQLParams(request: Request): Promise`** + +Given an HTTP Request, this returns a Promise for the parameters relevant to +running a GraphQL request. This function is used internally to handle the +incoming request, you may use it directly for building other similar services. + +```js +const graphqlHTTP = require('express-graphql'); + +graphqlHTTP.getGraphQLParams(request).then(params => { + // do something... +}) +``` + + +## Debugging Tips + +During development, it's useful to get more information from errors, such as +stack traces. Providing a function to `formatError` enables this: + +```js +formatError: error => ({ + message: error.message, + locations: error.locations, + stack: error.stack ? error.stack.split('\n') : [], + path: error.path +}) +``` + + +[`GraphQL.js`]: https://github.com/graphql/graphql-js +[`formatError`]: https://github.com/graphql/graphql-js/blob/master/src/error/formatError.js +[GraphiQL]: https://github.com/graphql/graphiql +[`multer`]: https://github.com/expressjs/multer +[`express-session`]: https://github.com/expressjs/session diff --git a/node_modules/express-graphql/dist/index.js b/node_modules/express-graphql/dist/index.js new file mode 100644 index 00000000..16fdbd98 --- /dev/null +++ b/node_modules/express-graphql/dist/index.js @@ -0,0 +1,299 @@ +'use strict'; + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * strict + */ + +var _accepts = require('accepts'); + +var _accepts2 = _interopRequireDefault(_accepts); + +var _graphql = require('graphql'); + +var _httpErrors = require('http-errors'); + +var _httpErrors2 = _interopRequireDefault(_httpErrors); + +var _url = require('url'); + +var _url2 = _interopRequireDefault(_url); + +var _parseBody = require('./parseBody'); + +var _renderGraphiQL = require('./renderGraphiQL'); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Middleware for express; takes an options object or function as input to + * configure behavior, and returns an express middleware. + */ + + +/** + * Used to configure the graphqlHTTP middleware by providing a schema + * and other configuration options. + * + * Options can be provided as an Object, a Promise for an Object, or a Function + * that returns an Object or a Promise for an Object. + */ + + +/** + * All information about a GraphQL request. + */ +module.exports = graphqlHTTP; +function graphqlHTTP(options) { + if (!options) { + throw new Error('GraphQL middleware requires options.'); + } + + return function graphqlMiddleware(request, response) { + // Higher scoped variables are referred to at various stages in the + // asynchronous state machine below. + var params = void 0; + var pretty = void 0; + var formatErrorFn = void 0; + var extensionsFn = void 0; + var showGraphiQL = void 0; + var query = void 0; + + var documentAST = void 0; + var variables = void 0; + var operationName = void 0; + + // Promises are used as a mechanism for capturing any thrown errors during + // the asynchronous process below. + + // Parse the Request to get GraphQL request parameters. + return getGraphQLParams(request).then(function (graphQLParams) { + params = graphQLParams; + // Then, resolve the Options to get OptionsData. + return typeof options === 'function' ? options(request, response, params) : options; + }).then(function (optionsData) { + // Assert that optionsData is in fact an Object. + if (!optionsData || (typeof optionsData === 'undefined' ? 'undefined' : _typeof(optionsData)) !== 'object') { + throw new Error('GraphQL middleware option function must return an options object ' + 'or a promise which will be resolved to an options object.'); + } + + // Assert that schema is required. + if (!optionsData.schema) { + throw new Error('GraphQL middleware options must contain a schema.'); + } + + // Collect information from the options data object. + var schema = optionsData.schema; + var context = optionsData.context || request; + var rootValue = optionsData.rootValue; + var graphiql = optionsData.graphiql; + pretty = optionsData.pretty; + formatErrorFn = optionsData.formatError; + extensionsFn = optionsData.extensions; + + var validationRules = _graphql.specifiedRules; + if (optionsData.validationRules) { + validationRules = validationRules.concat(optionsData.validationRules); + } + + // GraphQL HTTP only supports GET and POST methods. + if (request.method !== 'GET' && request.method !== 'POST') { + response.setHeader('Allow', 'GET, POST'); + throw (0, _httpErrors2.default)(405, 'GraphQL only supports GET and POST requests.'); + } + + // Get GraphQL params from the request and POST body data. + query = params.query; + variables = params.variables; + operationName = params.operationName; + showGraphiQL = graphiql && canDisplayGraphiQL(request, params); + + // If there is no query, but GraphiQL will be displayed, do not produce + // a result, otherwise return a 400: Bad Request. + if (!query) { + if (showGraphiQL) { + return null; + } + throw (0, _httpErrors2.default)(400, 'Must provide query string.'); + } + + // GraphQL source. + var source = new _graphql.Source(query, 'GraphQL request'); + + // Parse source to AST, reporting any syntax error. + try { + documentAST = (0, _graphql.parse)(source); + } catch (syntaxError) { + // Return 400: Bad Request if any syntax errors errors exist. + response.statusCode = 400; + return { errors: [syntaxError] }; + } + + // Validate AST, reporting any errors. + var validationErrors = (0, _graphql.validate)(schema, documentAST, validationRules); + if (validationErrors.length > 0) { + // Return 400: Bad Request if any validation errors exist. + response.statusCode = 400; + return { errors: validationErrors }; + } + + // Only query operations are allowed on GET requests. + if (request.method === 'GET') { + // Determine if this GET request will perform a non-query. + var operationAST = (0, _graphql.getOperationAST)(documentAST, operationName); + if (operationAST && operationAST.operation !== 'query') { + // If GraphiQL can be shown, do not perform this query, but + // provide it to GraphiQL so that the requester may perform it + // themselves if desired. + if (showGraphiQL) { + return null; + } + + // Otherwise, report a 405: Method Not Allowed error. + response.setHeader('Allow', 'POST'); + throw (0, _httpErrors2.default)(405, 'Can only perform a ' + operationAST.operation + ' operation ' + 'from a POST request.'); + } + } + // Perform the execution, reporting any errors creating the context. + try { + return (0, _graphql.execute)(schema, documentAST, rootValue, context, variables, operationName); + } catch (contextError) { + // Return 400: Bad Request if any execution context errors exist. + response.statusCode = 400; + return { errors: [contextError] }; + } + }).then(function (result) { + // Collect and apply any metadata extensions if a function was provided. + // http://facebook.github.io/graphql/#sec-Response-Format + if (result && extensionsFn) { + return Promise.resolve(extensionsFn({ + document: documentAST, + variables: variables, + operationName: operationName, + result: result + })).then(function (extensions) { + if (extensions && (typeof extensions === 'undefined' ? 'undefined' : _typeof(extensions)) === 'object') { + result.extensions = extensions; + } + return result; + }); + } + return result; + }).catch(function (error) { + // If an error was caught, report the httpError status, or 500. + response.statusCode = error.status || 500; + return { errors: [error] }; + }).then(function (result) { + // If no data was included in the result, that indicates a runtime query + // error, indicate as such with a generic status code. + // Note: Information about the error itself will still be contained in + // the resulting JSON payload. + // http://facebook.github.io/graphql/#sec-Data + if (response.statusCode === 200 && result && !result.data) { + response.statusCode = 500; + } + // Format any encountered errors. + if (result && result.errors) { + result.errors = result.errors.map(formatErrorFn || _graphql.formatError); + } + + // If allowed to show GraphiQL, present it instead of JSON. + if (showGraphiQL) { + var payload = (0, _renderGraphiQL.renderGraphiQL)({ + query: query, + variables: variables, + operationName: operationName, + result: result + }); + return sendResponse(response, 'text/html', payload); + } + + // At this point, result is guaranteed to exist, as the only scenario + // where it will not is when showGraphiQL is true. + if (!result) { + throw (0, _httpErrors2.default)(500, 'Internal Error'); + } + + // If "pretty" JSON isn't requested, and the server provides a + // response.json method (express), use that directly. + // Otherwise use the simplified sendResponse method. + if (!pretty && typeof response.json === 'function') { + response.json(result); + } else { + var _payload = JSON.stringify(result, null, pretty ? 2 : 0); + sendResponse(response, 'application/json', _payload); + } + }); + }; +} + +/** + * Provided a "Request" provided by express or connect (typically a node style + * HTTPClientRequest), Promise the GraphQL request parameters. + */ +module.exports.getGraphQLParams = getGraphQLParams; +function getGraphQLParams(request) { + return (0, _parseBody.parseBody)(request).then(function (bodyData) { + var urlData = request.url && _url2.default.parse(request.url, true).query || {}; + return parseGraphQLParams(urlData, bodyData); + }); +} + +/** + * Helper function to get the GraphQL params from the request. + */ +function parseGraphQLParams(urlData, bodyData) { + // GraphQL Query string. + var query = urlData.query || bodyData.query; + if (typeof query !== 'string') { + query = null; + } + + // Parse the variables if needed. + var variables = urlData.variables || bodyData.variables; + if (variables && typeof variables === 'string') { + try { + variables = JSON.parse(variables); + } catch (error) { + throw (0, _httpErrors2.default)(400, 'Variables are invalid JSON.'); + } + } else if ((typeof variables === 'undefined' ? 'undefined' : _typeof(variables)) !== 'object') { + variables = null; + } + + // Name of GraphQL operation to execute. + var operationName = urlData.operationName || bodyData.operationName; + if (typeof operationName !== 'string') { + operationName = null; + } + + var raw = urlData.raw !== undefined || bodyData.raw !== undefined; + + return { query: query, variables: variables, operationName: operationName, raw: raw }; +} + +/** + * Helper function to determine if GraphiQL can be displayed. + */ +function canDisplayGraphiQL(request, params) { + // If `raw` exists, GraphiQL mode is not enabled. + // Allowed to show GraphiQL if not requested as raw and this request + // prefers HTML over JSON. + return !params.raw && (0, _accepts2.default)(request).types(['json', 'html']) === 'html'; +} + +/** + * Helper function for sending a response using only the core Node server APIs. + */ +function sendResponse(response, type, data) { + var chunk = new Buffer(data, 'utf8'); + response.setHeader('Content-Type', type + '; charset=utf-8'); + response.setHeader('Content-Length', String(chunk.length)); + response.end(chunk); +} \ No newline at end of file diff --git a/node_modules/express-graphql/dist/index.js.flow b/node_modules/express-graphql/dist/index.js.flow new file mode 100644 index 00000000..5ff14242 --- /dev/null +++ b/node_modules/express-graphql/dist/index.js.flow @@ -0,0 +1,411 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @flow strict + */ + +import accepts from 'accepts'; +import { + Source, + parse, + validate, + execute, + formatError, + getOperationAST, + specifiedRules, +} from 'graphql'; +import httpError from 'http-errors'; +import url from 'url'; + +import { parseBody } from './parseBody'; +import { renderGraphiQL } from './renderGraphiQL'; + +import type { DocumentNode, GraphQLError, GraphQLSchema } from 'graphql'; +import type { $Request, $Response } from 'express'; + +/** + * Used to configure the graphqlHTTP middleware by providing a schema + * and other configuration options. + * + * Options can be provided as an Object, a Promise for an Object, or a Function + * that returns an Object or a Promise for an Object. + */ +export type Options = + | (( + request: $Request, + response: $Response, + params?: GraphQLParams, + ) => OptionsResult) + | OptionsResult; +export type OptionsResult = OptionsData | Promise; +export type OptionsData = { + /** + * A GraphQL schema from graphql-js. + */ + schema: GraphQLSchema, + + /** + * A value to pass as the context to the graphql() function. + */ + context?: ?mixed, + + /** + * An object to pass as the rootValue to the graphql() function. + */ + rootValue?: ?mixed, + + /** + * A boolean to configure whether the output should be pretty-printed. + */ + pretty?: ?boolean, + + /** + * An optional function which will be used to format any errors produced by + * fulfilling a GraphQL operation. If no function is provided, GraphQL's + * default spec-compliant `formatError` function will be used. + */ + formatError?: ?(error: GraphQLError) => mixed, + + /** + * An optional array of validation rules that will be applied on the document + * in additional to those defined by the GraphQL spec. + */ + validationRules?: ?Array, + + /** + * An optional function for adding additional metadata to the GraphQL response + * as a key-value object. The result will be added to "extensions" field in + * the resulting JSON. This is often a useful place to add development time + * info such as the runtime of a query or the amount of resources consumed. + * + * Information about the request is provided to be used. + * + * This function may be async. + */ + extensions?: ?(info: RequestInfo) => { [key: string]: mixed }, + + /** + * A boolean to optionally enable GraphiQL mode. + */ + graphiql?: ?boolean, +}; + +/** + * All information about a GraphQL request. + */ +export type RequestInfo = { + /** + * The parsed GraphQL document. + */ + document: ?DocumentNode, + + /** + * The variable values used at runtime. + */ + variables: ?{ [name: string]: mixed }, + + /** + * The (optional) operation name requested. + */ + operationName: ?string, + + /** + * The result of executing the operation. + */ + result: ?mixed, +}; + +type Middleware = (request: $Request, response: $Response) => Promise; + +/** + * Middleware for express; takes an options object or function as input to + * configure behavior, and returns an express middleware. + */ +module.exports = graphqlHTTP; +function graphqlHTTP(options: Options): Middleware { + if (!options) { + throw new Error('GraphQL middleware requires options.'); + } + + return function graphqlMiddleware(request: $Request, response: $Response) { + // Higher scoped variables are referred to at various stages in the + // asynchronous state machine below. + let params; + let pretty; + let formatErrorFn; + let extensionsFn; + let showGraphiQL; + let query; + + let documentAST; + let variables; + let operationName; + + // Promises are used as a mechanism for capturing any thrown errors during + // the asynchronous process below. + + // Parse the Request to get GraphQL request parameters. + return getGraphQLParams(request) + .then(graphQLParams => { + params = graphQLParams; + // Then, resolve the Options to get OptionsData. + return typeof options === 'function' + ? options(request, response, params) + : options; + }) + .then(optionsData => { + // Assert that optionsData is in fact an Object. + if (!optionsData || typeof optionsData !== 'object') { + throw new Error( + 'GraphQL middleware option function must return an options object ' + + 'or a promise which will be resolved to an options object.', + ); + } + + // Assert that schema is required. + if (!optionsData.schema) { + throw new Error('GraphQL middleware options must contain a schema.'); + } + + // Collect information from the options data object. + const schema = optionsData.schema; + const context = optionsData.context || request; + const rootValue = optionsData.rootValue; + const graphiql = optionsData.graphiql; + pretty = optionsData.pretty; + formatErrorFn = optionsData.formatError; + extensionsFn = optionsData.extensions; + + let validationRules = specifiedRules; + if (optionsData.validationRules) { + validationRules = validationRules.concat(optionsData.validationRules); + } + + // GraphQL HTTP only supports GET and POST methods. + if (request.method !== 'GET' && request.method !== 'POST') { + response.setHeader('Allow', 'GET, POST'); + throw httpError(405, 'GraphQL only supports GET and POST requests.'); + } + + // Get GraphQL params from the request and POST body data. + query = params.query; + variables = params.variables; + operationName = params.operationName; + showGraphiQL = graphiql && canDisplayGraphiQL(request, params); + + // If there is no query, but GraphiQL will be displayed, do not produce + // a result, otherwise return a 400: Bad Request. + if (!query) { + if (showGraphiQL) { + return null; + } + throw httpError(400, 'Must provide query string.'); + } + + // GraphQL source. + const source = new Source(query, 'GraphQL request'); + + // Parse source to AST, reporting any syntax error. + try { + documentAST = parse(source); + } catch (syntaxError) { + // Return 400: Bad Request if any syntax errors errors exist. + response.statusCode = 400; + return { errors: [syntaxError] }; + } + + // Validate AST, reporting any errors. + const validationErrors = validate(schema, documentAST, validationRules); + if (validationErrors.length > 0) { + // Return 400: Bad Request if any validation errors exist. + response.statusCode = 400; + return { errors: validationErrors }; + } + + // Only query operations are allowed on GET requests. + if (request.method === 'GET') { + // Determine if this GET request will perform a non-query. + const operationAST = getOperationAST(documentAST, operationName); + if (operationAST && operationAST.operation !== 'query') { + // If GraphiQL can be shown, do not perform this query, but + // provide it to GraphiQL so that the requester may perform it + // themselves if desired. + if (showGraphiQL) { + return null; + } + + // Otherwise, report a 405: Method Not Allowed error. + response.setHeader('Allow', 'POST'); + throw httpError( + 405, + `Can only perform a ${operationAST.operation} operation ` + + 'from a POST request.', + ); + } + } + // Perform the execution, reporting any errors creating the context. + try { + return execute( + schema, + documentAST, + rootValue, + context, + variables, + operationName, + ); + } catch (contextError) { + // Return 400: Bad Request if any execution context errors exist. + response.statusCode = 400; + return { errors: [contextError] }; + } + }) + .then(result => { + // Collect and apply any metadata extensions if a function was provided. + // http://facebook.github.io/graphql/#sec-Response-Format + if (result && extensionsFn) { + return Promise.resolve( + extensionsFn({ + document: documentAST, + variables, + operationName, + result, + }), + ).then(extensions => { + if (extensions && typeof extensions === 'object') { + (result: any).extensions = extensions; + } + return result; + }); + } + return result; + }) + .catch(error => { + // If an error was caught, report the httpError status, or 500. + response.statusCode = error.status || 500; + return { errors: [error] }; + }) + .then(result => { + // If no data was included in the result, that indicates a runtime query + // error, indicate as such with a generic status code. + // Note: Information about the error itself will still be contained in + // the resulting JSON payload. + // http://facebook.github.io/graphql/#sec-Data + if (response.statusCode === 200 && result && !result.data) { + response.statusCode = 500; + } + // Format any encountered errors. + if (result && result.errors) { + (result: any).errors = result.errors.map( + formatErrorFn || formatError, + ); + } + + // If allowed to show GraphiQL, present it instead of JSON. + if (showGraphiQL) { + const payload = renderGraphiQL({ + query, + variables, + operationName, + result, + }); + return sendResponse(response, 'text/html', payload); + } + + // At this point, result is guaranteed to exist, as the only scenario + // where it will not is when showGraphiQL is true. + if (!result) { + throw httpError(500, 'Internal Error'); + } + + // If "pretty" JSON isn't requested, and the server provides a + // response.json method (express), use that directly. + // Otherwise use the simplified sendResponse method. + if (!pretty && typeof response.json === 'function') { + response.json(result); + } else { + const payload = JSON.stringify(result, null, pretty ? 2 : 0); + sendResponse(response, 'application/json', payload); + } + }); + }; +} + +export type GraphQLParams = { + query: ?string, + variables: ?{ [name: string]: mixed }, + operationName: ?string, + raw: ?boolean, +}; + +/** + * Provided a "Request" provided by express or connect (typically a node style + * HTTPClientRequest), Promise the GraphQL request parameters. + */ +module.exports.getGraphQLParams = getGraphQLParams; +function getGraphQLParams(request: $Request): Promise { + return parseBody(request).then(bodyData => { + const urlData = (request.url && url.parse(request.url, true).query) || {}; + return parseGraphQLParams(urlData, bodyData); + }); +} + +/** + * Helper function to get the GraphQL params from the request. + */ +function parseGraphQLParams( + urlData: { [param: string]: mixed }, + bodyData: { [param: string]: mixed }, +): GraphQLParams { + // GraphQL Query string. + let query = urlData.query || bodyData.query; + if (typeof query !== 'string') { + query = null; + } + + // Parse the variables if needed. + let variables = urlData.variables || bodyData.variables; + if (variables && typeof variables === 'string') { + try { + variables = JSON.parse(variables); + } catch (error) { + throw httpError(400, 'Variables are invalid JSON.'); + } + } else if (typeof variables !== 'object') { + variables = null; + } + + // Name of GraphQL operation to execute. + let operationName = urlData.operationName || bodyData.operationName; + if (typeof operationName !== 'string') { + operationName = null; + } + + const raw = urlData.raw !== undefined || bodyData.raw !== undefined; + + return { query, variables, operationName, raw }; +} + +/** + * Helper function to determine if GraphiQL can be displayed. + */ +function canDisplayGraphiQL(request: $Request, params: GraphQLParams): boolean { + // If `raw` exists, GraphiQL mode is not enabled. + // Allowed to show GraphiQL if not requested as raw and this request + // prefers HTML over JSON. + return !params.raw && accepts(request).types(['json', 'html']) === 'html'; +} + +/** + * Helper function for sending a response using only the core Node server APIs. + */ +function sendResponse(response: $Response, type: string, data: string): void { + const chunk = new Buffer(data, 'utf8'); + response.setHeader('Content-Type', type + '; charset=utf-8'); + response.setHeader('Content-Length', String(chunk.length)); + response.end(chunk); +} diff --git a/node_modules/express-graphql/dist/parseBody.js b/node_modules/express-graphql/dist/parseBody.js new file mode 100644 index 00000000..60ae15d9 --- /dev/null +++ b/node_modules/express-graphql/dist/parseBody.js @@ -0,0 +1,162 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * strict + */ + +exports.parseBody = parseBody; + +var _contentType = require('content-type'); + +var _contentType2 = _interopRequireDefault(_contentType); + +var _rawBody = require('raw-body'); + +var _rawBody2 = _interopRequireDefault(_rawBody); + +var _httpErrors = require('http-errors'); + +var _httpErrors2 = _interopRequireDefault(_httpErrors); + +var _querystring = require('querystring'); + +var _querystring2 = _interopRequireDefault(_querystring); + +var _zlib = require('zlib'); + +var _zlib2 = _interopRequireDefault(_zlib); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Provided a "Request" provided by express or connect (typically a node style + * HTTPClientRequest), Promise the body data contained. + */ +function parseBody(req) { + return new Promise(function (resolve, reject) { + var body = req.body; + + // If express has already parsed a body as a keyed object, use it. + if ((typeof body === 'undefined' ? 'undefined' : _typeof(body)) === 'object' && !(body instanceof Buffer)) { + return resolve(body); + } + + // Skip requests without content types. + if (req.headers['content-type'] === undefined) { + return resolve({}); + } + + var typeInfo = _contentType2.default.parse(req); + + // If express has already parsed a body as a string, and the content-type + // was application/graphql, parse the string body. + if (typeof body === 'string' && typeInfo.type === 'application/graphql') { + return resolve(graphqlParser(body)); + } + + // Already parsed body we didn't recognise? Parse nothing. + if (body) { + return resolve({}); + } + + // Use the correct body parser based on Content-Type header. + switch (typeInfo.type) { + case 'application/graphql': + return read(req, typeInfo, graphqlParser, resolve, reject); + case 'application/json': + return read(req, typeInfo, jsonEncodedParser, resolve, reject); + case 'application/x-www-form-urlencoded': + return read(req, typeInfo, urlEncodedParser, resolve, reject); + } + + // If no Content-Type header matches, parse nothing. + return resolve({}); + }); +} + +function jsonEncodedParser(body) { + if (jsonObjRegex.test(body)) { + /* eslint-disable no-empty */ + try { + return JSON.parse(body); + } catch (error) {} + // Do nothing + + /* eslint-enable no-empty */ + } + throw (0, _httpErrors2.default)(400, 'POST body sent invalid JSON.'); +} + +function urlEncodedParser(body) { + return _querystring2.default.parse(body); +} + +function graphqlParser(body) { + return { query: body }; +} + +/** + * RegExp to match an Object-opening brace "{" as the first non-space + * in a string. Allowed whitespace is defined in RFC 7159: + * + * x20 Space + * x09 Horizontal tab + * x0A Line feed or New line + * x0D Carriage return + */ +var jsonObjRegex = /^[\x20\x09\x0a\x0d]*\{/; + +// Read and parse a request body. +function read(req, typeInfo, parseFn, resolve, reject) { + var charset = (typeInfo.parameters.charset || 'utf-8').toLowerCase(); + + // Assert charset encoding per JSON RFC 7159 sec 8.1 + if (charset.slice(0, 4) !== 'utf-') { + throw (0, _httpErrors2.default)(415, 'Unsupported charset "' + charset.toUpperCase() + '".'); + } + + // Get content-encoding (e.g. gzip) + var contentEncoding = req.headers['content-encoding']; + var encoding = typeof contentEncoding === 'string' ? contentEncoding.toLowerCase() : 'identity'; + var length = encoding === 'identity' ? req.headers['content-length'] : null; + var limit = 100 * 1024; // 100kb + var stream = decompressed(req, encoding); + + // Read body from stream. + (0, _rawBody2.default)(stream, { encoding: charset, length: length, limit: limit }, function (err, body) { + if (err) { + return reject(err.type === 'encoding.unsupported' ? (0, _httpErrors2.default)(415, 'Unsupported charset "' + charset.toUpperCase() + '".') : (0, _httpErrors2.default)(400, 'Invalid body: ' + err.message + '.')); + } + + try { + // Decode and parse body. + return resolve(parseFn(body)); + } catch (error) { + return reject(error); + } + }); +} + +// Return a decompressed stream, given an encoding. +function decompressed(req, encoding) { + switch (encoding) { + case 'identity': + return req; + case 'deflate': + return req.pipe(_zlib2.default.createInflate()); + case 'gzip': + return req.pipe(_zlib2.default.createGunzip()); + } + throw (0, _httpErrors2.default)(415, 'Unsupported content-encoding "' + encoding + '".'); +} \ No newline at end of file diff --git a/node_modules/express-graphql/dist/parseBody.js.flow b/node_modules/express-graphql/dist/parseBody.js.flow new file mode 100644 index 00000000..0cd87262 --- /dev/null +++ b/node_modules/express-graphql/dist/parseBody.js.flow @@ -0,0 +1,147 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @flow strict + */ + +import contentType from 'content-type'; +import getBody from 'raw-body'; +import httpError from 'http-errors'; +import querystring from 'querystring'; +import zlib from 'zlib'; + +import type { $Request } from 'express'; + +/** + * Provided a "Request" provided by express or connect (typically a node style + * HTTPClientRequest), Promise the body data contained. + */ +export function parseBody(req: $Request): Promise<{ [param: string]: mixed }> { + return new Promise((resolve, reject) => { + const body = req.body; + + // If express has already parsed a body as a keyed object, use it. + if (typeof body === 'object' && !(body instanceof Buffer)) { + return resolve((body: any)); + } + + // Skip requests without content types. + if (req.headers['content-type'] === undefined) { + return resolve({}); + } + + const typeInfo = contentType.parse(req); + + // If express has already parsed a body as a string, and the content-type + // was application/graphql, parse the string body. + if (typeof body === 'string' && typeInfo.type === 'application/graphql') { + return resolve(graphqlParser(body)); + } + + // Already parsed body we didn't recognise? Parse nothing. + if (body) { + return resolve({}); + } + + // Use the correct body parser based on Content-Type header. + switch (typeInfo.type) { + case 'application/graphql': + return read(req, typeInfo, graphqlParser, resolve, reject); + case 'application/json': + return read(req, typeInfo, jsonEncodedParser, resolve, reject); + case 'application/x-www-form-urlencoded': + return read(req, typeInfo, urlEncodedParser, resolve, reject); + } + + // If no Content-Type header matches, parse nothing. + return resolve({}); + }); +} + +function jsonEncodedParser(body) { + if (jsonObjRegex.test(body)) { + /* eslint-disable no-empty */ + try { + return JSON.parse(body); + } catch (error) { + // Do nothing + } + /* eslint-enable no-empty */ + } + throw httpError(400, 'POST body sent invalid JSON.'); +} + +function urlEncodedParser(body) { + return querystring.parse(body); +} + +function graphqlParser(body) { + return { query: body }; +} + +/** + * RegExp to match an Object-opening brace "{" as the first non-space + * in a string. Allowed whitespace is defined in RFC 7159: + * + * x20 Space + * x09 Horizontal tab + * x0A Line feed or New line + * x0D Carriage return + */ +const jsonObjRegex = /^[\x20\x09\x0a\x0d]*\{/; + +// Read and parse a request body. +function read(req, typeInfo, parseFn, resolve, reject) { + const charset = (typeInfo.parameters.charset || 'utf-8').toLowerCase(); + + // Assert charset encoding per JSON RFC 7159 sec 8.1 + if (charset.slice(0, 4) !== 'utf-') { + throw httpError(415, `Unsupported charset "${charset.toUpperCase()}".`); + } + + // Get content-encoding (e.g. gzip) + const contentEncoding = req.headers['content-encoding']; + const encoding = + typeof contentEncoding === 'string' + ? contentEncoding.toLowerCase() + : 'identity'; + const length = encoding === 'identity' ? req.headers['content-length'] : null; + const limit = 100 * 1024; // 100kb + const stream = decompressed(req, encoding); + + // Read body from stream. + getBody(stream, { encoding: charset, length, limit }, (err, body) => { + if (err) { + return reject( + err.type === 'encoding.unsupported' + ? httpError(415, `Unsupported charset "${charset.toUpperCase()}".`) + : httpError(400, `Invalid body: ${err.message}.`), + ); + } + + try { + // Decode and parse body. + return resolve(parseFn(body)); + } catch (error) { + return reject(error); + } + }); +} + +// Return a decompressed stream, given an encoding. +function decompressed(req, encoding) { + switch (encoding) { + case 'identity': + return req; + case 'deflate': + return req.pipe(zlib.createInflate()); + case 'gzip': + return req.pipe(zlib.createGunzip()); + } + throw httpError(415, `Unsupported content-encoding "${encoding}".`); +} diff --git a/node_modules/express-graphql/dist/renderGraphiQL.js b/node_modules/express-graphql/dist/renderGraphiQL.js new file mode 100644 index 00000000..a5916801 --- /dev/null +++ b/node_modules/express-graphql/dist/renderGraphiQL.js @@ -0,0 +1,42 @@ +'use strict'; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.renderGraphiQL = renderGraphiQL; + + +// Current latest version of GraphiQL. +var GRAPHIQL_VERSION = '0.11.11'; + +// Ensures string values are safe to be used within a \n \n \n \n \n\n\n
Loading...
\n \n\n'; +} \ No newline at end of file diff --git a/node_modules/express-graphql/dist/renderGraphiQL.js.flow b/node_modules/express-graphql/dist/renderGraphiQL.js.flow new file mode 100644 index 00000000..bbed4cc2 --- /dev/null +++ b/node_modules/express-graphql/dist/renderGraphiQL.js.flow @@ -0,0 +1,174 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @flow strict + */ + +type GraphiQLData = { + query: ?string, + variables: ?{ [name: string]: mixed }, + operationName: ?string, + result?: mixed, +}; + +// Current latest version of GraphiQL. +const GRAPHIQL_VERSION = '0.11.11'; + +// Ensures string values are safe to be used within a + + + + + + +
Loading...
+ + +`; +} diff --git a/node_modules/express-graphql/package.json b/node_modules/express-graphql/package.json new file mode 100644 index 00000000..dd57e3f7 --- /dev/null +++ b/node_modules/express-graphql/package.json @@ -0,0 +1,127 @@ +{ + "_args": [ + [ + "express-graphql@0.6.12", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "express-graphql@0.6.12", + "_id": "express-graphql@0.6.12", + "_inBundle": false, + "_integrity": "sha512-ouLWV0hRw4hnaLtXzzwhdC79ewxKbY2PRvm05mPc/zOH5W5WVCHDQ1SmNxEPBQdUeeSNh29aIqW9zEQkA3kMuA==", + "_location": "/express-graphql", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "express-graphql@0.6.12", + "name": "express-graphql", + "escapedName": "express-graphql", + "rawSpec": "0.6.12", + "saveSpec": null, + "fetchSpec": "0.6.12" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "http://registry.npmjs.org/express-graphql/-/express-graphql-0.6.12.tgz", + "_spec": "0.6.12", + "_where": "C:\\GitHub\\cis411_lab0", + "babel": { + "presets": [ + "es2015" + ], + "plugins": [ + "transform-class-properties", + "transform-flow-strip-types" + ] + }, + "bugs": { + "url": "https://github.com/graphql/express-graphql/issues" + }, + "dependencies": { + "accepts": "^1.3.0", + "content-type": "^1.0.4", + "http-errors": "^1.3.0", + "raw-body": "^2.3.2" + }, + "description": "Production ready GraphQL HTTP middleware.", + "devDependencies": { + "babel-cli": "^6.26.0", + "babel-eslint": "^8.2.1", + "babel-plugin-transform-async-to-generator": "6.24.1", + "babel-plugin-transform-class-properties": "6.24.1", + "babel-plugin-transform-flow-strip-types": "6.22.0", + "babel-plugin-transform-runtime": "^6.23.0", + "babel-preset-es2015": "6.24.1", + "babel-register": "^6.26.0", + "babel-runtime": "^6.26.0", + "body-parser": "1.18.2", + "chai": "^4.1.2", + "connect": "3.6.6", + "coveralls": "3.0.0", + "eslint": "^4.18.0", + "eslint-plugin-flowtype": "^2.44.0", + "express": "^4.16.2", + "express3": "*", + "flow-bin": "^0.65.0", + "graphql": "^0.13.1", + "isparta": "4.0.0", + "mocha": "5.0.1", + "multer": "1.3.0", + "prettier": "^1.10.2", + "restify": "4.3.2", + "sane": "2.4.1", + "sinon": "^4.3.0", + "supertest": "3.0.0" + }, + "directories": { + "lib": "./dist" + }, + "files": [ + "dist", + "README.md", + "LICENSE", + "PATENTS" + ], + "homepage": "https://github.com/graphql/express-graphql#readme", + "keywords": [ + "express", + "restify", + "connect", + "http", + "graphql", + "middleware", + "api" + ], + "license": "BSD-3-Clause", + "main": "dist/index.js", + "name": "express-graphql", + "options": { + "mocha": "--require resources/mocha-bootload src/**/__tests__/**/*.js" + }, + "peerDependencies": { + "graphql": "^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/graphql/express-graphql.git" + }, + "scripts": { + "build": "rm -rf dist/* && babel src --ignore __tests__ --out-dir dist && npm run build:flow", + "build:flow": "find ./src -name '*.js' -not -path '*/__tests__*' | while read filepath; do cp $filepath `echo $filepath | sed 's/\\/src\\//\\/dist\\//g'`.flow; done", + "check": "flow check", + "cover": "babel-node node_modules/.bin/isparta cover --root src --report html node_modules/.bin/_mocha -- $npm_package_options_mocha", + "cover:lcov": "babel-node node_modules/.bin/isparta cover --root src --report lcovonly node_modules/.bin/_mocha -- $npm_package_options_mocha", + "lint": "eslint src", + "prepublish": ". ./resources/prepublish.sh", + "pretty": "node resources/pretty.js", + "pretty-check": "node resources/pretty.js --check", + "preversion": "npm test", + "start": "babel-node examples/index.js", + "test": "npm run lint && npm run pretty-check && npm run check && npm run testonly", + "testonly": "mocha $npm_package_options_mocha", + "watch": "node resources/watch.js" + }, + "version": "0.6.12" +} diff --git a/node_modules/express/History.md b/node_modules/express/History.md new file mode 100644 index 00000000..e02fcd5b --- /dev/null +++ b/node_modules/express/History.md @@ -0,0 +1,3402 @@ +4.16.3 / 2018-03-12 +=================== + + * deps: accepts@~1.3.5 + - deps: mime-types@~2.1.18 + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: finalhandler@1.1.1 + - Fix 404 output for bad / missing pathnames + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: proxy-addr@~2.0.3 + - deps: ipaddr.js@1.6.0 + * deps: send@0.16.2 + - Fix incorrect end tag in default error & redirects + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + * deps: serve-static@1.13.2 + - Fix incorrect end tag in redirects + - deps: encodeurl@~1.0.2 + - deps: send@0.16.2 + * deps: statuses@~1.4.0 + * deps: type-is@~1.6.16 + - deps: mime-types@~2.1.18 + +4.16.2 / 2017-10-09 +=================== + + * Fix `TypeError` in `res.send` when given `Buffer` and `ETag` header set + * perf: skip parsing of entire `X-Forwarded-Proto` header + +4.16.1 / 2017-09-29 +=================== + + * deps: send@0.16.1 + * deps: serve-static@1.13.1 + - Fix regression when `root` is incorrectly set to a file + - deps: send@0.16.1 + +4.16.0 / 2017-09-28 +=================== + + * Add `"json escape"` setting for `res.json` and `res.jsonp` + * Add `express.json` and `express.urlencoded` to parse bodies + * Add `options` argument to `res.download` + * Improve error message when autoloading invalid view engine + * Improve error messages when non-function provided as middleware + * Skip `Buffer` encoding when not generating ETag for small response + * Use `safe-buffer` for improved Buffer API + * deps: accepts@~1.3.4 + - deps: mime-types@~2.1.16 + * deps: content-type@~1.0.4 + - perf: remove argument reassignment + - perf: skip parameter parsing when no parameters + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: finalhandler@1.1.0 + - Use `res.headersSent` when available + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: proxy-addr@~2.0.2 + - Fix trimming leading / trailing OWS in `X-Forwarded-For` + - deps: forwarded@~0.1.2 + - deps: ipaddr.js@1.5.2 + - perf: reduce overhead when no `X-Forwarded-For` header + * deps: qs@6.5.1 + - Fix parsing & compacting very deep objects + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + * deps: serve-static@1.13.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Set charset as "UTF-8" for .js and .json + - deps: send@0.16.0 + * deps: setprototypeof@1.1.0 + * deps: utils-merge@1.0.1 + * deps: vary@~1.1.2 + - perf: improve header token parsing speed + * perf: re-use options object when generating ETags + * perf: remove dead `.charset` set in `res.jsonp` + +4.15.5 / 2017-09-24 +=================== + + * deps: debug@2.6.9 + * deps: finalhandler@~1.0.6 + - deps: debug@2.6.9 + - deps: parseurl@~1.3.2 + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + * deps: send@0.15.6 + - Fix handling of modified headers with invalid dates + - deps: debug@2.6.9 + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + - perf: improve `If-Match` token parsing + * deps: serve-static@1.12.6 + - deps: parseurl@~1.3.2 + - deps: send@0.15.6 + - perf: improve slash collapsing + +4.15.4 / 2017-08-06 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: finalhandler@~1.0.4 + - deps: debug@2.6.8 + * deps: proxy-addr@~1.1.5 + - Fix array argument being altered + - deps: ipaddr.js@1.4.0 + * deps: qs@6.5.0 + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + * deps: serve-static@1.12.4 + - deps: send@0.15.4 + +4.15.3 / 2017-05-16 +=================== + + * Fix error when `res.set` cannot add charset to `Content-Type` + * deps: debug@2.6.7 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@2.0.0 + * deps: finalhandler@~1.0.3 + - Fix missing `` in HTML document + - deps: debug@2.6.7 + * deps: proxy-addr@~1.1.4 + - deps: ipaddr.js@1.3.0 + * deps: send@0.15.3 + - deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: serve-static@1.12.3 + - deps: send@0.15.3 + * deps: type-is@~1.6.15 + - deps: mime-types@~2.1.15 + * deps: vary@~1.1.1 + - perf: hoist regular expression + +4.15.2 / 2017-03-06 +=================== + + * deps: qs@6.4.0 + - Fix regression parsing keys starting with `[` + +4.15.1 / 2017-03-05 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + * deps: serve-static@1.12.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - deps: send@0.15.1 + +4.15.0 / 2017-03-01 +=================== + + * Add debug message when loading view engine + * Add `next("router")` to exit from router + * Fix case where `router.use` skipped requests routes did not + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Skip routing when `req.url` is not set + * Use `%o` in path debug to tell types apart + * Use `Object.create` to setup request & response prototypes + * Use `setprototypeof` module to replace `__proto__` setting + * Use `statuses` instead of `http` module for status messages + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + - Use SHA1 instead of MD5 for ETag hashing + - Works with FIPS 140-2 OpenSSL configuration + * deps: finalhandler@~1.0.0 + - Fix exception when `err` cannot be converted to a string + - Fully URL-encode the pathname in the 404 + - Only include the pathname in the 404 message + - Send complete HTML document + - Set `Content-Security-Policy: default-src 'self'` header + - deps: debug@2.6.1 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: qs@6.3.1 + - Fix array parsing from skipping empty values + - Fix compacting nested arrays + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + * deps: serve-static@1.12.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Send complete HTML document in redirect response + - Set default CSP header in redirect response + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: send@0.15.0 + * perf: add fast match path for `*` route + * perf: improve `req.ips` performance + +4.14.1 / 2017-01-28 +=================== + + * deps: content-disposition@0.5.2 + * deps: finalhandler@0.5.1 + - Fix exception when `err.headers` is not an object + - deps: statuses@~1.3.1 + - perf: hoist regular expressions + - perf: remove duplicate validation path + * deps: proxy-addr@~1.1.3 + - deps: ipaddr.js@1.2.0 + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + * deps: serve-static@~1.11.2 + - deps: send@0.14.2 + * deps: type-is@~1.6.14 + - deps: mime-types@~2.1.13 + +4.14.0 / 2016-06-16 +=================== + + * Add `acceptRanges` option to `res.sendFile`/`res.sendfile` + * Add `cacheControl` option to `res.sendFile`/`res.sendfile` + * Add `options` argument to `req.range` + - Includes the `combine` option + * Encode URL in `res.location`/`res.redirect` if not already encoded + * Fix some redirect handling in `res.sendFile`/`res.sendfile` + * Fix Windows absolute path check using forward slashes + * Improve error with invalid arguments to `req.get()` + * Improve performance for `res.json`/`res.jsonp` in most cases + * Improve `Range` header handling in `res.sendFile`/`res.sendfile` + * deps: accepts@~1.3.3 + - Fix including type extensions in parameters in `Accept` parsing + - Fix parsing `Accept` parameters with quoted equals + - Fix parsing `Accept` parameters with quoted semicolons + - Many performance improvments + - deps: mime-types@~2.1.11 + - deps: negotiator@0.6.1 + * deps: content-type@~1.0.2 + - perf: enable strict mode + * deps: cookie@0.3.1 + - Add `sameSite` option + - Fix cookie `Max-Age` to never be a floating point number + - Improve error message when `encode` is not a function + - Improve error message when `expires` is not a `Date` + - Throw better error for invalid argument to parse + - Throw on invalid values provided to `serialize` + - perf: enable strict mode + - perf: hoist regular expression + - perf: use for loop in parse + - perf: use string concatination for serialization + * deps: finalhandler@0.5.0 + - Change invalid or non-numeric status code to 500 + - Overwrite status message to match set status code + - Prefer `err.statusCode` if `err.status` is invalid + - Set response headers from `err.headers` object + - Use `statuses` instead of `http` module for status messages + * deps: proxy-addr@~1.1.2 + - Fix accepting various invalid netmasks + - Fix IPv6-mapped IPv4 validation edge cases + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + - deps: ipaddr.js@1.1.1 + * deps: qs@6.2.0 + - Add `decoder` option in `parse` function + * deps: range-parser@~1.2.0 + - Add `combine` option to combine overlapping ranges + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: send@0.14.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Fix redirect error when `path` contains raw non-URL characters + - Fix redirect when `path` starts with multiple forward slashes + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + * deps: serve-static@~1.11.1 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Fix redirect error when `req.url` contains raw non-URL characters + - Ignore non-byte `Range` headers + - Use status code 301 for redirects + - deps: send@0.14.1 + * deps: type-is@~1.6.13 + - Fix type error when given invalid type to match against + - deps: mime-types@~2.1.11 + * deps: vary@~1.1.0 + - Only accept valid field names in the `field` argument + * perf: use strict equality when possible + +4.13.4 / 2016-01-21 +=================== + + * deps: content-disposition@0.5.1 + - perf: enable strict mode + * deps: cookie@0.1.5 + - Throw on invalid values provided to `serialize` + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: finalhandler@0.4.1 + - deps: escape-html@~1.0.3 + * deps: merge-descriptors@1.0.1 + - perf: enable strict mode + * deps: methods@~1.1.2 + - perf: enable strict mode + * deps: parseurl@~1.3.1 + - perf: enable strict mode + * deps: proxy-addr@~1.0.10 + - deps: ipaddr.js@1.0.5 + - perf: enable strict mode + * deps: range-parser@~1.0.3 + - perf: enable strict mode + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + * deps: serve-static@~1.10.2 + - deps: escape-html@~1.0.3 + - deps: parseurl@~1.3.0 + - deps: send@0.13.1 + +4.13.3 / 2015-08-02 +=================== + + * Fix infinite loop condition using `mergeParams: true` + * Fix inner numeric indices incorrectly altering parent `req.params` + +4.13.2 / 2015-07-31 +=================== + + * deps: accepts@~1.2.12 + - deps: mime-types@~2.1.4 + * deps: array-flatten@1.1.1 + - perf: enable strict mode + * deps: path-to-regexp@0.1.7 + - Fix regression with escaped round brackets and matching groups + * deps: type-is@~1.6.6 + - deps: mime-types@~2.1.4 + +4.13.1 / 2015-07-05 +=================== + + * deps: accepts@~1.2.10 + - deps: mime-types@~2.1.2 + * deps: qs@4.0.0 + - Fix dropping parameters like `hasOwnProperty` + - Fix various parsing edge cases + * deps: type-is@~1.6.4 + - deps: mime-types@~2.1.2 + - perf: enable strict mode + - perf: remove argument reassignment + +4.13.0 / 2015-06-20 +=================== + + * Add settings to debug output + * Fix `res.format` error when only `default` provided + * Fix issue where `next('route')` in `app.param` would incorrectly skip values + * Fix hiding platform issues with `decodeURIComponent` + - Only `URIError`s are a 400 + * Fix using `*` before params in routes + * Fix using capture groups before params in routes + * Simplify `res.cookie` to call `res.append` + * Use `array-flatten` module for flattening arrays + * deps: accepts@~1.2.9 + - deps: mime-types@~2.1.1 + - perf: avoid argument reassignment & argument slice + - perf: avoid negotiator recursive construction + - perf: enable strict mode + - perf: remove unnecessary bitwise operator + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: finalhandler@0.4.0 + - Fix a false-positive when unpiping in Node.js 0.8 + - Support `statusCode` property on `Error` objects + - Use `unpipe` module for unpiping requests + - deps: escape-html@1.0.2 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * deps: path-to-regexp@0.1.6 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * deps: serve-static@~1.10.0 + - Add `fallthrough` option + - Fix reading options from options prototype + - Improve the default redirect response headers + - Malformed URLs now `next()` instead of 400 + - deps: escape-html@1.0.2 + - deps: send@0.13.0 + - perf: enable strict mode + - perf: remove argument reassignment + * deps: type-is@~1.6.3 + - deps: mime-types@~2.1.1 + - perf: reduce try block size + - perf: remove bitwise operations + * perf: enable strict mode + * perf: isolate `app.render` try block + * perf: remove argument reassignments in application + * perf: remove argument reassignments in request prototype + * perf: remove argument reassignments in response prototype + * perf: remove argument reassignments in routing + * perf: remove argument reassignments in `View` + * perf: skip attempting to decode zero length string + * perf: use saved reference to `http.STATUS_CODES` + +4.12.4 / 2015-05-17 +=================== + + * deps: accepts@~1.2.7 + - deps: mime-types@~2.0.11 + - deps: negotiator@0.5.3 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: finalhandler@0.3.6 + - deps: debug@~2.2.0 + - deps: on-finished@~2.2.1 + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: qs@2.4.2 + - Fix allowing parameters like `constructor` + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + * deps: serve-static@~1.9.3 + - deps: send@0.12.3 + * deps: type-is@~1.6.2 + - deps: mime-types@~2.0.11 + +4.12.3 / 2015-03-17 +=================== + + * deps: accepts@~1.2.5 + - deps: mime-types@~2.0.10 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: finalhandler@0.3.4 + - deps: debug@~2.1.3 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: qs@2.4.1 + - Fix error when parameter `hasOwnProperty` is present + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + * deps: serve-static@~1.9.2 + - deps: send@0.12.2 + * deps: type-is@~1.6.1 + - deps: mime-types@~2.0.10 + +4.12.2 / 2015-03-02 +=================== + + * Fix regression where `"Request aborted"` is logged using `res.sendFile` + +4.12.1 / 2015-03-01 +=================== + + * Fix constructing application with non-configurable prototype properties + * Fix `ECONNRESET` errors from `res.sendFile` usage + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + * Fix wrong `code` on aborted connections from `res.sendFile` + * deps: merge-descriptors@1.0.0 + +4.12.0 / 2015-02-23 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: accepts@~1.2.4 + - Fix preference sorting to be stable for long acceptable lists + - deps: mime-types@~2.0.9 + - deps: negotiator@0.5.1 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + * deps: serve-static@~1.9.1 + - deps: send@0.12.1 + * deps: type-is@~1.6.0 + - fix argument reassignment + - fix false-positives in `hasBody` `Transfer-Encoding` check + - support wildcard for both type and subtype (`*/*`) + - deps: mime-types@~2.0.9 + +4.11.2 / 2015-02-01 +=================== + + * Fix `res.redirect` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.2.3 + - deps: mime-types@~2.0.8 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + * deps: type-is@~1.5.6 + - deps: mime-types@~2.0.8 + +4.11.1 / 2015-01-20 +=================== + + * deps: send@0.11.1 + - Fix root path disclosure + * deps: serve-static@~1.8.1 + - Fix redirect loop in Node.js 0.11.14 + - Fix root path disclosure + - deps: send@0.11.1 + +4.11.0 / 2015-01-13 +=================== + + * Add `res.append(field, val)` to append headers + * Deprecate leading `:` in `name` for `app.param(name, fn)` + * Deprecate `req.param()` -- use `req.params`, `req.body`, or `req.query` instead + * Deprecate `app.param(fn)` + * Fix `OPTIONS` responses to include the `HEAD` method properly + * Fix `res.sendFile` not always detecting aborted connection + * Match routes iteratively to prevent stack overflows + * deps: accepts@~1.2.2 + - deps: mime-types@~2.0.7 + - deps: negotiator@0.5.0 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + * deps: serve-static@~1.8.0 + - deps: send@0.11.0 + +4.10.8 / 2015-01-13 +=================== + + * Fix crash from error within `OPTIONS` response handler + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + +4.10.7 / 2015-01-04 +=================== + + * Fix `Allow` header for `OPTIONS` to not contain duplicate methods + * Fix incorrect "Request aborted" for `res.sendFile` when `HEAD` or 304 + * deps: debug@~2.1.1 + * deps: finalhandler@0.3.3 + - deps: debug@~2.1.1 + - deps: on-finished@~2.2.0 + * deps: methods@~1.1.1 + * deps: on-finished@~2.2.0 + * deps: serve-static@~1.7.2 + - Fix potential open redirect when mounted at root + * deps: type-is@~1.5.5 + - deps: mime-types@~2.0.7 + +4.10.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +4.10.5 / 2014-12-10 +=================== + + * Fix `res.send` double-calling `res.end` for `HEAD` requests + * deps: accepts@~1.1.4 + - deps: mime-types@~2.0.4 + * deps: type-is@~1.5.4 + - deps: mime-types@~2.0.4 + +4.10.4 / 2014-11-24 +=================== + + * Fix `res.sendfile` logging standard write errors + +4.10.3 / 2014-11-23 +=================== + + * Fix `res.sendFile` logging standard write errors + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + * deps: qs@2.3.3 + - Fix `arrayLimit` behavior + +4.10.2 / 2014-11-09 +=================== + + * Correctly invoke async router callback asynchronously + * deps: accepts@~1.1.3 + - deps: mime-types@~2.0.3 + * deps: type-is@~1.5.3 + - deps: mime-types@~2.0.3 + +4.10.1 / 2014-10-28 +=================== + + * Fix handling of URLs containing `://` in the path + * deps: qs@2.3.2 + - Fix parsing of mixed objects and values + +4.10.0 / 2014-10-23 +=================== + + * Add support for `app.set('views', array)` + - Views are looked up in sequence in array of directories + * Fix `res.send(status)` to mention `res.sendStatus(status)` + * Fix handling of invalid empty URLs + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `path.resolve` in view lookup + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + * deps: finalhandler@0.3.2 + - Terminate in progress response only on error + - Use `on-finished` to determine request status + - deps: debug@~2.1.0 + - deps: on-finished@~2.1.1 + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + * deps: qs@2.3.0 + - Fix parsing of mixed implicit and explicit arrays + * deps: send@0.10.1 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + - deps: on-finished@~2.1.1 + * deps: serve-static@~1.7.1 + - deps: send@0.10.1 + +4.9.8 / 2014-10-17 +================== + + * Fix `res.redirect` body when redirect status specified + * deps: accepts@~1.1.2 + - Fix error when media type has invalid parameter + - deps: negotiator@0.4.9 + +4.9.7 / 2014-10-10 +================== + + * Fix using same param name in array of paths + +4.9.6 / 2014-10-08 +================== + + * deps: accepts@~1.1.1 + - deps: mime-types@~2.0.2 + - deps: negotiator@0.4.8 + * deps: serve-static@~1.6.4 + - Fix redirect loop when index file serving disabled + * deps: type-is@~1.5.2 + - deps: mime-types@~2.0.2 + +4.9.5 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + * deps: serve-static@~1.6.3 + - deps: send@0.9.3 + +4.9.4 / 2014-09-19 +================== + + * deps: qs@2.2.4 + - Fix issue with object keys starting with numbers truncated + +4.9.3 / 2014-09-18 +================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +4.9.2 / 2014-09-17 +================== + + * Fix regression for empty string `path` in `app.use` + * Fix `router.use` to accept array of middleware without path + * Improve error message for bad `app.use` arguments + +4.9.1 / 2014-09-16 +================== + + * Fix `app.use` to accept array of middleware without path + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + * deps: serve-static@~1.6.2 + - deps: send@0.9.2 + +4.9.0 / 2014-09-08 +================== + + * Add `res.sendStatus` + * Invoke callback for sendfile when client aborts + - Applies to `res.sendFile`, `res.sendfile`, and `res.download` + - `err` will be populated with request aborted error + * Support IP address host in `req.subdomains` + * Use `etag` to generate `ETag` headers + * deps: accepts@~1.1.0 + - update `mime-types` + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: finalhandler@0.2.0 + - Set `X-Content-Type-Options: nosniff` header + - deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: qs@2.2.3 + - Fix issue where first empty value in array is discarded + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: serve-static@~1.6.1 + - Add `lastModified` option + - deps: send@0.9.1 + * deps: type-is@~1.5.1 + - fix `hasbody` to be true for `content-length: 0` + - deps: media-typer@0.3.0 + - deps: mime-types@~2.0.1 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +4.8.8 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + * deps: serve-static@~1.5.4 + - deps: send@0.8.5 + +4.8.7 / 2014-08-29 +================== + + * deps: qs@2.2.2 + - Remove unnecessary cloning + +4.8.6 / 2014-08-27 +================== + + * deps: qs@2.2.0 + - Array parsing fix + - Performance improvements + +4.8.5 / 2014-08-18 +================== + + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + * deps: serve-static@~1.5.3 + - deps: send@0.8.3 + +4.8.4 / 2014-08-14 +================== + + * deps: qs@1.2.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: serve-static@~1.5.2 + - deps: send@0.8.2 + +4.8.3 / 2014-08-10 +================== + + * deps: parseurl@~1.3.0 + * deps: qs@1.2.1 + * deps: serve-static@~1.5.1 + - Fix parsing of weird `req.originalUrl` values + - deps: parseurl@~1.3.0 + - deps: utils-merge@1.0.0 + +4.8.2 / 2014-08-07 +================== + + * deps: qs@1.2.0 + - Fix parsing array of objects + +4.8.1 / 2014-08-06 +================== + + * fix incorrect deprecation warnings on `res.download` + * deps: qs@1.1.0 + - Accept urlencoded square brackets + - Accept empty values in implicit array notation + +4.8.0 / 2014-08-05 +================== + + * add `res.sendFile` + - accepts a file system path instead of a URL + - requires an absolute path or `root` option specified + * deprecate `res.sendfile` -- use `res.sendFile` instead + * support mounted app as any argument to `app.use()` + * deps: qs@1.0.2 + - Complete rewrite + - Limits array length to 20 + - Limits object depth to 5 + - Limits parameters to 1,000 + * deps: send@0.8.1 + - Add `extensions` option + * deps: serve-static@~1.5.0 + - Add `extensions` option + - deps: send@0.8.1 + +4.7.4 / 2014-08-04 +================== + + * fix `res.sendfile` regression for serving directory index files + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + * deps: serve-static@~1.4.4 + - deps: send@0.7.4 + +4.7.3 / 2014-08-04 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + * deps: serve-static@~1.4.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + - deps: send@0.7.3 + +4.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + * deps: serve-static@~1.4.2 + +4.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + * deps: serve-static@~1.4.1 + +4.7.0 / 2014-07-25 +================== + + * fix `req.protocol` for proxy-direct connections + * configurable query parser with `app.set('query parser', parser)` + - `app.set('query parser', 'extended')` parse with "qs" module + - `app.set('query parser', 'simple')` parse with "querystring" core module + - `app.set('query parser', false)` disable query string parsing + - `app.set('query parser', true)` enable simple parsing + * deprecate `res.json(status, obj)` -- use `res.status(status).json(obj)` instead + * deprecate `res.jsonp(status, obj)` -- use `res.status(status).jsonp(obj)` instead + * deprecate `res.send(status, body)` -- use `res.status(status).send(body)` instead + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: finalhandler@0.1.0 + - Respond after request fully read + - deps: debug@1.0.4 + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + * deps: serve-static@~1.4.0 + - deps: parseurl@~1.2.0 + - deps: send@0.7.0 + * perf: prevent multiple `Buffer` creation in `res.send` + +4.6.1 / 2014-07-12 +================== + + * fix `subapp.mountpath` regression for `app.use(subapp)` + +4.6.0 / 2014-07-11 +================== + + * accept multiple callbacks to `app.use()` + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * catch errors in multiple `req.param(name, fn)` handlers + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * support non-string `path` in `app.use(path, fn)` + - supports array of paths + - supports `RegExp` + * router: fix optimization on router exit + * router: refactor location of `try` blocks + * router: speed up standard `app.use(fn)` + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: finalhandler@0.0.3 + - deps: debug@1.0.3 + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + * deps: path-to-regexp@0.1.3 + * deps: send@0.6.0 + - deps: debug@1.0.3 + * deps: serve-static@~1.3.2 + - deps: parseurl@~1.1.3 + - deps: send@0.6.0 + * perf: fix arguments reassign deopt in some `res` methods + +4.5.1 / 2014-07-06 +================== + + * fix routing regression when altering `req.method` + +4.5.0 / 2014-07-04 +================== + + * add deprecation message to non-plural `req.accepts*` + * add deprecation message to `res.send(body, status)` + * add deprecation message to `res.vary()` + * add `headers` option to `res.sendfile` + - use to set headers on successful file transfer + * add `mergeParams` option to `Router` + - merges `req.params` from parent routes + * add `req.hostname` -- correct name for what `req.host` returns + * deprecate things with `depd` module + * deprecate `req.host` -- use `req.hostname` instead + * fix behavior when handling request without routes + * fix handling when `route.all` is only route + * invoke `router.param()` only when route matches + * restore `req.params` after invoking router + * use `finalhandler` for final response handling + * use `media-typer` to alter content-type charset + * deps: accepts@~1.0.7 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + * deps: serve-static@~1.3.0 + - Accept string for `maxAge` (converted by `ms`) + - Add `setHeaders` option + - Include HTML link in redirect response + - deps: send@0.5.0 + * deps: type-is@~1.3.2 + +4.4.5 / 2014-06-26 +================== + + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +4.4.4 / 2014-06-20 +================== + + * fix `res.attachment` Unicode filenames in Safari + * fix "trim prefix" debug message in `express:router` + * deps: accepts@~1.0.5 + * deps: buffer-crc32@0.2.3 + +4.4.3 / 2014-06-11 +================== + + * fix persistence of modified `req.params[name]` from `app.param()` + * deps: accepts@1.0.3 + - deps: negotiator@0.4.6 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + * deps: serve-static@1.2.3 + - Do not throw un-catchable error on file open race condition + - deps: send@0.4.3 + +4.4.2 / 2014-06-09 +================== + + * fix catching errors from top-level handlers + * use `vary` module for `res.vary` + * deps: debug@1.0.1 + * deps: proxy-addr@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + * deps: serve-static@1.2.2 + - fix "event emitter leak" warnings + - deps: send@0.4.2 + * deps: type-is@1.2.1 + +4.4.1 / 2014-06-02 +================== + + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + * deps: serve-static@1.2.1 + - use `escape-html` for escaping + - deps: send@0.4.1 + +4.4.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * mark `res.send` ETag as weak and reduce collisions + * update accepts to 1.0.2 + - Fix interpretation when header not in request + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + * update serve-static to 1.2.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: send@0.4.0 + +4.3.2 / 2014-05-28 +================== + + * fix handling of errors from `router.param()` callbacks + +4.3.1 / 2014-05-23 +================== + + * revert "fix behavior of multiple `app.VERB` for the same path" + - this caused a regression in the order of route execution + +4.3.0 / 2014-05-21 +================== + + * add `req.baseUrl` to access the path stripped from `req.url` in routes + * fix behavior of multiple `app.VERB` for the same path + * fix issue routing requests among sub routers + * invoke `router.param()` only when necessary instead of every match + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * set proper `charset` in `Content-Type` for `res.send` + * update type-is to 1.2.0 + - support suffix matching + +4.2.0 / 2014-05-11 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * fix `req.next` when inside router instance + * include `ETag` header in `HEAD` requests + * keep previous `Content-Type` for `res.jsonp` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update debug to 0.8.0 + - add `enable()` method + - change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + +4.1.2 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +4.1.1 / 2014-04-27 +================== + + * fix package.json to reflect supported node version + +4.1.0 / 2014-04-24 +================== + + * pass options from `res.sendfile` to `send` + * preserve casing of headers in `res.header` and `res.set` + * support unicode file names in `res.attachment` and `res.download` + * update accepts to 1.0.1 + - deps: negotiator@0.4.0 + * update cookie to 0.1.2 + - Fix for maxAge == 0 + - made compat with expires field + * update send to 0.3.0 + - Accept API options in options object + - Coerce option types + - Control whether to generate etags + - Default directory access to 403 when index disabled + - Fix sending files with dots without root set + - Include file path in etag + - Make "Can't set headers after they are sent." catchable + - Send full entity-body for multi range requests + - Set etags to "weak" + - Support "If-Range" header + - Support multiple index paths + - deps: mime@1.2.11 + * update serve-static to 1.1.0 + - Accept options directly to `send` module + - Resolve relative paths at middleware setup + - Use parseurl to parse the URL from request + - deps: send@0.3.0 + * update type-is to 1.1.0 + - add non-array values support + - add `multipart` as a shorthand + +4.0.0 / 2014-04-09 +================== + + * remove: + - node 0.8 support + - connect and connect's patches except for charset handling + - express(1) - moved to [express-generator](https://github.com/expressjs/generator) + - `express.createServer()` - it has been deprecated for a long time. Use `express()` + - `app.configure` - use logic in your own app code + - `app.router` - is removed + - `req.auth` - use `basic-auth` instead + - `req.accepted*` - use `req.accepts*()` instead + - `res.location` - relative URL resolution is removed + - `res.charset` - include the charset in the content type when using `res.set()` + - all bundled middleware except `static` + * change: + - `app.route` -> `app.mountpath` when mounting an express app in another express app + - `json spaces` no longer enabled by default in development + - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` + - `req.params` is now an object instead of an array + - `res.locals` is no longer a function. It is a plain js object. Treat it as such. + - `res.headerSent` -> `res.headersSent` to match node.js ServerResponse object + * refactor: + - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) + - `req.is` with [type-is](https://github.com/expressjs/type-is) + - [path-to-regexp](https://github.com/component/path-to-regexp) + * add: + - `app.router()` - returns the app Router instance + - `app.route()` - Proxy to the app's `Router#route()` method to create a new route + - Router & Route - public API + +3.21.2 / 2015-07-31 +=================== + + * deps: connect@2.30.2 + - deps: body-parser@~1.13.3 + - deps: compression@~1.5.2 + - deps: errorhandler@~1.4.2 + - deps: method-override@~2.3.5 + - deps: serve-index@~1.7.2 + - deps: type-is@~1.6.6 + - deps: vhost@~3.0.1 + * deps: vary@~1.0.1 + - Fix setting empty header from empty `field` + - perf: enable strict mode + - perf: remove argument reassignments + +3.21.1 / 2015-07-05 +=================== + + * deps: basic-auth@~1.0.3 + * deps: connect@2.30.1 + - deps: body-parser@~1.13.2 + - deps: compression@~1.5.1 + - deps: errorhandler@~1.4.1 + - deps: morgan@~1.6.1 + - deps: pause@0.1.0 + - deps: qs@4.0.0 + - deps: serve-index@~1.7.1 + - deps: type-is@~1.6.4 + +3.21.0 / 2015-06-18 +=================== + + * deps: basic-auth@1.0.2 + - perf: enable strict mode + - perf: hoist regular expression + - perf: parse with regular expressions + - perf: remove argument reassignment + * deps: connect@2.30.0 + - deps: body-parser@~1.13.1 + - deps: bytes@2.1.0 + - deps: compression@~1.5.0 + - deps: cookie@0.1.3 + - deps: cookie-parser@~1.3.5 + - deps: csurf@~1.8.3 + - deps: errorhandler@~1.4.0 + - deps: express-session@~1.11.3 + - deps: finalhandler@0.4.0 + - deps: fresh@0.3.0 + - deps: morgan@~1.6.0 + - deps: serve-favicon@~2.3.0 + - deps: serve-index@~1.7.0 + - deps: serve-static@~1.10.0 + - deps: type-is@~1.6.3 + * deps: cookie@0.1.3 + - perf: deduce the scope of try-catch deopt + - perf: remove argument reassignments + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Always include entity length in ETags for hash length extensions + - Generate non-Stats ETags using MD5 only (no longer CRC32) + - Improve stat performance by removing hashing + - Improve support for JXcore + - Remove base64 padding in ETags to shorten + - Support "fake" stats objects in environments without fs + - Use MD5 instead of MD4 in weak ETags over 1KB + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: mkdirp@0.5.1 + - Work in global strict mode + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + +3.20.3 / 2015-05-17 +=================== + + * deps: connect@2.29.2 + - deps: body-parser@~1.12.4 + - deps: compression@~1.4.4 + - deps: connect-timeout@~1.6.2 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: errorhandler@~1.3.6 + - deps: finalhandler@0.3.6 + - deps: method-override@~2.3.3 + - deps: morgan@~1.5.3 + - deps: qs@2.4.2 + - deps: response-time@~2.3.1 + - deps: serve-favicon@~2.2.1 + - deps: serve-index@~1.6.4 + - deps: serve-static@~1.9.3 + - deps: type-is@~1.6.2 + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: proxy-addr@~1.0.8 + - deps: ipaddr.js@1.0.1 + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +3.20.2 / 2015-03-16 +=================== + + * deps: connect@2.29.1 + - deps: body-parser@~1.12.2 + - deps: compression@~1.4.3 + - deps: connect-timeout@~1.6.1 + - deps: debug@~2.1.3 + - deps: errorhandler@~1.3.5 + - deps: express-session@~1.10.4 + - deps: finalhandler@0.3.4 + - deps: method-override@~2.3.2 + - deps: morgan@~1.5.2 + - deps: qs@2.4.1 + - deps: serve-index@~1.6.3 + - deps: serve-static@~1.9.2 + - deps: type-is@~1.6.1 + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + * deps: merge-descriptors@1.0.0 + * deps: proxy-addr@~1.0.7 + - deps: ipaddr.js@0.1.9 + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +3.20.1 / 2015-02-28 +=================== + + * Fix `req.host` when using "trust proxy" hops count + * Fix `req.protocol`/`req.secure` when using "trust proxy" hops count + +3.20.0 / 2015-02-18 +=================== + + * Fix `"trust proxy"` setting to inherit when app is mounted + * Generate `ETag`s for all request responses + - No longer restricted to only responses for `GET` and `HEAD` requests + * Use `content-type` to parse `Content-Type` headers + * deps: connect@2.29.0 + - Use `content-type` to parse `Content-Type` headers + - deps: body-parser@~1.12.0 + - deps: compression@~1.4.1 + - deps: connect-timeout@~1.6.0 + - deps: cookie-parser@~1.3.4 + - deps: cookie-signature@1.0.6 + - deps: csurf@~1.7.0 + - deps: errorhandler@~1.3.4 + - deps: express-session@~1.10.3 + - deps: http-errors@~1.3.1 + - deps: response-time@~2.3.0 + - deps: serve-index@~1.6.2 + - deps: serve-static@~1.9.1 + - deps: type-is@~1.6.0 + * deps: cookie-signature@1.0.6 + * deps: send@0.12.1 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +3.19.2 / 2015-02-01 +=================== + + * deps: connect@2.28.3 + - deps: compression@~1.3.1 + - deps: csurf@~1.6.6 + - deps: errorhandler@~1.3.3 + - deps: express-session@~1.10.2 + - deps: serve-index@~1.6.1 + - deps: type-is@~1.5.6 + * deps: proxy-addr@~1.0.6 + - deps: ipaddr.js@0.1.8 + +3.19.1 / 2015-01-20 +=================== + + * deps: connect@2.28.2 + - deps: body-parser@~1.10.2 + - deps: serve-static@~1.8.1 + * deps: send@0.11.1 + - Fix root path disclosure + +3.19.0 / 2015-01-09 +=================== + + * Fix `OPTIONS` responses to include the `HEAD` method property + * Use `readline` for prompt in `express(1)` + * deps: commander@2.6.0 + * deps: connect@2.28.1 + - deps: body-parser@~1.10.1 + - deps: compression@~1.3.0 + - deps: connect-timeout@~1.5.0 + - deps: csurf@~1.6.4 + - deps: debug@~2.1.1 + - deps: errorhandler@~1.3.2 + - deps: express-session@~1.10.1 + - deps: finalhandler@0.3.3 + - deps: method-override@~2.3.1 + - deps: morgan@~1.5.1 + - deps: serve-favicon@~2.2.0 + - deps: serve-index@~1.6.0 + - deps: serve-static@~1.8.0 + - deps: type-is@~1.5.5 + * deps: debug@~2.1.1 + * deps: methods@~1.1.1 + * deps: proxy-addr@~1.0.5 + - deps: ipaddr.js@0.1.6 + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +3.18.6 / 2014-12-12 +=================== + + * Fix exception in `req.fresh`/`req.stale` without response headers + +3.18.5 / 2014-12-11 +=================== + + * deps: connect@2.27.6 + - deps: compression@~1.2.2 + - deps: express-session@~1.9.3 + - deps: http-errors@~1.2.8 + - deps: serve-index@~1.5.3 + - deps: type-is@~1.5.4 + +3.18.4 / 2014-11-23 +=================== + + * deps: connect@2.27.4 + - deps: body-parser@~1.9.3 + - deps: compression@~1.2.1 + - deps: errorhandler@~1.2.3 + - deps: express-session@~1.9.2 + - deps: qs@2.3.3 + - deps: serve-favicon@~2.1.7 + - deps: serve-static@~1.5.1 + - deps: type-is@~1.5.3 + * deps: etag@~1.5.1 + * deps: proxy-addr@~1.0.4 + - deps: ipaddr.js@0.1.5 + +3.18.3 / 2014-11-09 +=================== + + * deps: connect@2.27.3 + - Correctly invoke async callback asynchronously + - deps: csurf@~1.6.3 + +3.18.2 / 2014-10-28 +=================== + + * deps: connect@2.27.2 + - Fix handling of URLs containing `://` in the path + - deps: body-parser@~1.9.2 + - deps: qs@2.3.2 + +3.18.1 / 2014-10-22 +=================== + + * Fix internal `utils.merge` deprecation warnings + * deps: connect@2.27.1 + - deps: body-parser@~1.9.1 + - deps: express-session@~1.9.1 + - deps: finalhandler@0.3.2 + - deps: morgan@~1.4.1 + - deps: qs@2.3.0 + - deps: serve-static@~1.7.1 + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +3.18.0 / 2014-10-17 +=================== + + * Use `content-disposition` module for `res.attachment`/`res.download` + - Sends standards-compliant `Content-Disposition` header + - Full Unicode support + * Use `etag` module to generate `ETag` headers + * deps: connect@2.27.0 + - Use `http-errors` module for creating errors + - Use `utils-merge` module for merging objects + - deps: body-parser@~1.9.0 + - deps: compression@~1.2.0 + - deps: connect-timeout@~1.4.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: express-session@~1.9.0 + - deps: finalhandler@0.3.1 + - deps: method-override@~2.3.0 + - deps: morgan@~1.4.0 + - deps: response-time@~2.2.0 + - deps: serve-favicon@~2.1.6 + - deps: serve-index@~1.5.0 + - deps: serve-static@~1.7.0 + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +3.17.8 / 2014-10-15 +=================== + + * deps: connect@2.26.6 + - deps: compression@~1.1.2 + - deps: csurf@~1.6.2 + - deps: errorhandler@~1.2.2 + +3.17.7 / 2014-10-08 +=================== + + * deps: connect@2.26.5 + - Fix accepting non-object arguments to `logger` + - deps: serve-static@~1.6.4 + +3.17.6 / 2014-10-02 +=================== + + * deps: connect@2.26.4 + - deps: morgan@~1.3.2 + - deps: type-is@~1.5.2 + +3.17.5 / 2014-09-24 +=================== + + * deps: connect@2.26.3 + - deps: body-parser@~1.8.4 + - deps: serve-favicon@~2.1.5 + - deps: serve-static@~1.6.3 + * deps: proxy-addr@~1.0.3 + - Use `forwarded` npm module + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +3.17.4 / 2014-09-19 +=================== + + * deps: connect@2.26.2 + - deps: body-parser@~1.8.3 + - deps: qs@2.2.4 + +3.17.3 / 2014-09-18 +=================== + + * deps: proxy-addr@~1.0.2 + - Fix a global leak when multiple subnets are trusted + - deps: ipaddr.js@0.1.3 + +3.17.2 / 2014-09-15 +=================== + + * Use `crc` instead of `buffer-crc32` for speed + * deps: connect@2.26.1 + - deps: body-parser@~1.8.2 + - deps: depd@0.4.5 + - deps: express-session@~1.8.2 + - deps: morgan@~1.3.1 + - deps: serve-favicon@~2.1.3 + - deps: serve-static@~1.6.2 + * deps: depd@0.4.5 + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +3.17.1 / 2014-09-08 +=================== + + * Fix error in `req.subdomains` on empty host + +3.17.0 / 2014-09-08 +=================== + + * Support `X-Forwarded-Host` in `req.subdomains` + * Support IP address host in `req.subdomains` + * deps: connect@2.26.0 + - deps: body-parser@~1.8.1 + - deps: compression@~1.1.0 + - deps: connect-timeout@~1.3.0 + - deps: cookie-parser@~1.3.3 + - deps: cookie-signature@1.0.5 + - deps: csurf@~1.6.1 + - deps: debug@~2.0.0 + - deps: errorhandler@~1.2.0 + - deps: express-session@~1.8.1 + - deps: finalhandler@0.2.0 + - deps: fresh@0.2.4 + - deps: media-typer@0.3.0 + - deps: method-override@~2.2.0 + - deps: morgan@~1.3.0 + - deps: qs@2.2.3 + - deps: serve-favicon@~2.1.3 + - deps: serve-index@~1.2.1 + - deps: serve-static@~1.6.1 + - deps: type-is@~1.5.1 + - deps: vhost@~3.0.0 + * deps: cookie-signature@1.0.5 + * deps: debug@~2.0.0 + * deps: fresh@0.2.4 + * deps: media-typer@0.3.0 + - Throw error when parameter format invalid on parse + * deps: range-parser@~1.0.2 + * deps: send@0.9.1 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + - deps: fresh@0.2.4 + * deps: vary@~1.0.0 + - Accept valid `Vary` header string as `field` + +3.16.10 / 2014-09-04 +==================== + + * deps: connect@2.25.10 + - deps: serve-static@~1.5.4 + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +3.16.9 / 2014-08-29 +=================== + + * deps: connect@2.25.9 + - deps: body-parser@~1.6.7 + - deps: qs@2.2.2 + +3.16.8 / 2014-08-27 +=================== + + * deps: connect@2.25.8 + - deps: body-parser@~1.6.6 + - deps: csurf@~1.4.1 + - deps: qs@2.2.0 + +3.16.7 / 2014-08-18 +=================== + + * deps: connect@2.25.7 + - deps: body-parser@~1.6.5 + - deps: express-session@~1.7.6 + - deps: morgan@~1.2.3 + - deps: serve-static@~1.5.3 + * deps: send@0.8.3 + - deps: destroy@1.0.3 + - deps: on-finished@2.1.0 + +3.16.6 / 2014-08-14 +=================== + + * deps: connect@2.25.6 + - deps: body-parser@~1.6.4 + - deps: qs@1.2.2 + - deps: serve-static@~1.5.2 + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +3.16.5 / 2014-08-11 +=================== + + * deps: connect@2.25.5 + - Fix backwards compatibility in `logger` + +3.16.4 / 2014-08-10 +=================== + + * Fix original URL parsing in `res.location` + * deps: connect@2.25.4 + - Fix `query` middleware breaking with argument + - deps: body-parser@~1.6.3 + - deps: compression@~1.0.11 + - deps: connect-timeout@~1.2.2 + - deps: express-session@~1.7.5 + - deps: method-override@~2.1.3 + - deps: on-headers@~1.0.0 + - deps: parseurl@~1.3.0 + - deps: qs@1.2.1 + - deps: response-time@~2.0.1 + - deps: serve-index@~1.1.6 + - deps: serve-static@~1.5.1 + * deps: parseurl@~1.3.0 + +3.16.3 / 2014-08-07 +=================== + + * deps: connect@2.25.3 + - deps: multiparty@3.3.2 + +3.16.2 / 2014-08-07 +=================== + + * deps: connect@2.25.2 + - deps: body-parser@~1.6.2 + - deps: qs@1.2.0 + +3.16.1 / 2014-08-06 +=================== + + * deps: connect@2.25.1 + - deps: body-parser@~1.6.1 + - deps: qs@1.1.0 + +3.16.0 / 2014-08-05 +=================== + + * deps: connect@2.25.0 + - deps: body-parser@~1.6.0 + - deps: compression@~1.0.10 + - deps: csurf@~1.4.0 + - deps: express-session@~1.7.4 + - deps: qs@1.0.2 + - deps: serve-static@~1.5.0 + * deps: send@0.8.1 + - Add `extensions` option + +3.15.3 / 2014-08-04 +=================== + + * fix `res.sendfile` regression for serving directory index files + * deps: connect@2.24.3 + - deps: serve-index@~1.1.5 + - deps: serve-static@~1.4.4 + * deps: send@0.7.4 + - Fix incorrect 403 on Windows and Node.js 0.11 + - Fix serving index files without root dir + +3.15.2 / 2014-07-27 +=================== + + * deps: connect@2.24.2 + - deps: body-parser@~1.5.2 + - deps: depd@0.4.4 + - deps: express-session@~1.7.2 + - deps: morgan@~1.2.2 + - deps: serve-static@~1.4.2 + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + * deps: send@0.7.2 + - deps: depd@0.4.4 + +3.15.1 / 2014-07-26 +=================== + + * deps: connect@2.24.1 + - deps: body-parser@~1.5.1 + - deps: depd@0.4.3 + - deps: express-session@~1.7.1 + - deps: morgan@~1.2.1 + - deps: serve-index@~1.1.4 + - deps: serve-static@~1.4.1 + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + * deps: send@0.7.1 + - deps: depd@0.4.3 + +3.15.0 / 2014-07-22 +=================== + + * Fix `req.protocol` for proxy-direct connections + * Pass options from `res.sendfile` to `send` + * deps: connect@2.24.0 + - deps: body-parser@~1.5.0 + - deps: compression@~1.0.9 + - deps: connect-timeout@~1.2.1 + - deps: debug@1.0.4 + - deps: depd@0.4.2 + - deps: express-session@~1.7.0 + - deps: finalhandler@0.1.0 + - deps: method-override@~2.1.2 + - deps: morgan@~1.2.0 + - deps: multiparty@3.3.1 + - deps: parseurl@~1.2.0 + - deps: serve-static@~1.4.0 + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - Cap `maxAge` value to 1 year + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +3.14.0 / 2014-07-11 +=================== + + * add explicit "Rosetta Flash JSONP abuse" protection + - previous versions are not vulnerable; this is just explicit protection + * deprecate `res.redirect(url, status)` -- use `res.redirect(status, url)` instead + * fix `res.send(status, num)` to send `num` as json (not error) + * remove unnecessary escaping when `res.jsonp` returns JSON response + * deps: basic-auth@1.0.0 + - support empty password + - support empty username + * deps: connect@2.23.0 + - deps: debug@1.0.3 + - deps: express-session@~1.6.4 + - deps: method-override@~2.1.0 + - deps: parseurl@~1.1.3 + - deps: serve-static@~1.3.1 + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + * deps: methods@1.1.0 + - add `CONNECT` + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +3.13.0 / 2014-07-03 +=================== + + * add deprecation message to `app.configure` + * add deprecation message to `req.auth` + * use `basic-auth` to parse `Authorization` header + * deps: connect@2.22.0 + - deps: csurf@~1.3.0 + - deps: express-session@~1.6.1 + - deps: multiparty@3.3.0 + - deps: serve-static@~1.3.0 + * deps: send@0.5.0 + - Accept string for `maxage` (converted by `ms`) + - Include link in default redirect response + +3.12.1 / 2014-06-26 +=================== + + * deps: connect@2.21.1 + - deps: cookie-parser@1.3.2 + - deps: cookie-signature@1.0.4 + - deps: express-session@~1.5.2 + - deps: type-is@~1.3.2 + * deps: cookie-signature@1.0.4 + - fix for timing attacks + +3.12.0 / 2014-06-21 +=================== + + * use `media-typer` to alter content-type charset + * deps: connect@2.21.0 + - deprecate `connect(middleware)` -- use `app.use(middleware)` instead + - deprecate `connect.createServer()` -- use `connect()` instead + - fix `res.setHeader()` patch to work with with get -> append -> set pattern + - deps: compression@~1.0.8 + - deps: errorhandler@~1.1.1 + - deps: express-session@~1.5.0 + - deps: serve-index@~1.1.3 + +3.11.0 / 2014-06-19 +=================== + + * deprecate things with `depd` module + * deps: buffer-crc32@0.2.3 + * deps: connect@2.20.2 + - deprecate `verify` option to `json` -- use `body-parser` npm module instead + - deprecate `verify` option to `urlencoded` -- use `body-parser` npm module instead + - deprecate things with `depd` module + - use `finalhandler` for final response handling + - use `media-typer` to parse `content-type` for charset + - deps: body-parser@1.4.3 + - deps: connect-timeout@1.1.1 + - deps: cookie-parser@1.3.1 + - deps: csurf@1.2.2 + - deps: errorhandler@1.1.0 + - deps: express-session@1.4.0 + - deps: multiparty@3.2.9 + - deps: serve-index@1.1.2 + - deps: type-is@1.3.1 + - deps: vhost@2.0.0 + +3.10.5 / 2014-06-11 +=================== + + * deps: connect@2.19.6 + - deps: body-parser@1.3.1 + - deps: compression@1.0.7 + - deps: debug@1.0.2 + - deps: serve-index@1.1.1 + - deps: serve-static@1.2.3 + * deps: debug@1.0.2 + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +3.10.4 / 2014-06-09 +=================== + + * deps: connect@2.19.5 + - fix "event emitter leak" warnings + - deps: csurf@1.2.1 + - deps: debug@1.0.1 + - deps: serve-static@1.2.2 + - deps: type-is@1.2.1 + * deps: debug@1.0.1 + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: finished@1.2.1 + - deps: debug@1.0.1 + +3.10.3 / 2014-06-05 +=================== + + * use `vary` module for `res.vary` + * deps: connect@2.19.4 + - deps: errorhandler@1.0.2 + - deps: method-override@2.0.2 + - deps: serve-favicon@2.0.1 + * deps: debug@1.0.0 + +3.10.2 / 2014-06-03 +=================== + + * deps: connect@2.19.3 + - deps: compression@1.0.6 + +3.10.1 / 2014-06-03 +=================== + + * deps: connect@2.19.2 + - deps: compression@1.0.4 + * deps: proxy-addr@1.0.1 + +3.10.0 / 2014-06-02 +=================== + + * deps: connect@2.19.1 + - deprecate `methodOverride()` -- use `method-override` npm module instead + - deps: body-parser@1.3.0 + - deps: method-override@2.0.1 + - deps: multiparty@3.2.8 + - deps: response-time@2.0.0 + - deps: serve-static@1.2.1 + * deps: methods@1.0.1 + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +3.9.0 / 2014-05-30 +================== + + * custom etag control with `app.set('etag', val)` + - `app.set('etag', function(body, encoding){ return '"etag"' })` custom etag generation + - `app.set('etag', 'weak')` weak tag + - `app.set('etag', 'strong')` strong etag + - `app.set('etag', false)` turn off + - `app.set('etag', true)` standard etag + * Include ETag in HEAD requests + * mark `res.send` ETag as weak and reduce collisions + * update connect to 2.18.0 + - deps: compression@1.0.3 + - deps: serve-index@1.1.0 + - deps: serve-static@1.2.0 + * update send to 0.4.0 + - Calculate ETag with md5 for reduced collisions + - Ignore stream errors after request ends + - deps: debug@0.8.1 + +3.8.1 / 2014-05-27 +================== + + * update connect to 2.17.3 + - deps: body-parser@1.2.2 + - deps: express-session@1.2.1 + - deps: method-override@1.0.2 + +3.8.0 / 2014-05-21 +================== + + * keep previous `Content-Type` for `res.jsonp` + * set proper `charset` in `Content-Type` for `res.send` + * update connect to 2.17.1 + - fix `res.charset` appending charset when `content-type` has one + - deps: express-session@1.2.0 + - deps: morgan@1.1.1 + - deps: serve-index@1.0.3 + +3.7.0 / 2014-05-18 +================== + + * proper proxy trust with `app.set('trust proxy', trust)` + - `app.set('trust proxy', 1)` trust first hop + - `app.set('trust proxy', 'loopback')` trust loopback addresses + - `app.set('trust proxy', '10.0.0.1')` trust single IP + - `app.set('trust proxy', '10.0.0.1/16')` trust subnet + - `app.set('trust proxy', '10.0.0.1, 10.0.0.2')` trust list + - `app.set('trust proxy', false)` turn off + - `app.set('trust proxy', true)` trust everything + * update connect to 2.16.2 + - deprecate `res.headerSent` -- use `res.headersSent` + - deprecate `res.on("header")` -- use on-headers module instead + - fix edge-case in `res.appendHeader` that would append in wrong order + - json: use body-parser + - urlencoded: use body-parser + - dep: bytes@1.0.0 + - dep: cookie-parser@1.1.0 + - dep: csurf@1.2.0 + - dep: express-session@1.1.0 + - dep: method-override@1.0.1 + +3.6.0 / 2014-05-09 +================== + + * deprecate `app.del()` -- use `app.delete()` instead + * deprecate `res.json(obj, status)` -- use `res.json(status, obj)` instead + - the edge-case `res.json(status, num)` requires `res.status(status).json(num)` + * deprecate `res.jsonp(obj, status)` -- use `res.jsonp(status, obj)` instead + - the edge-case `res.jsonp(status, num)` requires `res.status(status).jsonp(num)` + * support PURGE method + - add `app.purge` + - add `router.purge` + - include PURGE in `app.all` + * update connect to 2.15.0 + * Add `res.appendHeader` + * Call error stack even when response has been sent + * Patch `res.headerSent` to return Boolean + * Patch `res.headersSent` for node.js 0.8 + * Prevent default 404 handler after response sent + * dep: compression@1.0.2 + * dep: connect-timeout@1.1.0 + * dep: debug@^0.8.0 + * dep: errorhandler@1.0.1 + * dep: express-session@1.0.4 + * dep: morgan@1.0.1 + * dep: serve-favicon@2.0.0 + * dep: serve-index@1.0.2 + * update debug to 0.8.0 + * add `enable()` method + * change from stderr to stdout + * update methods to 1.0.0 + - add PURGE + * update mkdirp to 0.5.0 + +3.5.3 / 2014-05-08 +================== + + * fix `req.host` for IPv6 literals + * fix `res.jsonp` error if callback param is object + +3.5.2 / 2014-04-24 +================== + + * update connect to 2.14.5 + * update cookie to 0.1.2 + * update mkdirp to 0.4.0 + * update send to 0.3.0 + +3.5.1 / 2014-03-25 +================== + + * pin less-middleware in generated app + +3.5.0 / 2014-03-06 +================== + + * bump deps + +3.4.8 / 2014-01-13 +================== + + * prevent incorrect automatic OPTIONS responses #1868 @dpatti + * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi + * throw 400 in case of malformed paths @rlidwka + +3.4.7 / 2013-12-10 +================== + + * update connect + +3.4.6 / 2013-12-01 +================== + + * update connect (raw-body) + +3.4.5 / 2013-11-27 +================== + + * update connect + * res.location: remove leading ./ #1802 @kapouer + * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra + * res.send: always send ETag when content-length > 0 + * router: add Router.all() method + +3.4.4 / 2013-10-29 +================== + + * update connect + * update supertest + * update methods + * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 + +3.4.3 / 2013-10-23 +================== + + * update connect + +3.4.2 / 2013-10-18 +================== + + * update connect + * downgrade commander + +3.4.1 / 2013-10-15 +================== + + * update connect + * update commander + * jsonp: check if callback is a function + * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) + * res.format: now includes charset @1747 (@sorribas) + * res.links: allow multiple calls @1746 (@sorribas) + +3.4.0 / 2013-09-07 +================== + + * add res.vary(). Closes #1682 + * update connect + +3.3.8 / 2013-09-02 +================== + + * update connect + +3.3.7 / 2013-08-28 +================== + + * update connect + +3.3.6 / 2013-08-27 +================== + + * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) + * add: req.accepts take an argument list + +3.3.4 / 2013-07-08 +================== + + * update send and connect + +3.3.3 / 2013-07-04 +================== + + * update connect + +3.3.2 / 2013-07-03 +================== + + * update connect + * update send + * remove .version export + +3.3.1 / 2013-06-27 +================== + + * update connect + +3.3.0 / 2013-06-26 +================== + + * update connect + * add support for multiple X-Forwarded-Proto values. Closes #1646 + * change: remove charset from json responses. Closes #1631 + * change: return actual booleans from req.accept* functions + * fix jsonp callback array throw + +3.2.6 / 2013-06-02 +================== + + * update connect + +3.2.5 / 2013-05-21 +================== + + * update connect + * update node-cookie + * add: throw a meaningful error when there is no default engine + * change generation of ETags with res.send() to GET requests only. Closes #1619 + +3.2.4 / 2013-05-09 +================== + + * fix `req.subdomains` when no Host is present + * fix `req.host` when no Host is present, return undefined + +3.2.3 / 2013-05-07 +================== + + * update connect / qs + +3.2.2 / 2013-05-03 +================== + + * update qs + +3.2.1 / 2013-04-29 +================== + + * add app.VERB() paths array deprecation warning + * update connect + * update qs and remove all ~ semver crap + * fix: accept number as value of Signed Cookie + +3.2.0 / 2013-04-15 +================== + + * add "view" constructor setting to override view behaviour + * add req.acceptsEncoding(name) + * add req.acceptedEncodings + * revert cookie signature change causing session race conditions + * fix sorting of Accept values of the same quality + +3.1.2 / 2013-04-12 +================== + + * add support for custom Accept parameters + * update cookie-signature + +3.1.1 / 2013-04-01 +================== + + * add X-Forwarded-Host support to `req.host` + * fix relative redirects + * update mkdirp + * update buffer-crc32 + * remove legacy app.configure() method from app template. + +3.1.0 / 2013-01-25 +================== + + * add support for leading "." in "view engine" setting + * add array support to `res.set()` + * add node 0.8.x to travis.yml + * add "subdomain offset" setting for tweaking `req.subdomains` + * add `res.location(url)` implementing `res.redirect()`-like setting of Location + * use app.get() for x-powered-by setting for inheritance + * fix colons in passwords for `req.auth` + +3.0.6 / 2013-01-04 +================== + + * add http verb methods to Router + * update connect + * fix mangling of the `res.cookie()` options object + * fix jsonp whitespace escape. Closes #1132 + +3.0.5 / 2012-12-19 +================== + + * add throwing when a non-function is passed to a route + * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses + * revert "add 'etag' option" + +3.0.4 / 2012-12-05 +================== + + * add 'etag' option to disable `res.send()` Etags + * add escaping of urls in text/plain in `res.redirect()` + for old browsers interpreting as html + * change crc32 module for a more liberal license + * update connect + +3.0.3 / 2012-11-13 +================== + + * update connect + * update cookie module + * fix cookie max-age + +3.0.2 / 2012-11-08 +================== + + * add OPTIONS to cors example. Closes #1398 + * fix route chaining regression. Closes #1397 + +3.0.1 / 2012-11-01 +================== + + * update connect + +3.0.0 / 2012-10-23 +================== + + * add `make clean` + * add "Basic" check to req.auth + * add `req.auth` test coverage + * add cb && cb(payload) to `res.jsonp()`. Closes #1374 + * add backwards compat for `res.redirect()` status. Closes #1336 + * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 + * update connect + * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 + * remove non-primitive string support for `res.send()` + * fix view-locals example. Closes #1370 + * fix route-separation example + +3.0.0rc5 / 2012-09-18 +================== + + * update connect + * add redis search example + * add static-files example + * add "x-powered-by" setting (`app.disable('x-powered-by')`) + * add "application/octet-stream" redirect Accept test case. Closes #1317 + +3.0.0rc4 / 2012-08-30 +================== + + * add `res.jsonp()`. Closes #1307 + * add "verbose errors" option to error-pages example + * add another route example to express(1) so people are not so confused + * add redis online user activity tracking example + * update connect dep + * fix etag quoting. Closes #1310 + * fix error-pages 404 status + * fix jsonp callback char restrictions + * remove old OPTIONS default response + +3.0.0rc3 / 2012-08-13 +================== + + * update connect dep + * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] + * fix `res.render()` clobbering of "locals" + +3.0.0rc2 / 2012-08-03 +================== + + * add CORS example + * update connect dep + * deprecate `.createServer()` & remove old stale examples + * fix: escape `res.redirect()` link + * fix vhost example + +3.0.0rc1 / 2012-07-24 +================== + + * add more examples to view-locals + * add scheme-relative redirects (`res.redirect("//foo.com")`) support + * update cookie dep + * update connect dep + * update send dep + * fix `express(1)` -h flag, use -H for hogan. Closes #1245 + * fix `res.sendfile()` socket error handling regression + +3.0.0beta7 / 2012-07-16 +================== + + * update connect dep for `send()` root normalization regression + +3.0.0beta6 / 2012-07-13 +================== + + * add `err.view` property for view errors. Closes #1226 + * add "jsonp callback name" setting + * add support for "/foo/:bar*" non-greedy matches + * change `res.sendfile()` to use `send()` module + * change `res.send` to use "response-send" module + * remove `app.locals.use` and `res.locals.use`, use regular middleware + +3.0.0beta5 / 2012-07-03 +================== + + * add "make check" support + * add route-map example + * add `res.json(obj, status)` support back for BC + * add "methods" dep, remove internal methods module + * update connect dep + * update auth example to utilize cores pbkdf2 + * updated tests to use "supertest" + +3.0.0beta4 / 2012-06-25 +================== + + * Added `req.auth` + * Added `req.range(size)` + * Added `res.links(obj)` + * Added `res.send(body, status)` support back for backwards compat + * Added `.default()` support to `res.format()` + * Added 2xx / 304 check to `req.fresh` + * Revert "Added + support to the router" + * Fixed `res.send()` freshness check, respect res.statusCode + +3.0.0beta3 / 2012-06-15 +================== + + * Added hogan `--hjs` to express(1) [nullfirm] + * Added another example to content-negotiation + * Added `fresh` dep + * Changed: `res.send()` always checks freshness + * Fixed: expose connects mime module. Closes #1165 + +3.0.0beta2 / 2012-06-06 +================== + + * Added `+` support to the router + * Added `req.host` + * Changed `req.param()` to check route first + * Update connect dep + +3.0.0beta1 / 2012-06-01 +================== + + * Added `res.format()` callback to override default 406 behaviour + * Fixed `res.redirect()` 406. Closes #1154 + +3.0.0alpha5 / 2012-05-30 +================== + + * Added `req.ip` + * Added `{ signed: true }` option to `res.cookie()` + * Removed `res.signedCookie()` + * Changed: dont reverse `req.ips` + * Fixed "trust proxy" setting check for `req.ips` + +3.0.0alpha4 / 2012-05-09 +================== + + * Added: allow `[]` in jsonp callback. Closes #1128 + * Added `PORT` env var support in generated template. Closes #1118 [benatkin] + * Updated: connect 2.2.2 + +3.0.0alpha3 / 2012-05-04 +================== + + * Added public `app.routes`. Closes #887 + * Added _view-locals_ example + * Added _mvc_ example + * Added `res.locals.use()`. Closes #1120 + * Added conditional-GET support to `res.send()` + * Added: coerce `res.set()` values to strings + * Changed: moved `static()` in generated apps below router + * Changed: `res.send()` only set ETag when not previously set + * Changed connect 2.2.1 dep + * Changed: `make test` now runs unit / acceptance tests + * Fixed req/res proto inheritance + +3.0.0alpha2 / 2012-04-26 +================== + + * Added `make benchmark` back + * Added `res.send()` support for `String` objects + * Added client-side data exposing example + * Added `res.header()` and `req.header()` aliases for BC + * Added `express.createServer()` for BC + * Perf: memoize parsed urls + * Perf: connect 2.2.0 dep + * Changed: make `expressInit()` middleware self-aware + * Fixed: use app.get() for all core settings + * Fixed redis session example + * Fixed session example. Closes #1105 + * Fixed generated express dep. Closes #1078 + +3.0.0alpha1 / 2012-04-15 +================== + + * Added `app.locals.use(callback)` + * Added `app.locals` object + * Added `app.locals(obj)` + * Added `res.locals` object + * Added `res.locals(obj)` + * Added `res.format()` for content-negotiation + * Added `app.engine()` + * Added `res.cookie()` JSON cookie support + * Added "trust proxy" setting + * Added `req.subdomains` + * Added `req.protocol` + * Added `req.secure` + * Added `req.path` + * Added `req.ips` + * Added `req.fresh` + * Added `req.stale` + * Added comma-delimited / array support for `req.accepts()` + * Added debug instrumentation + * Added `res.set(obj)` + * Added `res.set(field, value)` + * Added `res.get(field)` + * Added `app.get(setting)`. Closes #842 + * Added `req.acceptsLanguage()` + * Added `req.acceptsCharset()` + * Added `req.accepted` + * Added `req.acceptedLanguages` + * Added `req.acceptedCharsets` + * Added "json replacer" setting + * Added "json spaces" setting + * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 + * Added `--less` support to express(1) + * Added `express.response` prototype + * Added `express.request` prototype + * Added `express.application` prototype + * Added `app.path()` + * Added `app.render()` + * Added `res.type()` to replace `res.contentType()` + * Changed: `res.redirect()` to add relative support + * Changed: enable "jsonp callback" by default + * Changed: renamed "case sensitive routes" to "case sensitive routing" + * Rewrite of all tests with mocha + * Removed "root" setting + * Removed `res.redirect('home')` support + * Removed `req.notify()` + * Removed `app.register()` + * Removed `app.redirect()` + * Removed `app.is()` + * Removed `app.helpers()` + * Removed `app.dynamicHelpers()` + * Fixed `res.sendfile()` with non-GET. Closes #723 + * Fixed express(1) public dir for windows. Closes #866 + +2.5.9/ 2012-04-02 +================== + + * Added support for PURGE request method [pbuyle] + * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] + +2.5.8 / 2012-02-08 +================== + + * Update mkdirp dep. Closes #991 + +2.5.7 / 2012-02-06 +================== + + * Fixed `app.all` duplicate DELETE requests [mscdex] + +2.5.6 / 2012-01-13 +================== + + * Updated hamljs dev dep. Closes #953 + +2.5.5 / 2012-01-08 +================== + + * Fixed: set `filename` on cached templates [matthewleon] + +2.5.4 / 2012-01-02 +================== + + * Fixed `express(1)` eol on 0.4.x. Closes #947 + +2.5.3 / 2011-12-30 +================== + + * Fixed `req.is()` when a charset is present + +2.5.2 / 2011-12-10 +================== + + * Fixed: express(1) LF -> CRLF for windows + +2.5.1 / 2011-11-17 +================== + + * Changed: updated connect to 1.8.x + * Removed sass.js support from express(1) + +2.5.0 / 2011-10-24 +================== + + * Added ./routes dir for generated app by default + * Added npm install reminder to express(1) app gen + * Added 0.5.x support + * Removed `make test-cov` since it wont work with node 0.5.x + * Fixed express(1) public dir for windows. Closes #866 + +2.4.7 / 2011-10-05 +================== + + * Added mkdirp to express(1). Closes #795 + * Added simple _json-config_ example + * Added shorthand for the parsed request's pathname via `req.path` + * Changed connect dep to 1.7.x to fix npm issue... + * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] + * Fixed `req.flash()`, only escape args + * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] + +2.4.6 / 2011-08-22 +================== + + * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] + +2.4.5 / 2011-08-19 +================== + + * Added support for routes to handle errors. Closes #809 + * Added `app.routes.all()`. Closes #803 + * Added "basepath" setting to work in conjunction with reverse proxies etc. + * Refactored `Route` to use a single array of callbacks + * Added support for multiple callbacks for `app.param()`. Closes #801 +Closes #805 + * Changed: removed .call(self) for route callbacks + * Dependency: `qs >= 0.3.1` + * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 + +2.4.4 / 2011-08-05 +================== + + * Fixed `res.header()` intention of a set, even when `undefined` + * Fixed `*`, value no longer required + * Fixed `res.send(204)` support. Closes #771 + +2.4.3 / 2011-07-14 +================== + + * Added docs for `status` option special-case. Closes #739 + * Fixed `options.filename`, exposing the view path to template engines + +2.4.2. / 2011-07-06 +================== + + * Revert "removed jsonp stripping" for XSS + +2.4.1 / 2011-07-06 +================== + + * Added `res.json()` JSONP support. Closes #737 + * Added _extending-templates_ example. Closes #730 + * Added "strict routing" setting for trailing slashes + * Added support for multiple envs in `app.configure()` calls. Closes #735 + * Changed: `res.send()` using `res.json()` + * Changed: when cookie `path === null` don't default it + * Changed; default cookie path to "home" setting. Closes #731 + * Removed _pids/logs_ creation from express(1) + +2.4.0 / 2011-06-28 +================== + + * Added chainable `res.status(code)` + * Added `res.json()`, an explicit version of `res.send(obj)` + * Added simple web-service example + +2.3.12 / 2011-06-22 +================== + + * \#express is now on freenode! come join! + * Added `req.get(field, param)` + * Added links to Japanese documentation, thanks @hideyukisaito! + * Added; the `express(1)` generated app outputs the env + * Added `content-negotiation` example + * Dependency: connect >= 1.5.1 < 2.0.0 + * Fixed view layout bug. Closes #720 + * Fixed; ignore body on 304. Closes #701 + +2.3.11 / 2011-06-04 +================== + + * Added `npm test` + * Removed generation of dummy test file from `express(1)` + * Fixed; `express(1)` adds express as a dep + * Fixed; prune on `prepublish` + +2.3.10 / 2011-05-27 +================== + + * Added `req.route`, exposing the current route + * Added _package.json_ generation support to `express(1)` + * Fixed call to `app.param()` function for optional params. Closes #682 + +2.3.9 / 2011-05-25 +================== + + * Fixed bug-ish with `../' in `res.partial()` calls + +2.3.8 / 2011-05-24 +================== + + * Fixed `app.options()` + +2.3.7 / 2011-05-23 +================== + + * Added route `Collection`, ex: `app.get('/user/:id').remove();` + * Added support for `app.param(fn)` to define param logic + * Removed `app.param()` support for callback with return value + * Removed module.parent check from express(1) generated app. Closes #670 + * Refactored router. Closes #639 + +2.3.6 / 2011-05-20 +================== + + * Changed; using devDependencies instead of git submodules + * Fixed redis session example + * Fixed markdown example + * Fixed view caching, should not be enabled in development + +2.3.5 / 2011-05-20 +================== + + * Added export `.view` as alias for `.View` + +2.3.4 / 2011-05-08 +================== + + * Added `./examples/say` + * Fixed `res.sendfile()` bug preventing the transfer of files with spaces + +2.3.3 / 2011-05-03 +================== + + * Added "case sensitive routes" option. + * Changed; split methods supported per rfc [slaskis] + * Fixed route-specific middleware when using the same callback function several times + +2.3.2 / 2011-04-27 +================== + + * Fixed view hints + +2.3.1 / 2011-04-26 +================== + + * Added `app.match()` as `app.match.all()` + * Added `app.lookup()` as `app.lookup.all()` + * Added `app.remove()` for `app.remove.all()` + * Added `app.remove.VERB()` + * Fixed template caching collision issue. Closes #644 + * Moved router over from connect and started refactor + +2.3.0 / 2011-04-25 +================== + + * Added options support to `res.clearCookie()` + * Added `res.helpers()` as alias of `res.locals()` + * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` + * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] + * Renamed "cache views" to "view cache". Closes #628 + * Fixed caching of views when using several apps. Closes #637 + * Fixed gotcha invoking `app.param()` callbacks once per route middleware. +Closes #638 + * Fixed partial lookup precedence. Closes #631 +Shaw] + +2.2.2 / 2011-04-12 +================== + + * Added second callback support for `res.download()` connection errors + * Fixed `filename` option passing to template engine + +2.2.1 / 2011-04-04 +================== + + * Added `layout(path)` helper to change the layout within a view. Closes #610 + * Fixed `partial()` collection object support. + Previously only anything with `.length` would work. + When `.length` is present one must still be aware of holes, + however now `{ collection: {foo: 'bar'}}` is valid, exposes + `keyInCollection` and `keysInCollection`. + + * Performance improved with better view caching + * Removed `request` and `response` locals + * Changed; errorHandler page title is now `Express` instead of `Connect` + +2.2.0 / 2011-03-30 +================== + + * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 + * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 + * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. + * Dependency `connect >= 1.2.0` + +2.1.1 / 2011-03-29 +================== + + * Added; expose `err.view` object when failing to locate a view + * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] + * Fixed; `res.send(undefined)` responds with 204 [aheckmann] + +2.1.0 / 2011-03-24 +================== + + * Added `/_?` partial lookup support. Closes #447 + * Added `request`, `response`, and `app` local variables + * Added `settings` local variable, containing the app's settings + * Added `req.flash()` exception if `req.session` is not available + * Added `res.send(bool)` support (json response) + * Fixed stylus example for latest version + * Fixed; wrap try/catch around `res.render()` + +2.0.0 / 2011-03-17 +================== + + * Fixed up index view path alternative. + * Changed; `res.locals()` without object returns the locals + +2.0.0rc3 / 2011-03-17 +================== + + * Added `res.locals(obj)` to compliment `res.local(key, val)` + * Added `res.partial()` callback support + * Fixed recursive error reporting issue in `res.render()` + +2.0.0rc2 / 2011-03-17 +================== + + * Changed; `partial()` "locals" are now optional + * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] + * Fixed .filename view engine option [reported by drudge] + * Fixed blog example + * Fixed `{req,res}.app` reference when mounting [Ben Weaver] + +2.0.0rc / 2011-03-14 +================== + + * Fixed; expose `HTTPSServer` constructor + * Fixed express(1) default test charset. Closes #579 [reported by secoif] + * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] + +2.0.0beta3 / 2011-03-09 +================== + + * Added support for `res.contentType()` literal + The original `res.contentType('.json')`, + `res.contentType('application/json')`, and `res.contentType('json')` + will work now. + * Added `res.render()` status option support back + * Added charset option for `res.render()` + * Added `.charset` support (via connect 1.0.4) + * Added view resolution hints when in development and a lookup fails + * Added layout lookup support relative to the page view. + For example while rendering `./views/user/index.jade` if you create + `./views/user/layout.jade` it will be used in favour of the root layout. + * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] + * Fixed; default `res.send()` string charset to utf8 + * Removed `Partial` constructor (not currently used) + +2.0.0beta2 / 2011-03-07 +================== + + * Added res.render() `.locals` support back to aid in migration process + * Fixed flash example + +2.0.0beta / 2011-03-03 +================== + + * Added HTTPS support + * Added `res.cookie()` maxAge support + * Added `req.header()` _Referrer_ / _Referer_ special-case, either works + * Added mount support for `res.redirect()`, now respects the mount-point + * Added `union()` util, taking place of `merge(clone())` combo + * Added stylus support to express(1) generated app + * Added secret to session middleware used in examples and generated app + * Added `res.local(name, val)` for progressive view locals + * Added default param support to `req.param(name, default)` + * Added `app.disabled()` and `app.enabled()` + * Added `app.register()` support for omitting leading ".", either works + * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 + * Added `app.param()` to map route params to async/sync logic + * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 + * Added extname with no leading "." support to `res.contentType()` + * Added `cache views` setting, defaulting to enabled in "production" env + * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. + * Added `req.accepts()` support for extensions + * Changed; `res.download()` and `res.sendfile()` now utilize Connect's + static file server `connect.static.send()`. + * Changed; replaced `connect.utils.mime()` with npm _mime_ module + * Changed; allow `req.query` to be pre-defined (via middleware or other parent + * Changed view partial resolution, now relative to parent view + * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. + * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 + * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` + * Fixed; using _qs_ module instead of _querystring_ + * Fixed; strip unsafe chars from jsonp callbacks + * Removed "stream threshold" setting + +1.0.8 / 2011-03-01 +================== + + * Allow `req.query` to be pre-defined (via middleware or other parent app) + * "connect": ">= 0.5.0 < 1.0.0". Closes #547 + * Removed the long deprecated __EXPRESS_ENV__ support + +1.0.7 / 2011-02-07 +================== + + * Fixed `render()` setting inheritance. + Mounted apps would not inherit "view engine" + +1.0.6 / 2011-02-07 +================== + + * Fixed `view engine` setting bug when period is in dirname + +1.0.5 / 2011-02-05 +================== + + * Added secret to generated app `session()` call + +1.0.4 / 2011-02-05 +================== + + * Added `qs` dependency to _package.json_ + * Fixed namespaced `require()`s for latest connect support + +1.0.3 / 2011-01-13 +================== + + * Remove unsafe characters from JSONP callback names [Ryan Grove] + +1.0.2 / 2011-01-10 +================== + + * Removed nested require, using `connect.router` + +1.0.1 / 2010-12-29 +================== + + * Fixed for middleware stacked via `createServer()` + previously the `foo` middleware passed to `createServer(foo)` + would not have access to Express methods such as `res.send()` + or props like `req.query` etc. + +1.0.0 / 2010-11-16 +================== + + * Added; deduce partial object names from the last segment. + For example by default `partial('forum/post', postObject)` will + give you the _post_ object, providing a meaningful default. + * Added http status code string representation to `res.redirect()` body + * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. + * Added `req.is()` to aid in content negotiation + * Added partial local inheritance [suggested by masylum]. Closes #102 + providing access to parent template locals. + * Added _-s, --session[s]_ flag to express(1) to add session related middleware + * Added _--template_ flag to express(1) to specify the + template engine to use. + * Added _--css_ flag to express(1) to specify the + stylesheet engine to use (or just plain css by default). + * Added `app.all()` support [thanks aheckmann] + * Added partial direct object support. + You may now `partial('user', user)` providing the "user" local, + vs previously `partial('user', { object: user })`. + * Added _route-separation_ example since many people question ways + to do this with CommonJS modules. Also view the _blog_ example for + an alternative. + * Performance; caching view path derived partial object names + * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 + * Fixed jsonp support; _text/javascript_ as per mailinglist discussion + +1.0.0rc4 / 2010-10-14 +================== + + * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 + * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) + * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] + * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] + * Added `partial()` support for array-like collections. Closes #434 + * Added support for swappable querystring parsers + * Added session usage docs. Closes #443 + * Added dynamic helper caching. Closes #439 [suggested by maritz] + * Added authentication example + * Added basic Range support to `res.sendfile()` (and `res.download()` etc) + * Changed; `express(1)` generated app using 2 spaces instead of 4 + * Default env to "development" again [aheckmann] + * Removed _context_ option is no more, use "scope" + * Fixed; exposing _./support_ libs to examples so they can run without installs + * Fixed mvc example + +1.0.0rc3 / 2010-09-20 +================== + + * Added confirmation for `express(1)` app generation. Closes #391 + * Added extending of flash formatters via `app.flashFormatters` + * Added flash formatter support. Closes #411 + * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" + * Added _stream threshold_ setting for `res.sendfile()` + * Added `res.send()` __HEAD__ support + * Added `res.clearCookie()` + * Added `res.cookie()` + * Added `res.render()` headers option + * Added `res.redirect()` response bodies + * Added `res.render()` status option support. Closes #425 [thanks aheckmann] + * Fixed `res.sendfile()` responding with 403 on malicious path + * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ + * Fixed; mounted apps settings now inherit from parent app [aheckmann] + * Fixed; stripping Content-Length / Content-Type when 204 + * Fixed `res.send()` 204. Closes #419 + * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 + * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] + + +1.0.0rc2 / 2010-08-17 +================== + + * Added `app.register()` for template engine mapping. Closes #390 + * Added `res.render()` callback support as second argument (no options) + * Added callback support to `res.download()` + * Added callback support for `res.sendfile()` + * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` + * Added "partials" setting to docs + * Added default expresso tests to `express(1)` generated app. Closes #384 + * Fixed `res.sendfile()` error handling, defer via `next()` + * Fixed `res.render()` callback when a layout is used [thanks guillermo] + * Fixed; `make install` creating ~/.node_libraries when not present + * Fixed issue preventing error handlers from being defined anywhere. Closes #387 + +1.0.0rc / 2010-07-28 +================== + + * Added mounted hook. Closes #369 + * Added connect dependency to _package.json_ + + * Removed "reload views" setting and support code + development env never caches, production always caches. + + * Removed _param_ in route callbacks, signature is now + simply (req, res, next), previously (req, res, params, next). + Use _req.params_ for path captures, _req.query_ for GET params. + + * Fixed "home" setting + * Fixed middleware/router precedence issue. Closes #366 + * Fixed; _configure()_ callbacks called immediately. Closes #368 + +1.0.0beta2 / 2010-07-23 +================== + + * Added more examples + * Added; exporting `Server` constructor + * Added `Server#helpers()` for view locals + * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 + * Added support for absolute view paths + * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 + * Added Guillermo Rauch to the contributor list + * Added support for "as" for non-collection partials. Closes #341 + * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] + * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] + * Fixed instanceof `Array` checks, now `Array.isArray()` + * Fixed express(1) expansion of public dirs. Closes #348 + * Fixed middleware precedence. Closes #345 + * Fixed view watcher, now async [thanks aheckmann] + +1.0.0beta / 2010-07-15 +================== + + * Re-write + - much faster + - much lighter + - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs + +0.14.0 / 2010-06-15 +================== + + * Utilize relative requires + * Added Static bufferSize option [aheckmann] + * Fixed caching of view and partial subdirectories [aheckmann] + * Fixed mime.type() comments now that ".ext" is not supported + * Updated haml submodule + * Updated class submodule + * Removed bin/express + +0.13.0 / 2010-06-01 +================== + + * Added node v0.1.97 compatibility + * Added support for deleting cookies via Request#cookie('key', null) + * Updated haml submodule + * Fixed not-found page, now using using charset utf-8 + * Fixed show-exceptions page, now using using charset utf-8 + * Fixed view support due to fs.readFile Buffers + * Changed; mime.type() no longer accepts ".type" due to node extname() changes + +0.12.0 / 2010-05-22 +================== + + * Added node v0.1.96 compatibility + * Added view `helpers` export which act as additional local variables + * Updated haml submodule + * Changed ETag; removed inode, modified time only + * Fixed LF to CRLF for setting multiple cookies + * Fixed cookie complation; values are now urlencoded + * Fixed cookies parsing; accepts quoted values and url escaped cookies + +0.11.0 / 2010-05-06 +================== + + * Added support for layouts using different engines + - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) + - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' + - this.render('page.html.haml', { layout: false }) // no layout + * Updated ext submodule + * Updated haml submodule + * Fixed EJS partial support by passing along the context. Issue #307 + +0.10.1 / 2010-05-03 +================== + + * Fixed binary uploads. + +0.10.0 / 2010-04-30 +================== + + * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s + encoding is set to 'utf8' or 'utf-8'. + * Added "encoding" option to Request#render(). Closes #299 + * Added "dump exceptions" setting, which is enabled by default. + * Added simple ejs template engine support + * Added error response support for text/plain, application/json. Closes #297 + * Added callback function param to Request#error() + * Added Request#sendHead() + * Added Request#stream() + * Added support for Request#respond(304, null) for empty response bodies + * Added ETag support to Request#sendfile() + * Added options to Request#sendfile(), passed to fs.createReadStream() + * Added filename arg to Request#download() + * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request + * Performance enhanced by preventing several calls to toLowerCase() in Router#match() + * Changed; Request#sendfile() now streams + * Changed; Renamed Request#halt() to Request#respond(). Closes #289 + * Changed; Using sys.inspect() instead of JSON.encode() for error output + * Changed; run() returns the http.Server instance. Closes #298 + * Changed; Defaulting Server#host to null (INADDR_ANY) + * Changed; Logger "common" format scale of 0.4f + * Removed Logger "request" format + * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found + * Fixed several issues with http client + * Fixed Logger Content-Length output + * Fixed bug preventing Opera from retaining the generated session id. Closes #292 + +0.9.0 / 2010-04-14 +================== + + * Added DSL level error() route support + * Added DSL level notFound() route support + * Added Request#error() + * Added Request#notFound() + * Added Request#render() callback function. Closes #258 + * Added "max upload size" setting + * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 + * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js + * Added callback function support to Request#halt() as 3rd/4th arg + * Added preprocessing of route param wildcards using param(). Closes #251 + * Added view partial support (with collections etc) + * Fixed bug preventing falsey params (such as ?page=0). Closes #286 + * Fixed setting of multiple cookies. Closes #199 + * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) + * Changed; session cookie is now httpOnly + * Changed; Request is no longer global + * Changed; Event is no longer global + * Changed; "sys" module is no longer global + * Changed; moved Request#download to Static plugin where it belongs + * Changed; Request instance created before body parsing. Closes #262 + * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 + * Changed; Pre-caching view partials in memory when "cache view partials" is enabled + * Updated support to node --version 0.1.90 + * Updated dependencies + * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) + * Removed utils.mixin(); use Object#mergeDeep() + +0.8.0 / 2010-03-19 +================== + + * Added coffeescript example app. Closes #242 + * Changed; cache api now async friendly. Closes #240 + * Removed deprecated 'express/static' support. Use 'express/plugins/static' + +0.7.6 / 2010-03-19 +================== + + * Added Request#isXHR. Closes #229 + * Added `make install` (for the executable) + * Added `express` executable for setting up simple app templates + * Added "GET /public/*" to Static plugin, defaulting to /public + * Added Static plugin + * Fixed; Request#render() only calls cache.get() once + * Fixed; Namespacing View caches with "view:" + * Fixed; Namespacing Static caches with "static:" + * Fixed; Both example apps now use the Static plugin + * Fixed set("views"). Closes #239 + * Fixed missing space for combined log format + * Deprecated Request#sendfile() and 'express/static' + * Removed Server#running + +0.7.5 / 2010-03-16 +================== + + * Added Request#flash() support without args, now returns all flashes + * Updated ext submodule + +0.7.4 / 2010-03-16 +================== + + * Fixed session reaper + * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) + +0.7.3 / 2010-03-16 +================== + + * Added package.json + * Fixed requiring of haml / sass due to kiwi removal + +0.7.2 / 2010-03-16 +================== + + * Fixed GIT submodules (HAH!) + +0.7.1 / 2010-03-16 +================== + + * Changed; Express now using submodules again until a PM is adopted + * Changed; chat example using millisecond conversions from ext + +0.7.0 / 2010-03-15 +================== + + * Added Request#pass() support (finds the next matching route, or the given path) + * Added Logger plugin (default "common" format replaces CommonLogger) + * Removed Profiler plugin + * Removed CommonLogger plugin + +0.6.0 / 2010-03-11 +================== + + * Added seed.yml for kiwi package management support + * Added HTTP client query string support when method is GET. Closes #205 + + * Added support for arbitrary view engines. + For example "foo.engine.html" will now require('engine'), + the exports from this module are cached after the first require(). + + * Added async plugin support + + * Removed usage of RESTful route funcs as http client + get() etc, use http.get() and friends + + * Removed custom exceptions + +0.5.0 / 2010-03-10 +================== + + * Added ext dependency (library of js extensions) + * Removed extname() / basename() utils. Use path module + * Removed toArray() util. Use arguments.values + * Removed escapeRegexp() util. Use RegExp.escape() + * Removed process.mixin() dependency. Use utils.mixin() + * Removed Collection + * Removed ElementCollection + * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) + +0.4.0 / 2010-02-11 +================== + + * Added flash() example to sample upload app + * Added high level restful http client module (express/http) + * Changed; RESTful route functions double as HTTP clients. Closes #69 + * Changed; throwing error when routes are added at runtime + * Changed; defaulting render() context to the current Request. Closes #197 + * Updated haml submodule + +0.3.0 / 2010-02-11 +================== + + * Updated haml / sass submodules. Closes #200 + * Added flash message support. Closes #64 + * Added accepts() now allows multiple args. fixes #117 + * Added support for plugins to halt. Closes #189 + * Added alternate layout support. Closes #119 + * Removed Route#run(). Closes #188 + * Fixed broken specs due to use(Cookie) missing + +0.2.1 / 2010-02-05 +================== + + * Added "plot" format option for Profiler (for gnuplot processing) + * Added request number to Profiler plugin + * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 + * Fixed issue with routes not firing when not files are present. Closes #184 + * Fixed process.Promise -> events.Promise + +0.2.0 / 2010-02-03 +================== + + * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 + * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 + * Added expiration support to cache api with reaper. Closes #133 + * Added cache Store.Memory#reap() + * Added Cache; cache api now uses first class Cache instances + * Added abstract session Store. Closes #172 + * Changed; cache Memory.Store#get() utilizing Collection + * Renamed MemoryStore -> Store.Memory + * Fixed use() of the same plugin several time will always use latest options. Closes #176 + +0.1.0 / 2010-02-03 +================== + + * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context + * Updated node support to 0.1.27 Closes #169 + * Updated dirname(__filename) -> __dirname + * Updated libxmljs support to v0.2.0 + * Added session support with memory store / reaping + * Added quick uid() helper + * Added multi-part upload support + * Added Sass.js support / submodule + * Added production env caching view contents and static files + * Added static file caching. Closes #136 + * Added cache plugin with memory stores + * Added support to StaticFile so that it works with non-textual files. + * Removed dirname() helper + * Removed several globals (now their modules must be required) + +0.0.2 / 2010-01-10 +================== + + * Added view benchmarks; currently haml vs ejs + * Added Request#attachment() specs. Closes #116 + * Added use of node's parseQuery() util. Closes #123 + * Added `make init` for submodules + * Updated Haml + * Updated sample chat app to show messages on load + * Updated libxmljs parseString -> parseHtmlString + * Fixed `make init` to work with older versions of git + * Fixed specs can now run independent specs for those who cant build deps. Closes #127 + * Fixed issues introduced by the node url module changes. Closes 126. + * Fixed two assertions failing due to Collection#keys() returning strings + * Fixed faulty Collection#toArray() spec due to keys() returning strings + * Fixed `make test` now builds libxmljs.node before testing + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE new file mode 100644 index 00000000..aa927e44 --- /dev/null +++ b/node_modules/express/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2009-2014 TJ Holowaychuk +Copyright (c) 2013-2014 Roman Shtylman +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/express/Readme.md b/node_modules/express/Readme.md new file mode 100644 index 00000000..582e8958 --- /dev/null +++ b/node_modules/express/Readme.md @@ -0,0 +1,153 @@ +[![Express Logo](https://i.cloudup.com/zfY6lL7eFa-3000x3000.png)](http://expressjs.com/) + + Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). + + [![NPM Version][npm-image]][npm-url] + [![NPM Downloads][downloads-image]][downloads-url] + [![Linux Build][travis-image]][travis-url] + [![Windows Build][appveyor-image]][appveyor-url] + [![Test Coverage][coveralls-image]][coveralls-url] + +```js +var express = require('express') +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World') +}) + +app.listen(3000) +``` + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). + +Before installing, [download and install Node.js](https://nodejs.org/en/download/). +Node.js 0.10 or higher is required. + +Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install express +``` + +Follow [our installing guide](http://expressjs.com/en/starter/installing.html) +for more information. + +## Features + + * Robust routing + * Focus on high performance + * Super-high test coverage + * HTTP helpers (redirection, caching, etc) + * View system supporting 14+ template engines + * Content negotiation + * Executable for generating applications quickly + +## Docs & Community + + * [Website and Documentation](http://expressjs.com/) - [[website repo](https://github.com/expressjs/expressjs.com)] + * [#express](https://webchat.freenode.net/?channels=express) on freenode IRC + * [GitHub Organization](https://github.com/expressjs) for Official Middleware & Modules + * Visit the [Wiki](https://github.com/expressjs/express/wiki) + * [Google Group](https://groups.google.com/group/express-js) for discussion + * [Gitter](https://gitter.im/expressjs/express) for support and discussion + +**PROTIP** Be sure to read [Migrating from 3.x to 4.x](https://github.com/expressjs/express/wiki/Migrating-from-3.x-to-4.x) as well as [New features in 4.x](https://github.com/expressjs/express/wiki/New-features-in-4.x). + +### Security Issues + +If you discover a security vulnerability in Express, please see [Security Policies and Procedures](Security.md). + +## Quick Start + + The quickest way to get started with express is to utilize the executable [`express(1)`](https://github.com/expressjs/generator) to generate an application as shown below: + + Install the executable. The executable's major version will match Express's: + +```bash +$ npm install -g express-generator@4 +``` + + Create the app: + +```bash +$ express /tmp/foo && cd /tmp/foo +``` + + Install dependencies: + +```bash +$ npm install +``` + + Start the server: + +```bash +$ npm start +``` + +## Philosophy + + The Express philosophy is to provide small, robust tooling for HTTP servers, making + it a great solution for single page applications, web sites, hybrids, or public + HTTP APIs. + + Express does not force you to use any specific ORM or template engine. With support for over + 14 template engines via [Consolidate.js](https://github.com/tj/consolidate.js), + you can quickly craft your perfect framework. + +## Examples + + To view the examples, clone the Express repo and install the dependencies: + +```bash +$ git clone git://github.com/expressjs/express.git --depth 1 +$ cd express +$ npm install +``` + + Then run whichever example you want: + +```bash +$ node examples/content-negotiation +``` + +## Tests + + To run the test suite, first install the dependencies, then run `npm test`: + +```bash +$ npm install +$ npm test +``` + +## People + +The original author of Express is [TJ Holowaychuk](https://github.com/tj) + +The current lead maintainer is [Douglas Christopher Wilson](https://github.com/dougwilson) + +[List of all contributors](https://github.com/expressjs/express/graphs/contributors) + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/express.svg +[npm-url]: https://npmjs.org/package/express +[downloads-image]: https://img.shields.io/npm/dm/express.svg +[downloads-url]: https://npmjs.org/package/express +[travis-image]: https://img.shields.io/travis/expressjs/express/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/express +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/express/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/express +[coveralls-image]: https://img.shields.io/coveralls/expressjs/express/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/express?branch=master +[gratipay-image-visionmedia]: https://img.shields.io/gratipay/visionmedia.svg +[gratipay-url-visionmedia]: https://gratipay.com/visionmedia/ +[gratipay-image-dougwilson]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url-dougwilson]: https://gratipay.com/dougwilson/ diff --git a/node_modules/express/index.js b/node_modules/express/index.js new file mode 100644 index 00000000..d219b0c8 --- /dev/null +++ b/node_modules/express/index.js @@ -0,0 +1,11 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +module.exports = require('./lib/express'); diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js new file mode 100644 index 00000000..91f77d24 --- /dev/null +++ b/node_modules/express/lib/application.js @@ -0,0 +1,644 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var finalhandler = require('finalhandler'); +var Router = require('./router'); +var methods = require('methods'); +var middleware = require('./middleware/init'); +var query = require('./middleware/query'); +var debug = require('debug')('express:application'); +var View = require('./view'); +var http = require('http'); +var compileETag = require('./utils').compileETag; +var compileQueryParser = require('./utils').compileQueryParser; +var compileTrust = require('./utils').compileTrust; +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var merge = require('utils-merge'); +var resolve = require('path').resolve; +var setPrototypeOf = require('setprototypeof') +var slice = Array.prototype.slice; + +/** + * Application prototype. + */ + +var app = exports = module.exports = {}; + +/** + * Variable for trust proxy inheritance back-compat + * @private + */ + +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; + +/** + * Initialize the server. + * + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private + */ + +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; + + this.defaultConfiguration(); +}; + +/** + * Initialize application configuration. + * @private + */ + +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; + + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); + } + + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); +}; + +/** + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * + * @private + */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); + + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); + } +}; + +/** + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * + * @private + */ + +app.handle = function handle(req, res, callback) { + var router = this._router; + + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; + } + + router.handle(req, res, done); +}; + +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ + +app.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') + } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; +}; + +/** + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. + * + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. + * + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. + * + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: + * + * app.engine('ejs', require('ejs').__express); + * + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: + * + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } + + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; + + // store engine + this.engines[extension] = fn; + + return this; +}; + +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +app.param = function param(name, fn) { + this.lazyrouter(); + + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); + } + + return this; + } + + this._router.param(name, fn); + + return this; +}; + +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public + */ + +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + + debug('set "%s" to %o', setting, val); + + // set value + this.settings[setting] = val; + + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); + + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); + + break; + } + + return this; +}; + +/** + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". + * + * @return {String} + * @private + */ + +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; + +/** + * Check if `setting` is enabled (truthy). + * + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); +}; + +/** + * Check if `setting` is disabled. + * + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false + * + * @param {String} setting + * @return {Boolean} + * @public + */ + +app.disabled = function disabled(setting) { + return !this.set(setting); +}; + +/** + * Enable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.enable = function enable(setting) { + return this.set(setting, true); +}; + +/** + * Disable `setting`. + * + * @param {String} setting + * @return {app} for chaining + * @public + */ + +app.disable = function disable(setting) { + return this.set(setting, false); +}; + +/** + * Delegate `.VERB(...)` calls to `router.VERB(...)`. + */ + +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); + } + + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +/** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + * + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public + */ + +app.all = function all(path) { + this.lazyrouter(); + + var route = this._router.route(path); + var args = slice.call(arguments, 1); + + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); + } + + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); + +/** + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. + * + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public + */ + +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge app.locals + merge(renderOptions, this.locals); + + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } + + // merge options + merge(renderOptions, opts); + + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); + } + + // primed cache + if (renderOptions.cache) { + view = cache[name]; + } + + // view + if (!view) { + var View = this.get('view'); + + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); + + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } + + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } + } + + // render + tryRender(view, renderOptions, done); +}; + +/** + * Listen for connections. + * + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public + */ + +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; + +/** + * Log error using console.error. + * + * @param {Error} err + * @private + */ + +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); +} + +/** + * Try rendering a view. + * @private + */ + +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } +} diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js new file mode 100644 index 00000000..485a8fc0 --- /dev/null +++ b/node_modules/express/lib/express.js @@ -0,0 +1,112 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var bodyParser = require('body-parser') +var EventEmitter = require('events').EventEmitter; +var mixin = require('merge-descriptors'); +var proto = require('./application'); +var Route = require('./router/route'); +var Router = require('./router'); +var req = require('./request'); +var res = require('./response'); + +/** + * Expose `createApplication()`. + */ + +exports = module.exports = createApplication; + +/** + * Create an express application. + * + * @return {Function} + * @api public + */ + +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; + + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); + + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) + + app.init(); + return app; +} + +/** + * Expose the prototypes. + */ + +exports.application = proto; +exports.request = req; +exports.response = res; + +/** + * Expose constructors. + */ + +exports.Route = Route; +exports.Router = Router; + +/** + * Expose middleware + */ + +exports.json = bodyParser.json +exports.query = require('./middleware/query'); +exports.static = require('serve-static'); +exports.urlencoded = bodyParser.urlencoded + +/** + * Replace removed middleware with an appropriate error message. + */ + +;[ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache', +].forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); diff --git a/node_modules/express/lib/middleware/init.js b/node_modules/express/lib/middleware/init.js new file mode 100644 index 00000000..dfd04274 --- /dev/null +++ b/node_modules/express/lib/middleware/init.js @@ -0,0 +1,43 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var setPrototypeOf = require('setprototypeof') + +/** + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. + * + * @param {Function} app + * @return {Function} + * @api private + */ + +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; + + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) + + res.locals = res.locals || Object.create(null); + + next(); + }; +}; + diff --git a/node_modules/express/lib/middleware/query.js b/node_modules/express/lib/middleware/query.js new file mode 100644 index 00000000..7e916694 --- /dev/null +++ b/node_modules/express/lib/middleware/query.js @@ -0,0 +1,47 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + */ + +var merge = require('utils-merge') +var parseUrl = require('parseurl'); +var qs = require('qs'); + +/** + * @param {Object} options + * @return {Function} + * @api public + */ + +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; + + if (typeof options === 'function') { + queryparse = options; + opts = undefined; + } + + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } + + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } + + next(); + }; +}; diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js new file mode 100644 index 00000000..8bb86a9a --- /dev/null +++ b/node_modules/express/lib/request.js @@ -0,0 +1,521 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var accepts = require('accepts'); +var deprecate = require('depd')('express'); +var isIP = require('net').isIP; +var typeis = require('type-is'); +var http = require('http'); +var fresh = require('fresh'); +var parseRange = require('range-parser'); +var parse = require('parseurl'); +var proxyaddr = require('proxy-addr'); + +/** + * Request prototype. + * @public + */ + +var req = Object.create(http.IncomingMessage.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = req + +/** + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public + */ + +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } + + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); + } + + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; + +/** + * To do: update docs. + * + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public + */ + +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; + +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ + +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; + +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); + +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ + +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; + +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); + +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ + +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; + +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); + +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ + +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; + +/** + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. + * + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public + */ + +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; + + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; + + return defaultValue; +}; + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; + } + } + + return typeis(this, arr); +}; + +/** + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. + * + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public + */ + +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } + + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') + + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); + +/** + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); + +/** + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public + */ + +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); + +/** + * When "trust proxy" is set, trusted proxy addresses + client. + * + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); + + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() + + return addrs +}); + +/** + * Return subdomains as an array. + * + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public + */ + +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; + + if (!hostname) return []; + + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); + +/** + * Short-hand for `url.parse(req.url).pathname`. + * + * @return {String} + * @public + */ + +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); + +/** + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public + */ + +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); + + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } + + if (!host) return; + + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); + + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); + +/** + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode + + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; + + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) + } + + return false; +}); + +/** + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); + +/** + * Check if the request was an _XMLHttpRequest_. + * + * @return {Boolean} + * @public + */ + +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); + +/** + * Helper function for creating a getter on an object. + * + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private + */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js new file mode 100644 index 00000000..9c1796d3 --- /dev/null +++ b/node_modules/express/lib/response.js @@ -0,0 +1,1137 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var deprecate = require('depd')('express'); +var encodeUrl = require('encodeurl'); +var escapeHtml = require('escape-html'); +var http = require('http'); +var isAbsolute = require('./utils').isAbsolute; +var onFinished = require('on-finished'); +var path = require('path'); +var statuses = require('statuses') +var merge = require('utils-merge'); +var sign = require('cookie-signature').sign; +var normalizeType = require('./utils').normalizeType; +var normalizeTypes = require('./utils').normalizeTypes; +var setCharset = require('./utils').setCharset; +var cookie = require('cookie'); +var send = require('send'); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = require('vary'); + +/** + * Response prototype. + * @public + */ + +var res = Object.create(http.ServerResponse.prototype) + +/** + * Module exports. + * @public + */ + +module.exports = res + +/** + * Module variables. + * @private + */ + +var charsetRegExp = /;\s*charset\s*=/; + +/** + * Set status `code`. + * + * @param {Number} code + * @return {ServerResponse} + * @public + */ + +res.status = function status(code) { + this.statusCode = code; + return this; +}; + +/** + * Set Link header field with the given `links`. + * + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public + */ + +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; + +/** + * Send a response. + * + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public + */ + +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } + } + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] + } + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; + } + + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); + + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } + + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' + + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); + } + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } + } + + // freshness + if (req.fresh) this.statusCode = 304; + + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } + + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } + + return this; +}; + +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.json = function json(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); + } + + return this.send(body); +}; + +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ + +res.jsonp = function jsonp(obj) { + var val = obj; + + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } + + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; + + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } + + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); + + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); + + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } + + return this.send(body); +}; + +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ + +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) + + this.statusCode = statusCode; + this.type('txt'); + + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); + } + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); + } + + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // create file stream + var file = send(req, path, opts); + + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORT' && err.syscall !== 'write') { + next(err); + } + }); +}; + +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); + +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ + +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null + + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } + + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] + } + } + } + + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + + // Resolve the full path for sendFile + var fullPath = resolve(path); + + // send file + return this.sendFile(fullPath, opts, done) +}; + +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ + +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + + return this.set('Content-Type', ct); +}; + +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ + +res.format = function(obj){ + var req = this.req; + var next = req.next; + + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); + + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); + } + + return this; +}; + +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ + +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } + + this.set('Content-Disposition', contentDisposition(filename)); + + return this; +}; + +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; + + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + + return this.set(field, value); +}; + +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } + + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; + +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ + +res.get = function(field){ + return this.getHeader(field); +}; + +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); + + return this.cookie(name, '', opts); +}; + +/** + * Set cookie `name` to `value`, with the given `options`. + * + * Options: + * + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // save as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ + +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; + + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); + + if (signed) { + val = 's:' + sign(val, secret); + } + + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } + + if (opts.path == null) { + opts.path = '/'; + } + + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + + return this; +}; + +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ + +res.location = function location(url) { + var loc = url; + + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } + + // set location + return this.set('Location', encodeUrl(loc)); +}; + +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ + +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; + + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } + } + + // Set location header + address = this.location(address).get('Location'); + + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, + + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, + + default: function(){ + body = ''; + } + }); + + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); + + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; + +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ + +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } + + vary(this, field); + + return this; +}; + +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ + +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } + + // merge res.locals + opts._locals = self.locals; + + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; + + // render + app.render(view, opts, done); +}; + +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; + + // request aborted + function onaborted() { + if (done) return; + done = true; + + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); + } + + // directory + function ondirectory() { + if (done) return; + done = true; + + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); + } + + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); + } + + // ended + function onend() { + if (done) return; + done = true; + callback(); + } + + // file + function onfile() { + streaming = false; + } + + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; + + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } + + if (done) return; + done = true; + callback(); + }); + } + + // streaming + function onstream() { + streaming = true; + } + + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); + + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); + + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } + + // pipe + file.pipe(res); +} + +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ + +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); + + if (escape) { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + default: + return c + } + }) + } + + return json +} diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js new file mode 100644 index 00000000..60727ed6 --- /dev/null +++ b/node_modules/express/lib/router/index.js @@ -0,0 +1,662 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var Route = require('./route'); +var Layer = require('./layer'); +var methods = require('methods'); +var mixin = require('utils-merge'); +var debug = require('debug')('express:router'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var parseUrl = require('parseurl'); +var setPrototypeOf = require('setprototypeof') + +/** + * Module variables. + * @private + */ + +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} options + * @return {Router} which is an callable function + * @public + */ + +var proto = module.exports = function(options) { + var opts = options || {}; + + function router(req, res, next) { + router.handle(req, res, next); + } + + // mixin Router class functions + setPrototypeOf(router, proto) + + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; + + return router; +}; + +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ + +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } + + // apply param functions + var params = this._params; + var len = params.length; + var ret; + + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; + } + } + + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } + + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; + +/** + * Dispatch a req, res into the router. + * @private + */ + +proto.handle = function handle(req, res, out) { + var self = this; + + debug('dispatching %s %s', req.method, req.url); + + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; + + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; + + // middleware and routes + var stack = self.stack; + + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); + + // setup next layer + req.next = next; + + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } + + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; + + next(); + + function next(err) { + var layerError = err === 'route' + ? null + : err; + + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; + } + + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; + } + + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } + + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; + } + + // get pathname of request + var path = getPathname(req); + + if (path == null) { + return done(layerError); + } + + // find next matching layer + var layer; + var match; + var route; + + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; + + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } + + if (match !== true) { + continue; + } + + if (!route) { + // process non-route handlers normally + continue; + } + + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } + + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } + } + + // no match + if (match !== true) { + return done(layerError); + } + + // store route for dispatch on change + if (route) { + req.route = route; + } + + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; + + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } + + if (route) { + return layer.handle_request(req, res, next); + } + + trim_prefix(layer, layerError, layerPath, path); + }); + } + + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) + + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); + + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } + + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } + + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); + + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Process any parameters for the layer. + * @private + */ + +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; + + // captured parameters from the layer, keys and values + var keys = layer.keys; + + // fast track + if (!keys || keys.length === 0) { + return done(); + } + + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; + + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); + } + + if (i >= keys.length ) { + return done(); + } + + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; + + if (paramVal === undefined || !paramCallbacks) { + return param(); + } + + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; + + // next param + return param(paramCalled.error); + } + + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; + + paramCallback(); + } + + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; + + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; + } + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); + } + } + + param(); +}; + +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ + +proto.use = function use(fn) { + var offset = 0; + var path = '/'; + + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; + + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; + } + + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; + } + } + + var callbacks = flatten(slice.call(arguments, offset)); + + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } + + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; + + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) + } + + // add the middleware + debug('use %o %s', path, fn.name || '') + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); + + layer.route = undefined; + + this.stack.push(layer); + } + + return this; +}; + +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ + +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; +}; + +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } +} + +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } +} + +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } + + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') + + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined +} + +// get type for error message +function gettype(obj) { + var type = typeof obj; + + if (type !== 'object') { + return type; + } + + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); +} + +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ + +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} + +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + + // make copy of parent for base + var obj = mixin({}, parent); + + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } + + var i = 0; + var o = 0; + + // determine numeric gaps + while (i in params) { + i++; + } + + while (o in parent) { + o++; + } + + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; + + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } + + return mixin(obj, params); +} + +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); + + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } + + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } + + return fn.apply(this, arguments); + }; +} + +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} + +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} diff --git a/node_modules/express/lib/router/layer.js b/node_modules/express/lib/router/layer.js new file mode 100644 index 00000000..4dc8e86d --- /dev/null +++ b/node_modules/express/lib/router/layer.js @@ -0,0 +1,181 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var pathRegexp = require('path-to-regexp'); +var debug = require('debug')('express:router:layer'); + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +/** + * Module exports. + * @public + */ + +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %o', path) + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} + +/** + * Handle the error for the layer. + * + * @param {Error} error + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; + + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } + + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ + +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; + + if (fn.length > 3) { + // not a standard request handler + return next(); + } + + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; + +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +Layer.prototype.match = function match(path) { + var match + + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true + } + + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true + } + + // match the path + match = this.regexp.exec(path) + } + + if (!match) { + this.params = undefined; + this.path = undefined; + return false; + } + + // store values + this.params = {}; + this.path = match[0] + + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } + } + + return true; +}; + +/** + * Decode param value. + * + * @param {string} val + * @return {string} + * @private + */ + +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } + + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; + } + + throw err; + } +} diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js new file mode 100644 index 00000000..178df0d5 --- /dev/null +++ b/node_modules/express/lib/router/route.js @@ -0,0 +1,216 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:router:route'); +var flatten = require('array-flatten'); +var Layer = require('./layer'); +var methods = require('methods'); + +/** + * Module variables. + * @private + */ + +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; + +/** + * Module exports. + * @public + */ + +module.exports = Route; + +/** + * Initialize `Route` with the given `path`, + * + * @param {String} path + * @public + */ + +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; +} + +/** + * Determine if the route handles a given method. + * @private + */ + +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } + + var name = method.toLowerCase(); + + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } + + return Boolean(this.methods[name]); +}; + +/** + * @return {Array} supported HTTP methods + * @private + */ + +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); + + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); + } + + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); + } + + return methods; +}; + +/** + * dispatch req, res into this route + * @private + */ + +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); + } + + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; + } + + req.route = this; + + next(); + + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } + + // signal to exit router + if (err && err === 'router') { + return done(err) + } + + var layer = stack[idx++]; + if (!layer) { + return done(err); + } + + if (layer.method && layer.method !== method) { + return next(err); + } + + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; + +/** + * Add a handler for all HTTP verbs to this route. + * + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public + */ + +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; + + this.methods._all = true; + this.stack.push(layer); + } + + return this; +}; + +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); + + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; + + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } + + debug('%s %o', method, this.path) + + var layer = Layer('/', {}, handle); + layer.method = method; + + this.methods[method] = true; + this.stack.push(layer); + } + + return this; + }; +}); diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js new file mode 100644 index 00000000..bd81ac7f --- /dev/null +++ b/node_modules/express/lib/utils.js @@ -0,0 +1,306 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @api private + */ + +var Buffer = require('safe-buffer').Buffer +var contentDisposition = require('content-disposition'); +var contentType = require('content-type'); +var deprecate = require('depd')('express'); +var flatten = require('array-flatten'); +var mime = require('send').mime; +var etag = require('etag'); +var proxyaddr = require('proxy-addr'); +var qs = require('qs'); +var querystring = require('querystring'); + +/** + * Return strong ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.etag = createETagGenerator({ weak: false }) + +/** + * Return weak ETag for `body`. + * + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private + */ + +exports.wetag = createETagGenerator({ weak: true }) + +/** + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private + */ + +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; + +/** + * Flatten the given `arr`. + * + * @param {Array} arr + * @return {Array} + * @api private + */ + +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); + +/** + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private + */ + +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; + +/** + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} + * @api private + */ + +exports.normalizeTypes = function(types){ + var ret = []; + + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); + } + + return ret; +}; + +/** + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added + * + * @param {String} filename + * @return {String} + * @api private + */ + +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); + +/** + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting + * + * @param {String} str + * @return {Object} + * @api private + */ + +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; + + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); + } else { + ret.params[pms[0]] = pms[1]; + } + } + + return ret; +} + +/** + * Compile "etag" value to function. + * + * @param {Boolean|String|Function} val + * @return {Function} + * @api private + */ + +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); + } + + return fn; +} + +/** + * Compile "query parser" value to function. + * + * @param {String|Function} val + * @return {Function} + * @api private + */ + +exports.compileQueryParser = function compileQueryParser(val) { + var fn; + + if (typeof val === 'function') { + return val; + } + + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } + + return fn; +} + +/** + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private + */ + +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; + + if (val === true) { + // Support plain true/false + return function(){ return true }; + } + + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } + + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } + + return proxyaddr.compile(val || []); +} + +/** + * Set the charset in a given Content-Type string. + * + * @param {String} type + * @param {String} charset + * @return {String} + * @api private + */ + +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } + + // parse type + var parsed = contentType.parse(type); + + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; + +/** + * Create an ETag generator function, generating ETags with + * the given options. + * + * @param {object} options + * @return {function} + * @private + */ + +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body + + return etag(buf, options) + } +} + +/** + * Parse an extended query string with qs. + * + * @return {Object} + * @private + */ + +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); +} + +/** + * Return new empty object. + * + * @return {Object} + * @api private + */ + +function newObject() { + return {}; +} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js new file mode 100644 index 00000000..cf101cae --- /dev/null +++ b/node_modules/express/lib/view.js @@ -0,0 +1,182 @@ +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('express:view'); +var path = require('path'); +var fs = require('fs'); + +/** + * Module variables. + * @private + */ + +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; + +/** + * Module exports. + * @public + */ + +module.exports = View; + +/** + * Initialize a new `View` with the given `name`. + * + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public + */ + +function View(name, options) { + var opts = options || {}; + + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; + + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } + + var fileName = name; + + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; + + fileName += this.ext; + } + + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) + + // default engine export + var fn = require(mod).__express + + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } + + opts.engines[this.ext] = fn + } + + // store loaded engine + this.engine = opts.engines[this.ext]; + + // lookup path + this.path = this.lookup(fileName); +} + +/** + * Lookup view by the given `name` + * + * @param {string} name + * @private + */ + +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); + + debug('lookup "%s"', name); + + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); + + // resolve the file + path = this.resolve(dir, file); + } + + return path; +}; + +/** + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private + */ + +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; + +/** + * Resolve the file within the given directory. + * + * @param {string} dir + * @param {string} file + * @private + */ + +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } +}; + +/** + * Return a stat, maybe. + * + * @param {string} path + * @return {fs.Stats} + * @private + */ + +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; + } +} diff --git a/node_modules/express/package.json b/node_modules/express/package.json new file mode 100644 index 00000000..d439566c --- /dev/null +++ b/node_modules/express/package.json @@ -0,0 +1,156 @@ +{ + "_args": [ + [ + "express@4.16.3", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "express@4.16.3", + "_id": "express@4.16.3", + "_inBundle": false, + "_integrity": "sha1-avilAjUNsyRuzEvs9rWjTSL37VM=", + "_location": "/express", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "express@4.16.3", + "name": "express", + "escapedName": "express", + "rawSpec": "4.16.3", + "saveSpec": null, + "fetchSpec": "4.16.3" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "http://registry.npmjs.org/express/-/express-4.16.3.tgz", + "_spec": "4.16.3", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "bugs": { + "url": "https://github.com/expressjs/express/issues" + }, + "contributors": [ + { + "name": "Aaron Heckmann", + "email": "aaron.heckmann+github@gmail.com" + }, + { + "name": "Ciaran Jessup", + "email": "ciaranj@gmail.com" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Guillermo Rauch", + "email": "rauchg@gmail.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com" + }, + { + "name": "Roman Shtylman", + "email": "shtylman+expressjs@gmail.com" + }, + { + "name": "Young Jae Sim", + "email": "hanul@hanul.me" + } + ], + "dependencies": { + "accepts": "~1.3.5", + "array-flatten": "1.1.1", + "body-parser": "1.18.2", + "content-disposition": "0.5.2", + "content-type": "~1.0.4", + "cookie": "0.3.1", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "~1.1.2", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.1.1", + "fresh": "0.5.2", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.3", + "qs": "6.5.1", + "range-parser": "~1.2.0", + "safe-buffer": "5.1.1", + "send": "0.16.2", + "serve-static": "1.13.2", + "setprototypeof": "1.1.0", + "statuses": "~1.4.0", + "type-is": "~1.6.16", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "description": "Fast, unopinionated, minimalist web framework", + "devDependencies": { + "after": "0.8.2", + "connect-redis": "~2.4.1", + "cookie-parser": "~1.4.3", + "cookie-session": "1.3.2", + "ejs": "2.5.7", + "eslint": "2.13.1", + "express-session": "1.15.6", + "hbs": "4.0.1", + "istanbul": "0.4.5", + "marked": "0.3.17", + "method-override": "2.3.10", + "mocha": "3.5.3", + "morgan": "1.9.0", + "multiparty": "4.1.3", + "pbkdf2-password": "1.2.1", + "should": "13.2.1", + "supertest": "1.2.0", + "vhost": "~3.0.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "files": [ + "LICENSE", + "History.md", + "Readme.md", + "index.js", + "lib/" + ], + "homepage": "http://expressjs.com/", + "keywords": [ + "express", + "framework", + "sinatra", + "web", + "rest", + "restful", + "router", + "app", + "api" + ], + "license": "MIT", + "name": "express", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/express.git" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --require test/support/env --reporter spec --bail --check-leaks --no-exit test/ test/acceptance/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks --no-exit test/ test/acceptance/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks --no-exit test/ test/acceptance/", + "test-tap": "mocha --require test/support/env --reporter tap --check-leaks --no-exit test/ test/acceptance/" + }, + "version": "4.16.3" +} diff --git a/node_modules/finalhandler/HISTORY.md b/node_modules/finalhandler/HISTORY.md new file mode 100644 index 00000000..9e43d2a5 --- /dev/null +++ b/node_modules/finalhandler/HISTORY.md @@ -0,0 +1,180 @@ +1.1.1 / 2018-03-06 +================== + + * Fix 404 output for bad / missing pathnames + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +1.1.0 / 2017-09-24 +================== + + * Use `res.headersSent` when available + +1.0.6 / 2017-09-22 +================== + + * deps: debug@2.6.9 + +1.0.5 / 2017-09-15 +================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + +1.0.4 / 2017-08-03 +================== + + * deps: debug@2.6.8 + +1.0.3 / 2017-05-16 +================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + +1.0.2 / 2017-04-22 +================== + + * deps: debug@2.6.4 + - deps: ms@0.7.3 + +1.0.1 / 2017-03-21 +================== + + * Fix missing `` in HTML document + * deps: debug@2.6.3 + - Fix: `DEBUG_MAX_ARRAY_LENGTH` + +1.0.0 / 2017-02-15 +================== + + * Fix exception when `err` cannot be converted to a string + * Fully URL-encode the pathname in the 404 message + * Only include the pathname in the 404 message + * Send complete HTML document + * Set `Content-Security-Policy: default-src 'self'` header + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + +0.5.1 / 2016-11-12 +================== + + * Fix exception when `err.headers` is not an object + * deps: statuses@~1.3.1 + * perf: hoist regular expressions + * perf: remove duplicate validation path + +0.5.0 / 2016-06-15 +================== + + * Change invalid or non-numeric status code to 500 + * Overwrite status message to match set status code + * Prefer `err.statusCode` if `err.status` is invalid + * Set response headers from `err.headers` object + * Use `statuses` instead of `http` module for status messages + - Includes all defined status messages + +0.4.1 / 2015-12-02 +================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + +0.4.0 / 2015-06-14 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + * Support `statusCode` property on `Error` objects + * Use `unpipe` module for unpiping requests + * deps: escape-html@1.0.2 + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove argument reassignment + +0.3.6 / 2015-05-11 +================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + +0.3.5 / 2015-04-22 +================== + + * deps: on-finished@~2.2.1 + - Fix `isFinished(req)` when data buffered + +0.3.4 / 2015-03-15 +================== + + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.3.3 / 2015-01-01 +================== + + * deps: debug@~2.1.1 + * deps: on-finished@~2.2.0 + +0.3.2 / 2014-10-22 +================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.3.1 / 2014-10-16 +================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + +0.3.0 / 2014-09-17 +================== + + * Terminate in progress response only on error + * Use `on-finished` to determine request status + +0.2.0 / 2014-09-03 +================== + + * Set `X-Content-Type-Options: nosniff` header + * deps: debug@~2.0.0 + +0.1.0 / 2014-07-16 +================== + + * Respond after request fully read + - prevents hung responses and socket hang ups + * deps: debug@1.0.4 + +0.0.3 / 2014-07-11 +================== + + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.0.2 / 2014-06-19 +================== + + * Handle invalid status codes + +0.0.1 / 2014-06-05 +================== + + * deps: debug@1.0.2 + +0.0.0 / 2014-06-05 +================== + + * Extracted from connect/express diff --git a/node_modules/finalhandler/LICENSE b/node_modules/finalhandler/LICENSE new file mode 100644 index 00000000..fb309827 --- /dev/null +++ b/node_modules/finalhandler/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/finalhandler/README.md b/node_modules/finalhandler/README.md new file mode 100644 index 00000000..6756f0cd --- /dev/null +++ b/node_modules/finalhandler/README.md @@ -0,0 +1,148 @@ +# finalhandler + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Node.js function to invoke as the final step to respond to HTTP request. + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install finalhandler +``` + +## API + + + +```js +var finalhandler = require('finalhandler') +``` + +### finalhandler(req, res, [options]) + +Returns function to be invoked as the final step for the given `req` and `res`. +This function is to be invoked as `fn(err)`. If `err` is falsy, the handler will +write out a 404 response to the `res`. If it is truthy, an error response will +be written out to the `res`. + +When an error is written, the following information is added to the response: + + * The `res.statusCode` is set from `err.status` (or `err.statusCode`). If + this value is outside the 4xx or 5xx range, it will be set to 500. + * The `res.statusMessage` is set according to the status code. + * The body will be the HTML of the status code message if `env` is + `'production'`, otherwise will be `err.stack`. + * Any headers specified in an `err.headers` object. + +The final handler will also unpipe anything from `req` when it is invoked. + +#### options.env + +By default, the environment is determined by `NODE_ENV` variable, but it can be +overridden by this option. + +#### options.onerror + +Provide a function to be called with the `err` when it exists. Can be used for +writing errors to a central location without excessive function generation. Called +as `onerror(err, req, res)`. + +## Examples + +### always 404 + +```js +var finalhandler = require('finalhandler') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + done() +}) + +server.listen(3000) +``` + +### perform simple action + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) +``` + +### use with middleware-style functions + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +var serve = serveStatic('public') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res) + serve(req, res, done) +}) + +server.listen(3000) +``` + +### keep log of all errors + +```js +var finalhandler = require('finalhandler') +var fs = require('fs') +var http = require('http') + +var server = http.createServer(function (req, res) { + var done = finalhandler(req, res, {onerror: logerror}) + + fs.readFile('index.html', function (err, buf) { + if (err) return done(err) + res.setHeader('Content-Type', 'text/html') + res.end(buf) + }) +}) + +server.listen(3000) + +function logerror (err) { + console.error(err.stack || err.toString()) +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/finalhandler.svg +[npm-url]: https://npmjs.org/package/finalhandler +[node-image]: https://img.shields.io/node/v/finalhandler.svg +[node-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/pillarjs/finalhandler.svg +[travis-url]: https://travis-ci.org/pillarjs/finalhandler +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/finalhandler.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/finalhandler?branch=master +[downloads-image]: https://img.shields.io/npm/dm/finalhandler.svg +[downloads-url]: https://npmjs.org/package/finalhandler diff --git a/node_modules/finalhandler/index.js b/node_modules/finalhandler/index.js new file mode 100644 index 00000000..f20ffe32 --- /dev/null +++ b/node_modules/finalhandler/index.js @@ -0,0 +1,331 @@ +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var debug = require('debug')('finalhandler') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var onFinished = require('on-finished') +var parseUrl = require('parseurl') +var statuses = require('statuses') +var unpipe = require('unpipe') + +/** + * Module variables. + * @private + */ + +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished + +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ + +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') + + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Module exports. + * @public + */ + +module.exports = finalhandler + +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ + +function finalhandler (req, res, options) { + var opts = options || {} + + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + + return function (err) { + var headers + var msg + var status + + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } + + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } + + debug('default %s', status) + + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } + + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } + + // send response + send(req, res, status, headers, msg) + } +} + +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ + +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } + + var headers = Object.create(null) + var keys = Object.keys(err.headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } + + return headers +} + +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ + +function getErrorMessage (err, status, env) { + var msg + + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack + + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } + + return msg || statuses[status] +} + +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ + +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } + + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } + + return undefined +} + +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ + +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} + +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ + +function getResponseStatusCode (res) { + var status = res.statusCode + + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } + + return status +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ + +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) + + // response status + res.statusCode = status + res.statusMessage = statuses[status] + + // response headers + setHeaders(res, headers) + + // security headers + res.setHeader('Content-Security-Policy', "default-src 'self'") + res.setHeader('X-Content-Type-Options', 'nosniff') + + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) + + if (req.method === 'HEAD') { + res.end() + return + } + + res.end(body, 'utf8') + } + + if (isFinished(req)) { + write() + return + } + + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() +} + +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + if (!headers) { + return + } + + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/finalhandler/package.json b/node_modules/finalhandler/package.json new file mode 100644 index 00000000..a2a105dd --- /dev/null +++ b/node_modules/finalhandler/package.json @@ -0,0 +1,83 @@ +{ + "_args": [ + [ + "finalhandler@1.1.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "finalhandler@1.1.1", + "_id": "finalhandler@1.1.1", + "_inBundle": false, + "_integrity": "sha512-Y1GUDo39ez4aHAw7MysnUD5JzYX+WaIj8I57kO3aEPT1fFRL4sr7mjei97FgnwhAyyzRYmQZaTHb2+9uZ1dPtg==", + "_location": "/finalhandler", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "finalhandler@1.1.1", + "name": "finalhandler", + "escapedName": "finalhandler", + "rawSpec": "1.1.1", + "saveSpec": null, + "fetchSpec": "1.1.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "http://registry.npmjs.org/finalhandler/-/finalhandler-1.1.1.tgz", + "_spec": "1.1.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/pillarjs/finalhandler/issues" + }, + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "~2.3.0", + "parseurl": "~1.3.2", + "statuses": "~1.4.0", + "unpipe": "~1.0.0" + }, + "description": "Node.js final http responder", + "devDependencies": { + "eslint": "4.18.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "readable-stream": "2.3.4", + "safe-buffer": "5.1.1", + "supertest": "1.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "homepage": "https://github.com/pillarjs/finalhandler#readme", + "license": "MIT", + "name": "finalhandler", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/finalhandler.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + }, + "version": "1.1.1" +} diff --git a/node_modules/forwarded/HISTORY.md b/node_modules/forwarded/HISTORY.md new file mode 100644 index 00000000..2599a557 --- /dev/null +++ b/node_modules/forwarded/HISTORY.md @@ -0,0 +1,16 @@ +0.1.2 / 2017-09-14 +================== + + * perf: improve header parsing + * perf: reduce overhead when no `X-Forwarded-For` header + +0.1.1 / 2017-09-10 +================== + + * Fix trimming leading / trailing OWS + * perf: hoist regular expression + +0.1.0 / 2014-09-21 +================== + + * Initial release diff --git a/node_modules/forwarded/LICENSE b/node_modules/forwarded/LICENSE new file mode 100644 index 00000000..84441fbb --- /dev/null +++ b/node_modules/forwarded/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/forwarded/README.md b/node_modules/forwarded/README.md new file mode 100644 index 00000000..c776ee54 --- /dev/null +++ b/node_modules/forwarded/README.md @@ -0,0 +1,57 @@ +# forwarded + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse HTTP X-Forwarded-For header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install forwarded +``` + +## API + +```js +var forwarded = require('forwarded') +``` + +### forwarded(req) + +```js +var addresses = forwarded(req) +``` + +Parse the `X-Forwarded-For` header from the request. Returns an array +of the addresses, including the socket address for the `req`, in reverse +order (i.e. index `0` is the socket address and the last index is the +furthest address, typically the end-user). + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/forwarded.svg +[npm-url]: https://npmjs.org/package/forwarded +[node-version-image]: https://img.shields.io/node/v/forwarded.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/forwarded/master.svg +[travis-url]: https://travis-ci.org/jshttp/forwarded +[coveralls-image]: https://img.shields.io/coveralls/jshttp/forwarded/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/forwarded?branch=master +[downloads-image]: https://img.shields.io/npm/dm/forwarded.svg +[downloads-url]: https://npmjs.org/package/forwarded diff --git a/node_modules/forwarded/index.js b/node_modules/forwarded/index.js new file mode 100644 index 00000000..7833b3de --- /dev/null +++ b/node_modules/forwarded/index.js @@ -0,0 +1,76 @@ +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = forwarded + +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ + +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } + + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = req.connection.remoteAddress + var addrs = [socketAddr].concat(proxyAddrs) + + // return all addresses + return addrs +} + +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ + +function parse (header) { + var end = header.length + var list = [] + var start = header.length + + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break + } + } + + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } + + return list +} diff --git a/node_modules/forwarded/package.json b/node_modules/forwarded/package.json new file mode 100644 index 00000000..69dc7fd8 --- /dev/null +++ b/node_modules/forwarded/package.json @@ -0,0 +1,81 @@ +{ + "_args": [ + [ + "forwarded@0.1.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "forwarded@0.1.2", + "_id": "forwarded@0.1.2", + "_inBundle": false, + "_integrity": "sha1-mMI9qxF1ZXuMBXPozszZGw/xjIQ=", + "_location": "/forwarded", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "forwarded@0.1.2", + "name": "forwarded", + "escapedName": "forwarded", + "rawSpec": "0.1.2", + "saveSpec": null, + "fetchSpec": "0.1.2" + }, + "_requiredBy": [ + "/proxy-addr" + ], + "_resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.1.2.tgz", + "_spec": "0.1.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/forwarded/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "description": "Parse HTTP X-Forwarded-For header", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/forwarded#readme", + "keywords": [ + "x-forwarded-for", + "http", + "req" + ], + "license": "MIT", + "name": "forwarded", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/forwarded.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "0.1.2" +} diff --git a/node_modules/fresh/HISTORY.md b/node_modules/fresh/HISTORY.md new file mode 100644 index 00000000..4586996a --- /dev/null +++ b/node_modules/fresh/HISTORY.md @@ -0,0 +1,70 @@ +0.5.2 / 2017-09-13 +================== + + * Fix regression matching multiple ETags in `If-None-Match` + * perf: improve `If-None-Match` token parsing + +0.5.1 / 2017-09-11 +================== + + * Fix handling of modified headers with invalid dates + * perf: improve ETag match loop + +0.5.0 / 2017-02-21 +================== + + * Fix incorrect result when `If-None-Match` has both `*` and ETags + * Fix weak `ETag` matching to match spec + * perf: delay reading header values until needed + * perf: skip checking modified time if ETag check failed + * perf: skip parsing `If-None-Match` when no `ETag` header + * perf: use `Date.parse` instead of `new Date` + +0.4.0 / 2017-02-05 +================== + + * Fix false detection of `no-cache` request directive + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove duplicate conditional + * perf: remove unnecessary boolean coercions + +0.3.0 / 2015-05-12 +================== + + * Add weak `ETag` matching support + +0.2.4 / 2014-09-07 +================== + + * Support Node.js 0.6 + +0.2.3 / 2014-09-07 +================== + + * Move repository to jshttp + +0.2.2 / 2014-02-19 +================== + + * Revert "Fix for blank page on Safari reload" + +0.2.1 / 2014-01-29 +================== + + * Fix for blank page on Safari reload + +0.2.0 / 2013-08-11 +================== + + * Return stale for `Cache-Control: no-cache` + +0.1.0 / 2012-06-15 +================== + + * Add `If-None-Match: *` support + +0.0.1 / 2012-06-10 +================== + + * Initial release diff --git a/node_modules/fresh/LICENSE b/node_modules/fresh/LICENSE new file mode 100644 index 00000000..1434ade7 --- /dev/null +++ b/node_modules/fresh/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2016-2017 Douglas Christopher Wilson + +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/fresh/README.md b/node_modules/fresh/README.md new file mode 100644 index 00000000..1c1c680d --- /dev/null +++ b/node_modules/fresh/README.md @@ -0,0 +1,119 @@ +# fresh + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP response freshness testing + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +``` +$ npm install fresh +``` + +## API + + + +```js +var fresh = require('fresh') +``` + +### fresh(reqHeaders, resHeaders) + +Check freshness of the response using request and response headers. + +When the response is still "fresh" in the client's cache `true` is +returned, otherwise `false` is returned to indicate that the client +cache is now stale and the full response should be sent. + +When a client sends the `Cache-Control: no-cache` request header to +indicate an end-to-end reload request, this module will return `false` +to make handling these requests transparent. + +## Known Issues + +This module is designed to only follow the HTTP specifications, not +to work-around all kinda of client bugs (especially since this module +typically does not recieve enough information to understand what the +client actually is). + +There is a known issue that in certain versions of Safari, Safari +will incorrectly make a request that allows this module to validate +freshness of the resource even when Safari does not have a +representation of the resource in the cache. The module +[jumanji](https://www.npmjs.com/package/jumanji) can be used in +an Express application to work-around this issue and also provides +links to further reading on this Safari bug. + +## Example + +### API usage + + + +```js +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"bar"' } +fresh(reqHeaders, resHeaders) +// => false + +var reqHeaders = { 'if-none-match': '"foo"' } +var resHeaders = { 'etag': '"foo"' } +fresh(reqHeaders, resHeaders) +// => true +``` + +### Using with Node.js http server + +```js +var fresh = require('fresh') +var http = require('http') + +var server = http.createServer(function (req, res) { + // perform server logic + // ... including adding ETag / Last-Modified response headers + + if (isFresh(req, res)) { + // client has a fresh copy of resource + res.statusCode = 304 + res.end() + return + } + + // send the resource + res.statusCode = 200 + res.end('hello, world!') +}) + +function isFresh (req, res) { + return fresh(req.headers, { + 'etag': res.getHeader('ETag'), + 'last-modified': res.getHeader('Last-Modified') + }) +} + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/fresh.svg +[npm-url]: https://npmjs.org/package/fresh +[node-version-image]: https://img.shields.io/node/v/fresh.svg +[node-version-url]: https://nodejs.org/en/ +[travis-image]: https://img.shields.io/travis/jshttp/fresh/master.svg +[travis-url]: https://travis-ci.org/jshttp/fresh +[coveralls-image]: https://img.shields.io/coveralls/jshttp/fresh/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/fresh?branch=master +[downloads-image]: https://img.shields.io/npm/dm/fresh.svg +[downloads-url]: https://npmjs.org/package/fresh diff --git a/node_modules/fresh/index.js b/node_modules/fresh/index.js new file mode 100644 index 00000000..d154f5a7 --- /dev/null +++ b/node_modules/fresh/index.js @@ -0,0 +1,137 @@ +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ + +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = fresh + +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ + +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } + + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } + + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] + + if (!etag) { + return false + } + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } + } + + if (etagStale) { + return false + } + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false + } + } + + return true +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} diff --git a/node_modules/fresh/package.json b/node_modules/fresh/package.json new file mode 100644 index 00000000..93f70b1f --- /dev/null +++ b/node_modules/fresh/package.json @@ -0,0 +1,93 @@ +{ + "_args": [ + [ + "fresh@0.5.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "fresh@0.5.2", + "_id": "fresh@0.5.2", + "_inBundle": false, + "_integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=", + "_location": "/fresh", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "fresh@0.5.2", + "name": "fresh", + "escapedName": "fresh", + "rawSpec": "0.5.2", + "saveSpec": null, + "fetchSpec": "0.5.2" + }, + "_requiredBy": [ + "/express", + "/send" + ], + "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "_spec": "0.5.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "bugs": { + "url": "https://github.com/jshttp/fresh/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "description": "HTTP response freshness testing", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "homepage": "https://github.com/jshttp/fresh#readme", + "keywords": [ + "fresh", + "http", + "conditional", + "cache" + ], + "license": "MIT", + "name": "fresh", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/fresh.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "0.5.2" +} diff --git a/node_modules/graphql/LICENSE b/node_modules/graphql/LICENSE new file mode 100644 index 00000000..9e051010 --- /dev/null +++ b/node_modules/graphql/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015-present, Facebook, 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/graphql/README.md b/node_modules/graphql/README.md new file mode 100644 index 00000000..0148a8cb --- /dev/null +++ b/node_modules/graphql/README.md @@ -0,0 +1,145 @@ +# GraphQL.js + +The JavaScript reference implementation for GraphQL, a query language for APIs created by Facebook. + +[![npm version](https://badge.fury.io/js/graphql.svg)](http://badge.fury.io/js/graphql) +[![Build Status](https://travis-ci.org/graphql/graphql-js.svg?branch=master)](https://travis-ci.org/graphql/graphql-js?branch=master) +[![Coverage Status](https://coveralls.io/repos/graphql/graphql-js/badge.svg?branch=master)](https://coveralls.io/r/graphql/graphql-js?branch=master) + +See more complete documentation at http://graphql.org/ and +http://graphql.org/graphql-js/. + +Looking for help? Find resources [from the community](http://graphql.org/community/). + + +## Getting Started + +An overview of GraphQL in general is available in the +[README](https://github.com/facebook/graphql/blob/master/README.md) for the +[Specification for GraphQL](https://github.com/facebook/graphql). That overview +describes a simple set of GraphQL examples that exist as [tests](src/__tests__) +in this repository. A good way to get started with this repository is to walk +through that README and the corresponding tests in parallel. + +### Using GraphQL.js + +Install GraphQL.js from npm + +With yarn: + +```sh +yarn add graphql +``` + +or alternatively using npm: + +```sh +npm install --save graphql +``` + +GraphQL.js provides two important capabilities: building a type schema, and +serving queries against that type schema. + +First, build a GraphQL type schema which maps to your code base. + +```js +import { + graphql, + GraphQLSchema, + GraphQLObjectType, + GraphQLString +} from 'graphql'; + +var schema = new GraphQLSchema({ + query: new GraphQLObjectType({ + name: 'RootQueryType', + fields: { + hello: { + type: GraphQLString, + resolve() { + return 'world'; + } + } + } + }) +}); +``` + +This defines a simple schema with one type and one field, that resolves +to a fixed value. The `resolve` function can return a value, a promise, +or an array of promises. A more complex example is included in the top +level [tests](src/__tests__) directory. + +Then, serve the result of a query against that type schema. + +```js +var query = '{ hello }'; + +graphql(schema, query).then(result => { + + // Prints + // { + // data: { hello: "world" } + // } + console.log(result); + +}); +``` + +This runs a query fetching the one field defined. The `graphql` function will +first ensure the query is syntactically and semantically valid before executing +it, reporting errors otherwise. + +```js +var query = '{ boyhowdy }'; + +graphql(schema, query).then(result => { + + // Prints + // { + // errors: [ + // { message: 'Cannot query field boyhowdy on RootQueryType', + // locations: [ { line: 1, column: 3 } ] } + // ] + // } + console.log(result); + +}); +``` + +### Want to ride the bleeding edge? + +The `npm` branch in this repository is automatically maintained to be the last +commit to `master` to pass all tests, in the same form found on npm. It is +recommended to use builds deployed to npm for many reasons, but if you want to use +the latest not-yet-released version of graphql-js, you can do so by depending +directly on this branch: + +``` +npm install graphql@git://github.com/graphql/graphql-js.git#npm +``` + +### Using in a Browser + +GraphQL.js is a general purpose library and can be used both in a Node server +and in the browser. As an example, the [GraphiQL](https://github.com/graphql/graphiql/) +tool is built with GraphQL.js! + +Building a project using GraphQL.js with [webpack](https://webpack.js.org) or +[rollup](https://github.com/rollup/rollup) should just work and only include +the portions of the library you use. This works because GraphQL.js is distributed +with both CommonJS (`require()`) and ESModule (`import`) files. Ensure that any +custom build configurations look for `.mjs` files! + +### Contributing + +We actively welcome pull requests, learn how to +[contribute](https://github.com/graphql/graphql-js/blob/master/.github/CONTRIBUTING.md). + +### Changelog + +Changes are tracked as [GitHub releases](https://github.com/graphql/graphql-js/releases). + +### License + +GraphQL.js is [MIT-licensed](https://github.com/graphql/graphql-js/blob/master/LICENSE). diff --git a/node_modules/graphql/error/GraphQLError.js b/node_modules/graphql/error/GraphQLError.js new file mode 100644 index 00000000..f9d53470 --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.js @@ -0,0 +1,146 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.GraphQLError = GraphQLError; + +var _printError = require("./printError"); + +var _location = require("../language/location"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function GraphQLError( // eslint-disable-line no-redeclare +message, nodes, source, positions, path, originalError, extensions) { + // Compute list of blame nodes. + var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions. + + + var _source = source; + + if (!_source && _nodes) { + var node = _nodes[0]; + _source = node && node.loc && node.loc.source; + } + + var _positions = positions; + + if (!_positions && _nodes) { + _positions = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push(node.loc.start); + } + + return list; + }, []); + } + + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + var _locations; + + if (positions && source) { + _locations = positions.map(function (pos) { + return (0, _location.getLocation)(source, pos); + }); + } else if (_nodes) { + _locations = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push((0, _location.getLocation)(node.loc.source, node.loc.start)); + } + + return list; + }, []); + } + + var _extensions = extensions || originalError && originalError.extensions; + + Object.defineProperties(this, { + message: { + value: message, + // By being enumerable, JSON.stringify will include `message` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: true, + writable: true + }, + locations: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _locations || undefined, + // By being enumerable, JSON.stringify will include `locations` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_locations) + }, + path: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: path || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(path) + }, + nodes: { + value: _nodes || undefined + }, + source: { + value: _source || undefined + }, + positions: { + value: _positions || undefined + }, + originalError: { + value: originalError + }, + extensions: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _extensions || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_extensions) + } + }); // Include (non-enumerable) stack trace. + + if (originalError && originalError.stack) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true + }); + } +} + +GraphQLError.prototype = Object.create(Error.prototype, { + constructor: { + value: GraphQLError + }, + name: { + value: 'GraphQLError' + }, + toString: { + value: function toString() { + return (0, _printError.printError)(this); + } + } +}); \ No newline at end of file diff --git a/node_modules/graphql/error/GraphQLError.js.flow b/node_modules/graphql/error/GraphQLError.js.flow new file mode 100644 index 00000000..89e540e3 --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.js.flow @@ -0,0 +1,220 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { printError } from './printError'; +import { getLocation } from '../language/location'; +import type { SourceLocation } from '../language/location'; +import type { ASTNode } from '../language/ast'; +import type { Source } from '../language/source'; + +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ +declare class GraphQLError extends Error { + constructor( + message: string, + nodes?: $ReadOnlyArray | ASTNode | void, + source?: ?Source, + positions?: ?$ReadOnlyArray, + path?: ?$ReadOnlyArray, + originalError?: ?Error, + extensions?: ?{ [key: string]: mixed }, + ): void; + + /** + * A message describing the Error for debugging purposes. + * + * Enumerable, and appears in the result of JSON.stringify(). + * + * Note: should be treated as readonly, despite invariant usage. + */ + message: string; + + /** + * An array of { line, column } locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + +locations: $ReadOnlyArray | void; + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + +path: $ReadOnlyArray | void; + + /** + * An array of GraphQL AST Nodes corresponding to this error. + */ + +nodes: $ReadOnlyArray | void; + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + +source: Source | void; + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + +positions: $ReadOnlyArray | void; + + /** + * The original error thrown from a field resolver during execution. + */ + +originalError: ?Error; + + /** + * Extension fields to add to the formatted error. + */ + +extensions: { [key: string]: mixed } | void; +} + +export function GraphQLError( // eslint-disable-line no-redeclare + message: string, + nodes?: $ReadOnlyArray | ASTNode | void, + source?: ?Source, + positions?: ?$ReadOnlyArray, + path?: ?$ReadOnlyArray, + originalError?: ?Error & { +extensions: mixed }, + extensions?: ?{ [key: string]: mixed }, +) { + // Compute list of blame nodes. + const _nodes = Array.isArray(nodes) + ? nodes.length !== 0 + ? nodes + : undefined + : nodes + ? [nodes] + : undefined; + + // Compute locations in the source for the given nodes/positions. + let _source = source; + if (!_source && _nodes) { + const node = _nodes[0]; + _source = node && node.loc && node.loc.source; + } + + let _positions = positions; + if (!_positions && _nodes) { + _positions = _nodes.reduce((list, node) => { + if (node.loc) { + list.push(node.loc.start); + } + return list; + }, []); + } + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + let _locations; + if (positions && source) { + _locations = positions.map(pos => getLocation(source, pos)); + } else if (_nodes) { + _locations = _nodes.reduce((list, node) => { + if (node.loc) { + list.push(getLocation(node.loc.source, node.loc.start)); + } + return list; + }, []); + } + + const _extensions = extensions || (originalError && originalError.extensions); + + Object.defineProperties(this, { + message: { + value: message, + // By being enumerable, JSON.stringify will include `message` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: true, + writable: true, + }, + locations: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _locations || undefined, + // By being enumerable, JSON.stringify will include `locations` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_locations), + }, + path: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: path || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(path), + }, + nodes: { + value: _nodes || undefined, + }, + source: { + value: _source || undefined, + }, + positions: { + value: _positions || undefined, + }, + originalError: { + value: originalError, + }, + extensions: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _extensions || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_extensions), + }, + }); + + // Include (non-enumerable) stack trace. + if (originalError && originalError.stack) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true, + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true, + }); + } +} + +(GraphQLError: any).prototype = Object.create(Error.prototype, { + constructor: { value: GraphQLError }, + name: { value: 'GraphQLError' }, + toString: { + value: function toString() { + return printError(this); + }, + }, +}); diff --git a/node_modules/graphql/error/GraphQLError.mjs b/node_modules/graphql/error/GraphQLError.mjs new file mode 100644 index 00000000..ac55ab1a --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.mjs @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { printError } from './printError'; +import { getLocation } from '../language/location'; +export function GraphQLError( // eslint-disable-line no-redeclare +message, nodes, source, positions, path, originalError, extensions) { + // Compute list of blame nodes. + var _nodes = Array.isArray(nodes) ? nodes.length !== 0 ? nodes : undefined : nodes ? [nodes] : undefined; // Compute locations in the source for the given nodes/positions. + + + var _source = source; + + if (!_source && _nodes) { + var node = _nodes[0]; + _source = node && node.loc && node.loc.source; + } + + var _positions = positions; + + if (!_positions && _nodes) { + _positions = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push(node.loc.start); + } + + return list; + }, []); + } + + if (_positions && _positions.length === 0) { + _positions = undefined; + } + + var _locations; + + if (positions && source) { + _locations = positions.map(function (pos) { + return getLocation(source, pos); + }); + } else if (_nodes) { + _locations = _nodes.reduce(function (list, node) { + if (node.loc) { + list.push(getLocation(node.loc.source, node.loc.start)); + } + + return list; + }, []); + } + + var _extensions = extensions || originalError && originalError.extensions; + + Object.defineProperties(this, { + message: { + value: message, + // By being enumerable, JSON.stringify will include `message` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: true, + writable: true + }, + locations: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _locations || undefined, + // By being enumerable, JSON.stringify will include `locations` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_locations) + }, + path: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: path || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(path) + }, + nodes: { + value: _nodes || undefined + }, + source: { + value: _source || undefined + }, + positions: { + value: _positions || undefined + }, + originalError: { + value: originalError + }, + extensions: { + // Coercing falsey values to undefined ensures they will not be included + // in JSON.stringify() when not provided. + value: _extensions || undefined, + // By being enumerable, JSON.stringify will include `path` in the + // resulting output. This ensures that the simplest possible GraphQL + // service adheres to the spec. + enumerable: Boolean(_extensions) + } + }); // Include (non-enumerable) stack trace. + + if (originalError && originalError.stack) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true + }); + } +} +GraphQLError.prototype = Object.create(Error.prototype, { + constructor: { + value: GraphQLError + }, + name: { + value: 'GraphQLError' + }, + toString: { + value: function toString() { + return printError(this); + } + } +}); \ No newline at end of file diff --git a/node_modules/graphql/error/formatError.js b/node_modules/graphql/error/formatError.js new file mode 100644 index 00000000..1ccb5ad4 --- /dev/null +++ b/node_modules/graphql/error/formatError.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.formatError = formatError; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +function formatError(error) { + !error ? (0, _invariant.default)(0, 'Received null or undefined error.') : void 0; + var message = error.message || 'An unknown error occurred.'; + var locations = error.locations; + var path = error.path; + var extensions = error.extensions; + return extensions ? { + message: message, + locations: locations, + path: path, + extensions: extensions + } : { + message: message, + locations: locations, + path: path + }; +} \ No newline at end of file diff --git a/node_modules/graphql/error/formatError.js.flow b/node_modules/graphql/error/formatError.js.flow new file mode 100644 index 00000000..a6718129 --- /dev/null +++ b/node_modules/graphql/error/formatError.js.flow @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import type { GraphQLError } from './GraphQLError'; +import type { SourceLocation } from '../language/location'; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error: GraphQLError): GraphQLFormattedError { + invariant(error, 'Received null or undefined error.'); + const message = error.message || 'An unknown error occurred.'; + const locations = error.locations; + const path = error.path; + const extensions = error.extensions; + + return extensions + ? { message, locations, path, extensions } + : { message, locations, path }; +} + +export type GraphQLFormattedError = {| + +message: string, + +locations: $ReadOnlyArray | void, + +path: $ReadOnlyArray | void, + +extensions?: { [key: string]: mixed }, +|}; diff --git a/node_modules/graphql/error/formatError.mjs b/node_modules/graphql/error/formatError.mjs new file mode 100644 index 00000000..a83bea67 --- /dev/null +++ b/node_modules/graphql/error/formatError.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; + +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. + */ +export function formatError(error) { + !error ? invariant(0, 'Received null or undefined error.') : void 0; + var message = error.message || 'An unknown error occurred.'; + var locations = error.locations; + var path = error.path; + var extensions = error.extensions; + return extensions ? { + message: message, + locations: locations, + path: path, + extensions: extensions + } : { + message: message, + locations: locations, + path: path + }; +} \ No newline at end of file diff --git a/node_modules/graphql/error/index.js b/node_modules/graphql/error/index.js new file mode 100644 index 00000000..94939e87 --- /dev/null +++ b/node_modules/graphql/error/index.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function get() { + return _GraphQLError.GraphQLError; + } +}); +Object.defineProperty(exports, "syntaxError", { + enumerable: true, + get: function get() { + return _syntaxError.syntaxError; + } +}); +Object.defineProperty(exports, "locatedError", { + enumerable: true, + get: function get() { + return _locatedError.locatedError; + } +}); +Object.defineProperty(exports, "printError", { + enumerable: true, + get: function get() { + return _printError.printError; + } +}); +Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function get() { + return _formatError.formatError; + } +}); + +var _GraphQLError = require("./GraphQLError"); + +var _syntaxError = require("./syntaxError"); + +var _locatedError = require("./locatedError"); + +var _printError = require("./printError"); + +var _formatError = require("./formatError"); \ No newline at end of file diff --git a/node_modules/graphql/error/index.js.flow b/node_modules/graphql/error/index.js.flow new file mode 100644 index 00000000..3ca6fdb1 --- /dev/null +++ b/node_modules/graphql/error/index.js.flow @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { GraphQLError } from './GraphQLError'; +export { syntaxError } from './syntaxError'; +export { locatedError } from './locatedError'; +export { printError } from './printError'; +export { formatError } from './formatError'; + +export type { GraphQLFormattedError } from './formatError'; diff --git a/node_modules/graphql/error/index.mjs b/node_modules/graphql/error/index.mjs new file mode 100644 index 00000000..2a23479f --- /dev/null +++ b/node_modules/graphql/error/index.mjs @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { GraphQLError } from './GraphQLError'; +export { syntaxError } from './syntaxError'; +export { locatedError } from './locatedError'; +export { printError } from './printError'; +export { formatError } from './formatError'; \ No newline at end of file diff --git a/node_modules/graphql/error/locatedError.js b/node_modules/graphql/error/locatedError.js new file mode 100644 index 00000000..07a0b8f6 --- /dev/null +++ b/node_modules/graphql/error/locatedError.js @@ -0,0 +1,32 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.locatedError = locatedError; + +var _GraphQLError = require("./GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given an arbitrary Error, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +function locatedError(originalError, nodes, path) { + // Note: this uses a brand-check to support GraphQL errors originating from + // other contexts. + if (originalError && Array.isArray(originalError.path)) { + return originalError; + } + + return new _GraphQLError.GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError); +} \ No newline at end of file diff --git a/node_modules/graphql/error/locatedError.js.flow b/node_modules/graphql/error/locatedError.js.flow new file mode 100644 index 00000000..0f49516f --- /dev/null +++ b/node_modules/graphql/error/locatedError.js.flow @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from './GraphQLError'; +import type { ASTNode } from '../language/ast'; + +/** + * Given an arbitrary Error, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +export function locatedError( + originalError: Error | GraphQLError, + nodes: $ReadOnlyArray, + path: $ReadOnlyArray, +): GraphQLError { + // Note: this uses a brand-check to support GraphQL errors originating from + // other contexts. + if (originalError && Array.isArray(originalError.path)) { + return (originalError: any); + } + + return new GraphQLError( + originalError && originalError.message, + (originalError && (originalError: any).nodes) || nodes, + originalError && (originalError: any).source, + originalError && (originalError: any).positions, + path, + originalError, + ); +} diff --git a/node_modules/graphql/error/locatedError.mjs b/node_modules/graphql/error/locatedError.mjs new file mode 100644 index 00000000..67a0a3ff --- /dev/null +++ b/node_modules/graphql/error/locatedError.mjs @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from './GraphQLError'; + +/** + * Given an arbitrary Error, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + */ +export function locatedError(originalError, nodes, path) { + // Note: this uses a brand-check to support GraphQL errors originating from + // other contexts. + if (originalError && Array.isArray(originalError.path)) { + return originalError; + } + + return new GraphQLError(originalError && originalError.message, originalError && originalError.nodes || nodes, originalError && originalError.source, originalError && originalError.positions, path, originalError); +} \ No newline at end of file diff --git a/node_modules/graphql/error/printError.js b/node_modules/graphql/error/printError.js new file mode 100644 index 00000000..80b7ed8e --- /dev/null +++ b/node_modules/graphql/error/printError.js @@ -0,0 +1,146 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printError = printError; + +var _location = require("../language/location"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +function printError(error) { + var printedLocations = []; + + if (error.nodes) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.loc) { + printedLocations.push(highlightSourceAtLocation(node.loc.source, (0, _location.getLocation)(node.loc.source, node.loc.start))); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if (error.source && error.locations) { + var source = error.source; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var location = _step2.value; + printedLocations.push(highlightSourceAtLocation(source, location)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n'; +} +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ + + +function highlightSourceAtLocation(source, location) { + var firstLineColumnOffset = source.locationOffset.column - 1; + var body = whitespace(firstLineColumnOffset) + source.body; + var lineIndex = location.line - 1; + var lineOffset = source.locationOffset.line - 1; + var lineNum = location.line + lineOffset; + var columnOffset = location.line === 1 ? firstLineColumnOffset : 0; + var columnNum = location.column + columnOffset; + var lines = body.split(/\r\n|[\n\r]/g); + return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"], + ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]); +} + +function printPrefixedLines(lines) { + var existingLines = lines.filter(function (_ref) { + var _ = _ref[0], + line = _ref[1]; + return line !== undefined; + }); + var padLen = 0; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _ref4 = _step3.value; + var prefix = _ref4[0]; + padLen = Math.max(padLen, prefix.length); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return existingLines.map(function (_ref3) { + var prefix = _ref3[0], + line = _ref3[1]; + return lpad(padLen, prefix) + line; + }).join('\n'); +} + +function whitespace(len) { + return Array(len + 1).join(' '); +} + +function lpad(len, str) { + return whitespace(len - str.length) + str; +} \ No newline at end of file diff --git a/node_modules/graphql/error/printError.js.flow b/node_modules/graphql/error/printError.js.flow new file mode 100644 index 00000000..90126408 --- /dev/null +++ b/node_modules/graphql/error/printError.js.flow @@ -0,0 +1,93 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { getLocation } from '../language/location'; +import type { SourceLocation } from '../language/location'; +import type { Source } from '../language/source'; +import type { GraphQLError } from './GraphQLError'; + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error: GraphQLError): string { + const printedLocations = []; + if (error.nodes) { + for (const node of error.nodes) { + if (node.loc) { + printedLocations.push( + highlightSourceAtLocation( + node.loc.source, + getLocation(node.loc.source, node.loc.start), + ), + ); + } + } + } else if (error.source && error.locations) { + const source = error.source; + for (const location of error.locations) { + printedLocations.push(highlightSourceAtLocation(source, location)); + } + } + return printedLocations.length === 0 + ? error.message + : [error.message, ...printedLocations].join('\n\n') + '\n'; +} + +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ +function highlightSourceAtLocation( + source: Source, + location: SourceLocation, +): string { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = whitespace(firstLineColumnOffset) + source.body; + + const lineIndex = location.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = location.line + lineOffset; + + const columnOffset = location.line === 1 ? firstLineColumnOffset : 0; + const columnNum = location.column + columnOffset; + + const lines = body.split(/\r\n|[\n\r]/g); + return ( + `${source.name} (${lineNum}:${columnNum})\n` + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1}: `, lines[lineIndex - 1]], + [`${lineNum}: `, lines[lineIndex]], + ['', whitespace(columnNum - 1) + '^'], + [`${lineNum + 1}: `, lines[lineIndex + 1]], + ]) + ); +} + +function printPrefixedLines(lines: Array<[string, string]>): string { + const existingLines = lines.filter(([_, line]) => line !== undefined); + + let padLen = 0; + for (const [prefix] of existingLines) { + padLen = Math.max(padLen, prefix.length); + } + + return existingLines + .map(([prefix, line]) => lpad(padLen, prefix) + line) + .join('\n'); +} + +function whitespace(len: number): string { + return Array(len + 1).join(' '); +} + +function lpad(len: number, str: string): string { + return whitespace(len - str.length) + str; +} diff --git a/node_modules/graphql/error/printError.mjs b/node_modules/graphql/error/printError.mjs new file mode 100644 index 00000000..a65d8736 --- /dev/null +++ b/node_modules/graphql/error/printError.mjs @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { getLocation } from '../language/location'; + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. + */ +export function printError(error) { + var printedLocations = []; + + if (error.nodes) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = error.nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.loc) { + printedLocations.push(highlightSourceAtLocation(node.loc.source, getLocation(node.loc.source, node.loc.start))); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if (error.source && error.locations) { + var source = error.source; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = error.locations[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var location = _step2.value; + printedLocations.push(highlightSourceAtLocation(source, location)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return printedLocations.length === 0 ? error.message : [error.message].concat(printedLocations).join('\n\n') + '\n'; +} +/** + * Render a helpful description of the location of the error in the GraphQL + * Source document. + */ + +function highlightSourceAtLocation(source, location) { + var firstLineColumnOffset = source.locationOffset.column - 1; + var body = whitespace(firstLineColumnOffset) + source.body; + var lineIndex = location.line - 1; + var lineOffset = source.locationOffset.line - 1; + var lineNum = location.line + lineOffset; + var columnOffset = location.line === 1 ? firstLineColumnOffset : 0; + var columnNum = location.column + columnOffset; + var lines = body.split(/\r\n|[\n\r]/g); + return "".concat(source.name, " (").concat(lineNum, ":").concat(columnNum, ")\n") + printPrefixedLines([// Lines specified like this: ["prefix", "string"], + ["".concat(lineNum - 1, ": "), lines[lineIndex - 1]], ["".concat(lineNum, ": "), lines[lineIndex]], ['', whitespace(columnNum - 1) + '^'], ["".concat(lineNum + 1, ": "), lines[lineIndex + 1]]]); +} + +function printPrefixedLines(lines) { + var existingLines = lines.filter(function (_ref) { + var _ = _ref[0], + line = _ref[1]; + return line !== undefined; + }); + var padLen = 0; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = existingLines[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _ref4 = _step3.value; + var prefix = _ref4[0]; + padLen = Math.max(padLen, prefix.length); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return existingLines.map(function (_ref3) { + var prefix = _ref3[0], + line = _ref3[1]; + return lpad(padLen, prefix) + line; + }).join('\n'); +} + +function whitespace(len) { + return Array(len + 1).join(' '); +} + +function lpad(len, str) { + return whitespace(len - str.length) + str; +} \ No newline at end of file diff --git a/node_modules/graphql/error/syntaxError.js b/node_modules/graphql/error/syntaxError.js new file mode 100644 index 00000000..412f6d39 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.js @@ -0,0 +1,25 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.syntaxError = syntaxError; + +var _GraphQLError = require("./GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]); +} \ No newline at end of file diff --git a/node_modules/graphql/error/syntaxError.js.flow b/node_modules/graphql/error/syntaxError.js.flow new file mode 100644 index 00000000..6409f405 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.js.flow @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Source } from '../language/source'; +import { GraphQLError } from './GraphQLError'; + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ +export function syntaxError( + source: Source, + position: number, + description: string, +): GraphQLError { + return new GraphQLError(`Syntax Error: ${description}`, undefined, source, [ + position, + ]); +} diff --git a/node_modules/graphql/error/syntaxError.mjs b/node_modules/graphql/error/syntaxError.mjs new file mode 100644 index 00000000..c7fe5dc5 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from './GraphQLError'; +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + */ + +export function syntaxError(source, position, description) { + return new GraphQLError("Syntax Error: ".concat(description), undefined, source, [position]); +} \ No newline at end of file diff --git a/node_modules/graphql/execution/execute.js b/node_modules/graphql/execution/execute.js new file mode 100644 index 00000000..e333064a --- /dev/null +++ b/node_modules/graphql/execution/execute.js @@ -0,0 +1,831 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.execute = execute; +exports.responsePathAsArray = responsePathAsArray; +exports.addPath = addPath; +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.collectFields = collectFields; +exports.buildResolveInfo = buildResolveInfo; +exports.resolveFieldValueOrError = resolveFieldValueOrError; +exports.getFieldDef = getFieldDef; +exports.defaultFieldResolver = void 0; + +var _iterall = require("iterall"); + +var _GraphQLError = require("../error/GraphQLError"); + +var _locatedError = require("../error/locatedError"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _isNullish = _interopRequireDefault(require("../jsutils/isNullish")); + +var _isPromise = _interopRequireDefault(require("../jsutils/isPromise")); + +var _memoize = _interopRequireDefault(require("../jsutils/memoize3")); + +var _promiseForObject = _interopRequireDefault(require("../jsutils/promiseForObject")); + +var _promiseReduce = _interopRequireDefault(require("../jsutils/promiseReduce")); + +var _getOperationRootType = require("../utilities/getOperationRootType"); + +var _typeFromAST = require("../utilities/typeFromAST"); + +var _kinds = require("../language/kinds"); + +var _values = require("./values"); + +var _definition = require("../type/definition"); + +var _introspection = require("../type/introspection"); + +var _directives = require("../type/directives"); + +var _validate = require("../type/validate"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} + +function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + + + var data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ + + +function buildResponse(exeContext, data) { + if ((0, _isPromise.default)(data)) { + return data.then(function (resolved) { + return buildResponse(exeContext, resolved); + }); + } + + return exeContext.errors.length === 0 ? { + data: data + } : { + errors: exeContext.errors, + data: data + }; +} +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + + +function responsePathAsArray(path) { + var flattened = []; + var curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + */ + + +function addPath(prev, key) { + return { + prev: prev, + key: key + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ + + +function assertValidExecutionArguments(schema, document, rawVariableValues) { + !document ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + + !(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? (0, _invariant.default)(0, 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.') : void 0; +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ + + +function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) { + var errors = []; + var operation; + var hasMultipleAssumedOperations = false; + var fragments = Object.create(null); + + for (var i = 0; i < document.definitions.length; i++) { + var definition = document.definitions[i]; + + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + hasMultipleAssumedOperations = true; + } else if (!operationName || definition.name && definition.name.value === operationName) { + operation = definition; + } + + break; + + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName) { + errors.push(new _GraphQLError.GraphQLError("Unknown operation named \"".concat(operationName, "\"."))); + } else { + errors.push(new _GraphQLError.GraphQLError('Must provide an operation.')); + } + } else if (hasMultipleAssumedOperations) { + errors.push(new _GraphQLError.GraphQLError('Must provide operation name if query contains multiple operations.')); + } + + var variableValues; + + if (operation) { + var coercedVariableValues = (0, _values.getVariableValues)(schema, operation.variableDefinitions || [], rawVariableValues || {}); + + if (coercedVariableValues.errors) { + errors.push.apply(errors, coercedVariableValues.errors); + } else { + variableValues = coercedVariableValues.coerced; + } + } + + if (errors.length !== 0) { + return errors; + } + + !operation ? (0, _invariant.default)(0, 'Has operation if no errors.') : void 0; + !variableValues ? (0, _invariant.default)(0, 'Has variables if no errors.') : void 0; + return { + schema: schema, + fragments: fragments, + rootValue: rootValue, + contextValue: contextValue, + operation: operation, + variableValues: variableValues, + fieldResolver: fieldResolver || defaultFieldResolver, + errors: errors + }; +} +/** + * Implements the "Evaluating operations" section of the spec. + */ + + +function executeOperation(exeContext, operation, rootValue) { + var type = (0, _getOperationRootType.getOperationRootType)(exeContext.schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + // + // Similar to completeValueCatchingError. + + try { + var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); + + if ((0, _isPromise.default)(result)) { + return result.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ + + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return (0, _promiseReduce.default)(Object.keys(fields), function (results, responseName) { + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result === undefined) { + return results; + } + + if ((0, _isPromise.default)(result)) { + return result.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ + + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var results = Object.create(null); + var containsPromise = false; + + for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) { + var responseName = keys[i]; + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result !== undefined) { + results[responseName] = result; + + if (!containsPromise && (0, _isPromise.default)(result)) { + containsPromise = true; + } + } + } // If there are no promises, we can just return the object + + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + + return (0, _promiseForObject.default)(results); +} +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ + + +function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case _kinds.Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + + var name = getFieldEntryKey(selection); + + if (!fields[name]) { + fields[name] = []; + } + + fields[name].push(selection); + break; + + case _kinds.Kind.INLINE_FRAGMENT: + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + + case _kinds.Kind.FRAGMENT_SPREAD: + var fragName = selection.name.value; + + if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { + continue; + } + + visitedFragmentNames[fragName] = true; + var fragment = exeContext.fragments[fragName]; + + if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + + return fields; +} +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ + + +function shouldIncludeNode(exeContext, node) { + var skip = (0, _values.getDirectiveValues)(_directives.GraphQLSkipDirective, node, exeContext.variableValues); + + if (skip && skip.if === true) { + return false; + } + + var include = (0, _values.getDirectiveValues)(_directives.GraphQLIncludeDirective, node, exeContext.variableValues); + + if (include && include.if === false) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + + +function doesFragmentConditionMatch(exeContext, fragment, type) { + var typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + var conditionalType = (0, _typeFromAST.typeFromAST)(exeContext.schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if ((0, _definition.isAbstractType)(conditionalType)) { + return exeContext.schema.isPossibleType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ + + +function resolveField(exeContext, parentType, source, fieldNodes, path) { + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + + if (!fieldDef) { + return; + } + + var resolveFn = fieldDef.resolve || exeContext.fieldResolver; + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal + // or abrupt (error). + + var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info); + return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result); +} + +function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes: fieldNodes, + returnType: fieldDef.type, + parentType: parentType, + path: path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; +} // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. + + +function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) { + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + var args = (0, _values.getArgumentValues)(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var _contextValue = exeContext.contextValue; + var result = resolveFn(source, args, _contextValue, info); + return (0, _isPromise.default)(result) ? result.then(undefined, asErrorInstance) : result; + } catch (error) { + return asErrorInstance(error); + } +} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a +// consistent Error interface. + + +function asErrorInstance(error) { + return error instanceof Error ? error : new Error(error || undefined); +} // This is a small wrapper around completeValue which detects and logs errors +// in the execution context. + + +function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) { + try { + var completed; + + if ((0, _isPromise.default)(result)) { + completed = result.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + + if ((0, _isPromise.default)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, function (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + }); + } + + return completed; + } catch (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + } +} + +function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { + var error = (0, _locatedError.locatedError)(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ + + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + + if ((0, _definition.isNonNullType)(returnType)) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + + if (completed === null) { + throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")); + } + + return completed; + } // If result value is null-ish (null, undefined, or NaN) then return null. + + + if ((0, _isNullish.default)(result)) { + return null; + } // If field type is List, complete each item in the list with the inner type + + + if ((0, _definition.isListType)(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + + + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } // Not reachable. All possible output types have been considered. + + /* istanbul ignore next */ + + + throw new Error("Cannot complete value of unexpected type \"".concat((0, _inspect.default)(returnType), "\".")); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + !(0, _iterall.isCollection)(result) ? (0, _invariant.default)(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + var itemType = returnType.ofType; + var containsPromise = false; + var completedResults = []; + (0, _iterall.forEach)(result, function (item, index) { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + var fieldPath = addPath(path, index); + var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item); + + if (!containsPromise && (0, _isPromise.default)(completedItem)) { + containsPromise = true; + } + + completedResults.push(completedItem); + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + +function completeLeafValue(returnType, result) { + !returnType.serialize ? (0, _invariant.default)(0, 'Missing serialize method on type') : void 0; + var serializedResult = returnType.serialize(result); + + if ((0, _isInvalid.default)(serializedResult)) { + throw new Error("Expected a value of type \"".concat((0, _inspect.default)(returnType), "\" but ") + "received: ".concat((0, _inspect.default)(result))); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); + + if ((0, _isPromise.default)(runtimeType)) { + return runtimeType.then(function (resolvedRuntimeType) { + return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + }); + } + + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} + +function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { + var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName; + + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat((0, _inspect.default)(result), ", received \"").concat((0, _inspect.default)(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if ((0, _isPromise.default)(isTypeOf)) { + return isTypeOf.then(function (resolvedIsTypeOf) { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat((0, _inspect.default)(result), "."), fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { + // Collect sub-fields to execute to complete this value. + var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + +var collectSubfields = (0, _memoize.default)(_collectSubfields); + +function _collectSubfields(exeContext, returnType, fieldNodes) { + var subFieldNodes = Object.create(null); + var visitedFragmentNames = Object.create(null); + + for (var i = 0; i < fieldNodes.length; i++) { + var selectionSet = fieldNodes[i].selectionSet; + + if (selectionSet) { + subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames); + } + } + + return subFieldNodes; +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + +function defaultResolveTypeFn(value, contextValue, info, abstractType) { + // First, look for `__typename`. + if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + + var possibleTypes = info.schema.getPossibleTypes(abstractType); + var promisedIsTypeOfResults = []; + + for (var i = 0; i < possibleTypes.length; i++) { + var type = possibleTypes[i]; + + if (type.isTypeOf) { + var isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if ((0, _isPromise.default)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) { + for (var _i = 0; _i < isTypeOfResults.length; _i++) { + if (isTypeOfResults[_i]) { + return possibleTypes[_i]; + } + } + }); + } +} +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + + +var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if (_typeof(source) === 'object' || typeof source === 'function') { + var property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ + + +exports.defaultFieldResolver = defaultFieldResolver; + +function getFieldDef(schema, parentType, fieldName) { + if (fieldName === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } else if (fieldName === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} \ No newline at end of file diff --git a/node_modules/graphql/execution/execute.js.flow b/node_modules/graphql/execution/execute.js.flow new file mode 100644 index 00000000..f6f61443 --- /dev/null +++ b/node_modules/graphql/execution/execute.js.flow @@ -0,0 +1,1268 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { forEach, isCollection } from 'iterall'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import isInvalid from '../jsutils/isInvalid'; +import isNullish from '../jsutils/isNullish'; +import isPromise from '../jsutils/isPromise'; +import memoize3 from '../jsutils/memoize3'; +import promiseForObject from '../jsutils/promiseForObject'; +import promiseReduce from '../jsutils/promiseReduce'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { MaybePromise } from '../jsutils/MaybePromise'; + +import { getOperationRootType } from '../utilities/getOperationRootType'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { Kind } from '../language/kinds'; +import { + getVariableValues, + getArgumentValues, + getDirectiveValues, +} from './values'; +import { + isObjectType, + isAbstractType, + isLeafType, + isListType, + isNonNullType, +} from '../type/definition'; +import type { + GraphQLObjectType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLAbstractType, + GraphQLField, + GraphQLFieldResolver, + GraphQLResolveInfo, + ResponsePath, + GraphQLList, +} from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection'; +import { + GraphQLIncludeDirective, + GraphQLSkipDirective, +} from '../type/directives'; +import { assertValidSchema } from '../type/validate'; +import type { + DocumentNode, + OperationDefinitionNode, + SelectionSetNode, + FieldNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, +} from '../language/ast'; + +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g "a" + * 2) fragment "spreads" e.g. "...c" + * 3) inline fragment "spreads" e.g. "...on Type { a }" + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + */ +export type ExecutionContext = {| + schema: GraphQLSchema, + fragments: ObjMap, + rootValue: mixed, + contextValue: mixed, + operation: OperationDefinitionNode, + variableValues: { [variable: string]: mixed }, + fieldResolver: GraphQLFieldResolver, + errors: Array, +|}; + +/** + * The result of GraphQL execution. + * + * - `errors` is included when any errors occurred as a non-empty array. + * - `data` is the result of a successful execution of the query. + */ +export type ExecutionResult = { + errors?: $ReadOnlyArray, + data?: ObjMap, +}; + +export type ExecutionArgs = {| + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ [variable: string]: mixed }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +|}; + +/** + * Implements the "Evaluating requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Accepts either an object with named arguments, or individual arguments. + */ +declare function execute( + ExecutionArgs, + ..._: [] +): MaybePromise; +/* eslint-disable no-redeclare */ +declare function execute( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?{ [variable: string]: mixed }, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): MaybePromise; +export function execute( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 + ? executeImpl( + argsOrSchema.schema, + argsOrSchema.document, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + ) + : executeImpl( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); +} + +function executeImpl( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); + + // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + const exeContext = buildExecutionContext( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Return early errors if execution context failed. + if (Array.isArray(exeContext)) { + return { errors: exeContext }; + } + + // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + const data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} + +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ +function buildResponse( + exeContext: ExecutionContext, + data: MaybePromise | null>, +) { + if (isPromise(data)) { + return data.then(resolved => buildResponse(exeContext, resolved)); + } + return exeContext.errors.length === 0 + ? { data } + : { errors: exeContext.errors, data }; +} + +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ +export function responsePathAsArray( + path: ResponsePath, +): $ReadOnlyArray { + const flattened = []; + let curr = path; + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + return flattened.reverse(); +} + +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + */ +export function addPath(prev: ResponsePath | void, key: string | number) { + return { prev, key }; +} + +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ +export function assertValidExecutionArguments( + schema: GraphQLSchema, + document: DocumentNode, + rawVariableValues: ?ObjMap, +): void { + invariant(document, 'Must provide document'); + + // If the schema used for execution is invalid, throw an error. + assertValidSchema(schema); + + // Variables, if provided, must be an object. + invariant( + !rawVariableValues || typeof rawVariableValues === 'object', + 'Variables must be provided as an Object where each property is a ' + + 'variable value. Perhaps look to see if an unparsed JSON string ' + + 'was provided.', + ); +} + +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ +export function buildExecutionContext( + schema: GraphQLSchema, + document: DocumentNode, + rootValue: mixed, + contextValue: mixed, + rawVariableValues: ?ObjMap, + operationName: ?string, + fieldResolver: ?GraphQLFieldResolver, +): $ReadOnlyArray | ExecutionContext { + const errors: Array = []; + let operation: OperationDefinitionNode | void; + let hasMultipleAssumedOperations = false; + const fragments: ObjMap = Object.create(null); + for (let i = 0; i < document.definitions.length; i++) { + const definition = document.definitions[i]; + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + hasMultipleAssumedOperations = true; + } else if ( + !operationName || + (definition.name && definition.name.value === operationName) + ) { + operation = definition; + } + break; + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName) { + errors.push( + new GraphQLError(`Unknown operation named "${operationName}".`), + ); + } else { + errors.push(new GraphQLError('Must provide an operation.')); + } + } else if (hasMultipleAssumedOperations) { + errors.push( + new GraphQLError( + 'Must provide operation name if query contains multiple operations.', + ), + ); + } + + let variableValues; + if (operation) { + const coercedVariableValues = getVariableValues( + schema, + operation.variableDefinitions || [], + rawVariableValues || {}, + ); + + if (coercedVariableValues.errors) { + errors.push(...coercedVariableValues.errors); + } else { + variableValues = coercedVariableValues.coerced; + } + } + + if (errors.length !== 0) { + return errors; + } + + invariant(operation, 'Has operation if no errors.'); + invariant(variableValues, 'Has variables if no errors.'); + + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues, + fieldResolver: fieldResolver || defaultFieldResolver, + errors, + }; +} + +/** + * Implements the "Evaluating operations" section of the spec. + */ +function executeOperation( + exeContext: ExecutionContext, + operation: OperationDefinitionNode, + rootValue: mixed, +): MaybePromise | null> { + const type = getOperationRootType(exeContext.schema, operation); + const fields = collectFields( + exeContext, + type, + operation.selectionSet, + Object.create(null), + Object.create(null), + ); + + const path = undefined; + + // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + // + // Similar to completeValueCatchingError. + try { + const result = + operation.operation === 'mutation' + ? executeFieldsSerially(exeContext, type, rootValue, path, fields) + : executeFields(exeContext, type, rootValue, path, fields); + if (isPromise(result)) { + return result.then(undefined, error => { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ +function executeFieldsSerially( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + sourceValue: mixed, + path: ResponsePath | void, + fields: ObjMap>, +): MaybePromise> { + return promiseReduce( + Object.keys(fields), + (results, responseName) => { + const fieldNodes = fields[responseName]; + const fieldPath = addPath(path, responseName); + const result = resolveField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + if (result === undefined) { + return results; + } + if (isPromise(result)) { + return result.then(resolvedResult => { + results[responseName] = resolvedResult; + return results; + }); + } + results[responseName] = result; + return results; + }, + Object.create(null), + ); +} + +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ +function executeFields( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + sourceValue: mixed, + path: ResponsePath | void, + fields: ObjMap>, +): MaybePromise> { + const results = Object.create(null); + let containsPromise = false; + + for (let i = 0, keys = Object.keys(fields); i < keys.length; ++i) { + const responseName = keys[i]; + const fieldNodes = fields[responseName]; + const fieldPath = addPath(path, responseName); + const result = resolveField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result !== undefined) { + results[responseName] = result; + if (!containsPromise && isPromise(result)) { + containsPromise = true; + } + } + } + + // If there are no promises, we can just return the object + if (!containsPromise) { + return results; + } + + // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + return promiseForObject(results); +} + +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ +export function collectFields( + exeContext: ExecutionContext, + runtimeType: GraphQLObjectType, + selectionSet: SelectionSetNode, + fields: ObjMap>, + visitedFragmentNames: ObjMap, +): ObjMap> { + for (let i = 0; i < selectionSet.selections.length; i++) { + const selection = selectionSet.selections[i]; + switch (selection.kind) { + case Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + const name = getFieldEntryKey(selection); + if (!fields[name]) { + fields[name] = []; + } + fields[name].push(selection); + break; + case Kind.INLINE_FRAGMENT: + if ( + !shouldIncludeNode(exeContext, selection) || + !doesFragmentConditionMatch(exeContext, selection, runtimeType) + ) { + continue; + } + collectFields( + exeContext, + runtimeType, + selection.selectionSet, + fields, + visitedFragmentNames, + ); + break; + case Kind.FRAGMENT_SPREAD: + const fragName = selection.name.value; + if ( + visitedFragmentNames[fragName] || + !shouldIncludeNode(exeContext, selection) + ) { + continue; + } + visitedFragmentNames[fragName] = true; + const fragment = exeContext.fragments[fragName]; + if ( + !fragment || + !doesFragmentConditionMatch(exeContext, fragment, runtimeType) + ) { + continue; + } + collectFields( + exeContext, + runtimeType, + fragment.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + } + return fields; +} + +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ +function shouldIncludeNode( + exeContext: ExecutionContext, + node: FragmentSpreadNode | FieldNode | InlineFragmentNode, +): boolean { + const skip = getDirectiveValues( + GraphQLSkipDirective, + node, + exeContext.variableValues, + ); + if (skip && skip.if === true) { + return false; + } + + const include = getDirectiveValues( + GraphQLIncludeDirective, + node, + exeContext.variableValues, + ); + if (include && include.if === false) { + return false; + } + return true; +} + +/** + * Determines if a fragment is applicable to the given type. + */ +function doesFragmentConditionMatch( + exeContext: ExecutionContext, + fragment: FragmentDefinitionNode | InlineFragmentNode, + type: GraphQLObjectType, +): boolean { + const typeConditionNode = fragment.typeCondition; + if (!typeConditionNode) { + return true; + } + const conditionalType = typeFromAST(exeContext.schema, typeConditionNode); + if (conditionalType === type) { + return true; + } + if (isAbstractType(conditionalType)) { + return exeContext.schema.isPossibleType(conditionalType, type); + } + return false; +} + +/** + * Implements the logic to compute the key of a given field's entry + */ +function getFieldEntryKey(node: FieldNode): string { + return node.alias ? node.alias.value : node.name.value; +} + +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ +function resolveField( + exeContext: ExecutionContext, + parentType: GraphQLObjectType, + source: mixed, + fieldNodes: $ReadOnlyArray, + path: ResponsePath, +): MaybePromise { + const fieldNode = fieldNodes[0]; + const fieldName = fieldNode.name.value; + + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + if (!fieldDef) { + return; + } + + const resolveFn = fieldDef.resolve || exeContext.fieldResolver; + + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, + ); + + // Get the resolve function, regardless of if its result is normal + // or abrupt (error). + const result = resolveFieldValueOrError( + exeContext, + fieldDef, + fieldNodes, + resolveFn, + source, + info, + ); + + return completeValueCatchingError( + exeContext, + fieldDef.type, + fieldNodes, + info, + path, + result, + ); +} + +export function buildResolveInfo( + exeContext: ExecutionContext, + fieldDef: GraphQLField<*, *>, + fieldNodes: $ReadOnlyArray, + parentType: GraphQLObjectType, + path: ResponsePath, +): GraphQLResolveInfo { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues, + }; +} + +// Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. +export function resolveFieldValueOrError( + exeContext: ExecutionContext, + fieldDef: GraphQLField, + fieldNodes: $ReadOnlyArray, + resolveFn: GraphQLFieldResolver, + source: TSource, + info: GraphQLResolveInfo, +): Error | mixed { + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = getArgumentValues( + fieldDef, + fieldNodes[0], + exeContext.variableValues, + ); + + // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + const contextValue = exeContext.contextValue; + + const result = resolveFn(source, args, contextValue, info); + return isPromise(result) ? result.then(undefined, asErrorInstance) : result; + } catch (error) { + return asErrorInstance(error); + } +} + +// Sometimes a non-error is thrown, wrap it as an Error instance to ensure a +// consistent Error interface. +function asErrorInstance(error: mixed): Error { + return error instanceof Error ? error : new Error(error || undefined); +} + +// This is a small wrapper around completeValue which detects and logs errors +// in the execution context. +function completeValueCatchingError( + exeContext: ExecutionContext, + returnType: GraphQLOutputType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise { + try { + let completed; + if (isPromise(result)) { + completed = result.then(resolved => + completeValue(exeContext, returnType, fieldNodes, info, path, resolved), + ); + } else { + completed = completeValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, error => + handleFieldError(error, fieldNodes, path, returnType, exeContext), + ); + } + return completed; + } catch (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + } +} + +function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { + const error = locatedError( + asErrorInstance(rawError), + fieldNodes, + responsePathAsArray(path), + ); + + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if (isNonNullType(returnType)) { + throw error; + } + + // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + exeContext.errors.push(error); + return null; +} + +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ +function completeValue( + exeContext: ExecutionContext, + returnType: GraphQLOutputType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } + + // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + if (isNonNullType(returnType)) { + const completed = completeValue( + exeContext, + returnType.ofType, + fieldNodes, + info, + path, + result, + ); + if (completed === null) { + throw new Error( + `Cannot return null for non-nullable field ${info.parentType.name}.${ + info.fieldName + }.`, + ); + } + return completed; + } + + // If result value is null-ish (null, undefined, or NaN) then return null. + if (isNullish(result)) { + return null; + } + + // If field type is List, complete each item in the list with the inner type + if (isListType(returnType)) { + return completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } + + // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + if (isAbstractType(returnType)) { + return completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // If field type is Object, execute and complete all sub-selections. + if (isObjectType(returnType)) { + return completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + // Not reachable. All possible output types have been considered. + /* istanbul ignore next */ + throw new Error( + `Cannot complete value of unexpected type "${inspect( + (returnType: empty), + )}".`, + ); +} + +/** + * Complete a list value by completing each item in the list with the + * inner type + */ +function completeListValue( + exeContext: ExecutionContext, + returnType: GraphQLList, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise<$ReadOnlyArray> { + invariant( + isCollection(result), + `Expected Iterable, but did not find one for field ${ + info.parentType.name + }.${info.fieldName}.`, + ); + + // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = []; + forEach((result: any), (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const fieldPath = addPath(path, index); + const completedItem = completeValueCatchingError( + exeContext, + itemType, + fieldNodes, + info, + fieldPath, + item, + ); + + if (!containsPromise && isPromise(completedItem)) { + containsPromise = true; + } + completedResults.push(completedItem); + }); + + return containsPromise ? Promise.all(completedResults) : completedResults; +} + +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ +function completeLeafValue(returnType: GraphQLLeafType, result: mixed): mixed { + invariant(returnType.serialize, 'Missing serialize method on type'); + const serializedResult = returnType.serialize(result); + if (isInvalid(serializedResult)) { + throw new Error( + `Expected a value of type "${inspect(returnType)}" but ` + + `received: ${inspect(result)}`, + ); + } + return serializedResult; +} + +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ +function completeAbstractValue( + exeContext: ExecutionContext, + returnType: GraphQLAbstractType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise> { + const runtimeType = returnType.resolveType + ? returnType.resolveType(result, exeContext.contextValue, info) + : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then(resolvedRuntimeType => + completeObjectValue( + exeContext, + ensureValidRuntimeType( + resolvedRuntimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ), + ); + } + + return completeObjectValue( + exeContext, + ensureValidRuntimeType( + runtimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ); +} + +function ensureValidRuntimeType( + runtimeTypeOrName: ?GraphQLObjectType | string, + exeContext: ExecutionContext, + returnType: GraphQLAbstractType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + result: mixed, +): GraphQLObjectType { + const runtimeType = + typeof runtimeTypeOrName === 'string' + ? exeContext.schema.getType(runtimeTypeOrName) + : runtimeTypeOrName; + + if (!isObjectType(runtimeType)) { + throw new GraphQLError( + `Abstract type ${returnType.name} must resolve to an Object type at ` + + `runtime for field ${info.parentType.name}.${info.fieldName} with ` + + `value ${inspect(result)}, received "${inspect(runtimeType)}". ` + + `Either the ${returnType.name} type should provide a "resolveType" ` + + 'function or each possible type should provide an "isTypeOf" function.', + fieldNodes, + ); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new GraphQLError( + `Runtime Object type "${runtimeType.name}" is not a possible type ` + + `for "${returnType.name}".`, + fieldNodes, + ); + } + + return runtimeType; +} + +/** + * Complete an Object value by executing all sub-selections. + */ +function completeObjectValue( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray, + info: GraphQLResolveInfo, + path: ResponsePath, + result: mixed, +): MaybePromise> { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then(resolvedIsTypeOf => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + return collectAndExecuteSubfields( + exeContext, + returnType, + fieldNodes, + path, + result, + ); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields( + exeContext, + returnType, + fieldNodes, + path, + result, + ); +} + +function invalidReturnTypeError( + returnType: GraphQLObjectType, + result: mixed, + fieldNodes: $ReadOnlyArray, +): GraphQLError { + return new GraphQLError( + `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, + fieldNodes, + ); +} + +function collectAndExecuteSubfields( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray, + path: ResponsePath, + result: mixed, +): MaybePromise> { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} + +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ +const collectSubfields = memoize3(_collectSubfields); +function _collectSubfields( + exeContext: ExecutionContext, + returnType: GraphQLObjectType, + fieldNodes: $ReadOnlyArray, +): ObjMap> { + let subFieldNodes = Object.create(null); + const visitedFragmentNames = Object.create(null); + for (let i = 0; i < fieldNodes.length; i++) { + const selectionSet = fieldNodes[i].selectionSet; + if (selectionSet) { + subFieldNodes = collectFields( + exeContext, + returnType, + selectionSet, + subFieldNodes, + visitedFragmentNames, + ); + } + } + return subFieldNodes; +} + +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ +function defaultResolveTypeFn( + value: mixed, + contextValue: mixed, + info: GraphQLResolveInfo, + abstractType: GraphQLAbstractType, +): MaybePromise { + // First, look for `__typename`. + if ( + value !== null && + typeof value === 'object' && + typeof value.__typename === 'string' + ) { + return value.__typename; + } + + // Otherwise, test each possible type. + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(isTypeOfResults => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i]; + } + } + }); + } +} + +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ +export const defaultFieldResolver: GraphQLFieldResolver = function( + source, + args, + contextValue, + info, +) { + // ensure source is a value for which property access is acceptable. + if (typeof source === 'object' || typeof source === 'function') { + const property = source[info.fieldName]; + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + return property; + } +}; + +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ +export function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLObjectType, + fieldName: string, +): ?GraphQLField<*, *> { + if ( + fieldName === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } else if ( + fieldName === TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + return parentType.getFields()[fieldName]; +} diff --git a/node_modules/graphql/execution/execute.mjs b/node_modules/graphql/execution/execute.mjs new file mode 100644 index 00000000..0c962b99 --- /dev/null +++ b/node_modules/graphql/execution/execute.mjs @@ -0,0 +1,792 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { forEach, isCollection } from 'iterall'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import isInvalid from '../jsutils/isInvalid'; +import isNullish from '../jsutils/isNullish'; +import isPromise from '../jsutils/isPromise'; +import memoize3 from '../jsutils/memoize3'; +import promiseForObject from '../jsutils/promiseForObject'; +import promiseReduce from '../jsutils/promiseReduce'; +import { getOperationRootType } from '../utilities/getOperationRootType'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { Kind } from '../language/kinds'; +import { getVariableValues, getArgumentValues, getDirectiveValues } from './values'; +import { isObjectType, isAbstractType, isLeafType, isListType, isNonNullType } from '../type/definition'; +import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection'; +import { GraphQLIncludeDirective, GraphQLSkipDirective } from '../type/directives'; +import { assertValidSchema } from '../type/validate'; +export function execute(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? executeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : executeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} + +function executeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrect, throw an error. + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return { + errors: exeContext + }; + } // Return a Promise that will eventually resolve to the data described by + // The "Response" section of the GraphQL specification. + // + // If errors are encountered while executing a GraphQL field, only that + // field and its descendants will be omitted, and sibling fields will still + // be executed. An execution which encounters errors will still result in a + // resolved Promise. + + + var data = executeOperation(exeContext, exeContext.operation, rootValue); + return buildResponse(exeContext, data); +} +/** + * Given a completed execution context and data, build the { errors, data } + * response defined by the "Response" section of the GraphQL specification. + */ + + +function buildResponse(exeContext, data) { + if (isPromise(data)) { + return data.then(function (resolved) { + return buildResponse(exeContext, resolved); + }); + } + + return exeContext.errors.length === 0 ? { + data: data + } : { + errors: exeContext.errors, + data: data + }; +} +/** + * Given a ResponsePath (found in the `path` entry in the information provided + * as the last argument to a field resolver), return an Array of the path keys. + */ + + +export function responsePathAsArray(path) { + var flattened = []; + var curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} +/** + * Given a ResponsePath and a key, return a new ResponsePath containing the + * new key. + */ + +export function addPath(prev, key) { + return { + prev: prev, + key: key + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. + */ + +export function assertValidExecutionArguments(schema, document, rawVariableValues) { + !document ? invariant(0, 'Must provide document') : void 0; // If the schema used for execution is invalid, throw an error. + + assertValidSchema(schema); // Variables, if provided, must be an object. + + !(!rawVariableValues || _typeof(rawVariableValues) === 'object') ? invariant(0, 'Variables must be provided as an Object where each property is a ' + 'variable value. Perhaps look to see if an unparsed JSON string ' + 'was provided.') : void 0; +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + */ + +export function buildExecutionContext(schema, document, rootValue, contextValue, rawVariableValues, operationName, fieldResolver) { + var errors = []; + var operation; + var hasMultipleAssumedOperations = false; + var fragments = Object.create(null); + + for (var i = 0; i < document.definitions.length; i++) { + var definition = document.definitions[i]; + + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (!operationName && operation) { + hasMultipleAssumedOperations = true; + } else if (!operationName || definition.name && definition.name.value === operationName) { + operation = definition; + } + + break; + + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + } + } + + if (!operation) { + if (operationName) { + errors.push(new GraphQLError("Unknown operation named \"".concat(operationName, "\"."))); + } else { + errors.push(new GraphQLError('Must provide an operation.')); + } + } else if (hasMultipleAssumedOperations) { + errors.push(new GraphQLError('Must provide operation name if query contains multiple operations.')); + } + + var variableValues; + + if (operation) { + var coercedVariableValues = getVariableValues(schema, operation.variableDefinitions || [], rawVariableValues || {}); + + if (coercedVariableValues.errors) { + errors.push.apply(errors, coercedVariableValues.errors); + } else { + variableValues = coercedVariableValues.coerced; + } + } + + if (errors.length !== 0) { + return errors; + } + + !operation ? invariant(0, 'Has operation if no errors.') : void 0; + !variableValues ? invariant(0, 'Has variables if no errors.') : void 0; + return { + schema: schema, + fragments: fragments, + rootValue: rootValue, + contextValue: contextValue, + operation: operation, + variableValues: variableValues, + fieldResolver: fieldResolver || defaultFieldResolver, + errors: errors + }; +} +/** + * Implements the "Evaluating operations" section of the spec. + */ + +function executeOperation(exeContext, operation, rootValue) { + var type = getOperationRootType(exeContext.schema, operation); + var fields = collectFields(exeContext, type, operation.selectionSet, Object.create(null), Object.create(null)); + var path = undefined; // Errors from sub-fields of a NonNull type may propagate to the top level, + // at which point we still log the error and null the parent field, which + // in this case is the entire response. + // + // Similar to completeValueCatchingError. + + try { + var result = operation.operation === 'mutation' ? executeFieldsSerially(exeContext, type, rootValue, path, fields) : executeFields(exeContext, type, rootValue, path, fields); + + if (isPromise(result)) { + return result.then(undefined, function (error) { + exeContext.errors.push(error); + return Promise.resolve(null); + }); + } + + return result; + } catch (error) { + exeContext.errors.push(error); + return null; + } +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "write" mode. + */ + + +function executeFieldsSerially(exeContext, parentType, sourceValue, path, fields) { + return promiseReduce(Object.keys(fields), function (results, responseName) { + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result === undefined) { + return results; + } + + if (isPromise(result)) { + return result.then(function (resolvedResult) { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, Object.create(null)); +} +/** + * Implements the "Evaluating selection sets" section of the spec + * for "read" mode. + */ + + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + var results = Object.create(null); + var containsPromise = false; + + for (var i = 0, keys = Object.keys(fields); i < keys.length; ++i) { + var responseName = keys[i]; + var fieldNodes = fields[responseName]; + var fieldPath = addPath(path, responseName); + var result = resolveField(exeContext, parentType, sourceValue, fieldNodes, fieldPath); + + if (result !== undefined) { + results[responseName] = result; + + if (!containsPromise && isPromise(result)) { + containsPromise = true; + } + } + } // If there are no promises, we can just return the object + + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + + return promiseForObject(results); +} +/** + * Given a selectionSet, adds all of the fields in that selection to + * the passed in map of fields, and returns it at the end. + * + * CollectFields requires the "runtime type" of an object. For a field which + * returns an Interface or Union type, the "runtime type" will be the actual + * Object type returned by that field. + */ + + +export function collectFields(exeContext, runtimeType, selectionSet, fields, visitedFragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case Kind.FIELD: + if (!shouldIncludeNode(exeContext, selection)) { + continue; + } + + var name = getFieldEntryKey(selection); + + if (!fields[name]) { + fields[name] = []; + } + + fields[name].push(selection); + break; + + case Kind.INLINE_FRAGMENT: + if (!shouldIncludeNode(exeContext, selection) || !doesFragmentConditionMatch(exeContext, selection, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames); + break; + + case Kind.FRAGMENT_SPREAD: + var fragName = selection.name.value; + + if (visitedFragmentNames[fragName] || !shouldIncludeNode(exeContext, selection)) { + continue; + } + + visitedFragmentNames[fragName] = true; + var fragment = exeContext.fragments[fragName]; + + if (!fragment || !doesFragmentConditionMatch(exeContext, fragment, runtimeType)) { + continue; + } + + collectFields(exeContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames); + break; + } + } + + return fields; +} +/** + * Determines if a field should be included based on the @include and @skip + * directives, where @skip has higher precedence than @include. + */ + +function shouldIncludeNode(exeContext, node) { + var skip = getDirectiveValues(GraphQLSkipDirective, node, exeContext.variableValues); + + if (skip && skip.if === true) { + return false; + } + + var include = getDirectiveValues(GraphQLIncludeDirective, node, exeContext.variableValues); + + if (include && include.if === false) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + */ + + +function doesFragmentConditionMatch(exeContext, fragment, type) { + var typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + var conditionalType = typeFromAST(exeContext.schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if (isAbstractType(conditionalType)) { + return exeContext.schema.isPossibleType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + */ + + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} +/** + * Resolves the field on the given source object. In particular, this + * figures out the value that the field returns by calling its resolve function, + * then calls completeValue to complete promises, serialize scalars, or execute + * the sub-selection-set for objects. + */ + + +function resolveField(exeContext, parentType, source, fieldNodes, path) { + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(exeContext.schema, parentType, fieldName); + + if (!fieldDef) { + return; + } + + var resolveFn = fieldDef.resolve || exeContext.fieldResolver; + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path); // Get the resolve function, regardless of if its result is normal + // or abrupt (error). + + var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info); + return completeValueCatchingError(exeContext, fieldDef.type, fieldNodes, info, path, result); +} + +export function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes: fieldNodes, + returnType: fieldDef.type, + parentType: parentType, + path: path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues + }; +} // Isolates the "ReturnOrAbrupt" behavior to not de-opt the `resolveField` +// function. Returns the result of resolveFn or the abrupt-return Error object. + +export function resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, source, info) { + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + var args = getArgumentValues(fieldDef, fieldNodes[0], exeContext.variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + var _contextValue = exeContext.contextValue; + var result = resolveFn(source, args, _contextValue, info); + return isPromise(result) ? result.then(undefined, asErrorInstance) : result; + } catch (error) { + return asErrorInstance(error); + } +} // Sometimes a non-error is thrown, wrap it as an Error instance to ensure a +// consistent Error interface. + +function asErrorInstance(error) { + return error instanceof Error ? error : new Error(error || undefined); +} // This is a small wrapper around completeValue which detects and logs errors +// in the execution context. + + +function completeValueCatchingError(exeContext, returnType, fieldNodes, info, path, result) { + try { + var completed; + + if (isPromise(result)) { + completed = result.then(function (resolved) { + return completeValue(exeContext, returnType, fieldNodes, info, path, resolved); + }); + } else { + completed = completeValue(exeContext, returnType, fieldNodes, info, path, result); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, function (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + }); + } + + return completed; + } catch (error) { + return handleFieldError(error, fieldNodes, path, returnType, exeContext); + } +} + +function handleFieldError(rawError, fieldNodes, path, returnType, exeContext) { + var error = locatedError(asErrorInstance(rawError), fieldNodes, responsePathAsArray(path)); // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + + if (isNonNullType(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + + exeContext.errors.push(error); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Field entries" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by evaluating all sub-selections. + */ + + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + + if (isNonNullType(returnType)) { + var completed = completeValue(exeContext, returnType.ofType, fieldNodes, info, path, result); + + if (completed === null) { + throw new Error("Cannot return null for non-nullable field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")); + } + + return completed; + } // If result value is null-ish (null, undefined, or NaN) then return null. + + + if (isNullish(result)) { + return null; + } // If field type is List, complete each item in the list with the inner type + + + if (isListType(returnType)) { + return completeListValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + + if (isAbstractType(returnType)) { + return completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result); + } // If field type is Object, execute and complete all sub-selections. + + + if (isObjectType(returnType)) { + return completeObjectValue(exeContext, returnType, fieldNodes, info, path, result); + } // Not reachable. All possible output types have been considered. + + /* istanbul ignore next */ + + + throw new Error("Cannot complete value of unexpected type \"".concat(inspect(returnType), "\".")); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + */ + + +function completeListValue(exeContext, returnType, fieldNodes, info, path, result) { + !isCollection(result) ? invariant(0, "Expected Iterable, but did not find one for field ".concat(info.parentType.name, ".").concat(info.fieldName, ".")) : void 0; // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + var itemType = returnType.ofType; + var containsPromise = false; + var completedResults = []; + forEach(result, function (item, index) { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + var fieldPath = addPath(path, index); + var completedItem = completeValueCatchingError(exeContext, itemType, fieldNodes, info, fieldPath, item); + + if (!containsPromise && isPromise(completedItem)) { + containsPromise = true; + } + + completedResults.push(completedItem); + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + */ + + +function completeLeafValue(returnType, result) { + !returnType.serialize ? invariant(0, 'Missing serialize method on type') : void 0; + var serializedResult = returnType.serialize(result); + + if (isInvalid(serializedResult)) { + throw new Error("Expected a value of type \"".concat(inspect(returnType), "\" but ") + "received: ".concat(inspect(result))); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + */ + + +function completeAbstractValue(exeContext, returnType, fieldNodes, info, path, result) { + var runtimeType = returnType.resolveType ? returnType.resolveType(result, exeContext.contextValue, info) : defaultResolveTypeFn(result, exeContext.contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then(function (resolvedRuntimeType) { + return completeObjectValue(exeContext, ensureValidRuntimeType(resolvedRuntimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); + }); + } + + return completeObjectValue(exeContext, ensureValidRuntimeType(runtimeType, exeContext, returnType, fieldNodes, info, result), fieldNodes, info, path, result); +} + +function ensureValidRuntimeType(runtimeTypeOrName, exeContext, returnType, fieldNodes, info, result) { + var runtimeType = typeof runtimeTypeOrName === 'string' ? exeContext.schema.getType(runtimeTypeOrName) : runtimeTypeOrName; + + if (!isObjectType(runtimeType)) { + throw new GraphQLError("Abstract type ".concat(returnType.name, " must resolve to an Object type at ") + "runtime for field ".concat(info.parentType.name, ".").concat(info.fieldName, " with ") + "value ".concat(inspect(result), ", received \"").concat(inspect(runtimeType), "\". ") + "Either the ".concat(returnType.name, " type should provide a \"resolveType\" ") + 'function or each possible type should provide an "isTypeOf" function.', fieldNodes); + } + + if (!exeContext.schema.isPossibleType(returnType, runtimeType)) { + throw new GraphQLError("Runtime Object type \"".concat(runtimeType.name, "\" is not a possible type ") + "for \"".concat(returnType.name, "\"."), fieldNodes); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + */ + + +function completeObjectValue(exeContext, returnType, fieldNodes, info, path, result) { + // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + if (returnType.isTypeOf) { + var isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then(function (resolvedIsTypeOf) { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new GraphQLError("Expected value of type \"".concat(returnType.name, "\" but got: ").concat(inspect(result), "."), fieldNodes); +} + +function collectAndExecuteSubfields(exeContext, returnType, fieldNodes, path, result) { + // Collect sub-fields to execute to complete this value. + var subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + */ + + +var collectSubfields = memoize3(_collectSubfields); + +function _collectSubfields(exeContext, returnType, fieldNodes) { + var subFieldNodes = Object.create(null); + var visitedFragmentNames = Object.create(null); + + for (var i = 0; i < fieldNodes.length; i++) { + var selectionSet = fieldNodes[i].selectionSet; + + if (selectionSet) { + subFieldNodes = collectFields(exeContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames); + } + } + + return subFieldNodes; +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + + +function defaultResolveTypeFn(value, contextValue, info, abstractType) { + // First, look for `__typename`. + if (value !== null && _typeof(value) === 'object' && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + + var possibleTypes = info.schema.getPossibleTypes(abstractType); + var promisedIsTypeOfResults = []; + + for (var i = 0; i < possibleTypes.length; i++) { + var type = possibleTypes[i]; + + if (type.isTypeOf) { + var isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + return type; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then(function (isTypeOfResults) { + for (var _i = 0; _i < isTypeOfResults.length; _i++) { + if (isTypeOfResults[_i]) { + return possibleTypes[_i]; + } + } + }); + } +} +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + + +export var defaultFieldResolver = function defaultFieldResolver(source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if (_typeof(source) === 'object' || typeof source === 'function') { + var property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the two introspection fields, __schema + * and __typename. __typename is special because it can always be + * queried as a field, even in situations where no other fields + * are allowed, like on a Union. __schema could get automatically + * added to the query type, but that would require mutating type + * definitions, which would cause issues. + */ + +export function getFieldDef(schema, parentType, fieldName) { + if (fieldName === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return SchemaMetaFieldDef; + } else if (fieldName === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} \ No newline at end of file diff --git a/node_modules/graphql/execution/index.js b/node_modules/graphql/execution/index.js new file mode 100644 index 00000000..77f12743 --- /dev/null +++ b/node_modules/graphql/execution/index.js @@ -0,0 +1,33 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "execute", { + enumerable: true, + get: function get() { + return _execute.execute; + } +}); +Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function get() { + return _execute.defaultFieldResolver; + } +}); +Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function get() { + return _execute.responsePathAsArray; + } +}); +Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function get() { + return _values.getDirectiveValues; + } +}); + +var _execute = require("./execute"); + +var _values = require("./values"); \ No newline at end of file diff --git a/node_modules/graphql/execution/index.js.flow b/node_modules/graphql/execution/index.js.flow new file mode 100644 index 00000000..d793e261 --- /dev/null +++ b/node_modules/graphql/execution/index.js.flow @@ -0,0 +1,13 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { execute, defaultFieldResolver, responsePathAsArray } from './execute'; +export { getDirectiveValues } from './values'; + +export type { ExecutionArgs, ExecutionResult } from './execute'; diff --git a/node_modules/graphql/execution/index.mjs b/node_modules/graphql/execution/index.mjs new file mode 100644 index 00000000..66db93af --- /dev/null +++ b/node_modules/graphql/execution/index.mjs @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { execute, defaultFieldResolver, responsePathAsArray } from './execute'; +export { getDirectiveValues } from './values'; \ No newline at end of file diff --git a/node_modules/graphql/execution/values.js b/node_modules/graphql/execution/values.js new file mode 100644 index 00000000..d9d9d7d3 --- /dev/null +++ b/node_modules/graphql/execution/values.js @@ -0,0 +1,240 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getVariableValues = getVariableValues; +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; + +var _GraphQLError = require("../error/GraphQLError"); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _coerceValue = require("../utilities/coerceValue"); + +var _typeFromAST = require("../utilities/typeFromAST"); + +var _valueFromAST = require("../utilities/valueFromAST"); + +var _kinds = require("../language/kinds"); + +var _printer = require("../language/printer"); + +var _definition = require("../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +function getVariableValues(schema, varDefNodes, inputs) { + var errors = []; + var coercedValues = {}; + + for (var i = 0; i < varDefNodes.length; i++) { + var varDefNode = varDefNodes[i]; + var varName = varDefNode.variable.name.value; + var varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + errors.push(new _GraphQLError.GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat((0, _printer.print)(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type])); + } else { + var hasValue = hasOwnProperty(inputs, varName); + var value = hasValue ? inputs[varName] : undefined; + + if (!hasValue && varDefNode.defaultValue) { + // If no value was provided to a variable with a default value, + // use the default value. + coercedValues[varName] = (0, _valueFromAST.valueFromAST)(varDefNode.defaultValue, varType); + } else if ((!hasValue || value === null) && (0, _definition.isNonNullType)(varType)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + errors.push(new _GraphQLError.GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat((0, _inspect.default)(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat((0, _inspect.default)(varType), "\" was not provided."), [varDefNode])); + } else if (hasValue) { + if (value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + var coerced = (0, _coerceValue.coerceValue)(value, varType, varDefNode); + var coercionErrors = coerced.errors; + + if (coercionErrors) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var error = _step.value; + error.message = "Variable \"$".concat(varName, "\" got invalid value ").concat((0, _inspect.default)(value), "; ") + error.message; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + errors.push.apply(errors, coercionErrors); + } else { + coercedValues[varName] = coerced.value; + } + } + } + } + } + + return errors.length === 0 ? { + errors: undefined, + coerced: coercedValues + } : { + errors: errors, + coerced: undefined + }; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + +function getArgumentValues(def, node, variableValues) { + var coercedValues = {}; + var argDefs = def.args; + var argNodes = node.arguments; + + if (!argDefs || !argNodes) { + return coercedValues; + } + + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + + for (var i = 0; i < argDefs.length; i++) { + var argDef = argDefs[i]; + var name = argDef.name; + var argType = argDef.type; + var argumentNode = argNodeMap[name]; + var hasValue = void 0; + var isNull = void 0; + + if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) { + var variableName = argumentNode.value.name.value; + hasValue = variableValues && hasOwnProperty(variableValues, variableName); + isNull = variableValues && variableValues[variableName] === null; + } else { + hasValue = argumentNode != null; + isNull = argumentNode && argumentNode.value.kind === _kinds.Kind.NULL; + } + + if (!hasValue && argDef.defaultValue !== undefined) { + // If no argument was provided where the definition has a default value, + // use the default value. + coercedValues[name] = argDef.defaultValue; + } else if ((!hasValue || isNull) && (0, _definition.isNonNullType)(argType)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if (isNull) { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat((0, _inspect.default)(argType), "\" ") + 'must not be null.', [argumentNode.value]); + } else if (argumentNode && argumentNode.value.kind === _kinds.Kind.VARIABLE) { + var _variableName = argumentNode.value.name.value; + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]); + } else { + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" of required type \"").concat((0, _inspect.default)(argType), "\" ") + 'was not provided.', [node]); + } + } else if (hasValue) { + if (argumentNode.value.kind === _kinds.Kind.NULL) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[name] = null; + } else if (argumentNode.value.kind === _kinds.Kind.VARIABLE) { + var _variableName2 = argumentNode.value.name.value; + !variableValues ? (0, _invariant.default)(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + coercedValues[name] = variableValues[_variableName2]; + } else { + var valueNode = argumentNode.value; + var coercedValue = (0, _valueFromAST.valueFromAST)(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectType validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat((0, _printer.print)(valueNode), "."), [argumentNode.value]); + } + + coercedValues[name] = coercedValue; + } + } + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + + +function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && (0, _find.default)(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} \ No newline at end of file diff --git a/node_modules/graphql/execution/values.js.flow b/node_modules/graphql/execution/values.js.flow new file mode 100644 index 00000000..db9bef6d --- /dev/null +++ b/node_modules/graphql/execution/values.js.flow @@ -0,0 +1,242 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import find from '../jsutils/find'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import { coerceValue } from '../utilities/coerceValue'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { valueFromAST } from '../utilities/valueFromAST'; +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; +import { isInputType, isNonNullType } from '../type/definition'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { GraphQLField } from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +import type { + FieldNode, + DirectiveNode, + VariableDefinitionNode, +} from '../language/ast'; + +type CoercedVariableValues = {| + errors: $ReadOnlyArray | void, + coerced: { [variable: string]: mixed } | void, +|}; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getVariableValues( + schema: GraphQLSchema, + varDefNodes: Array, + inputs: ObjMap, +): CoercedVariableValues { + const errors = []; + const coercedValues = {}; + for (let i = 0; i < varDefNodes.length; i++) { + const varDefNode = varDefNodes[i]; + const varName = varDefNode.variable.name.value; + const varType = typeFromAST(schema, varDefNode.type); + if (!isInputType(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + errors.push( + new GraphQLError( + `Variable "$${varName}" expected value of type ` + + `"${print( + varDefNode.type, + )}" which cannot be used as an input type.`, + [varDefNode.type], + ), + ); + } else { + const hasValue = hasOwnProperty(inputs, varName); + const value = hasValue ? inputs[varName] : undefined; + if (!hasValue && varDefNode.defaultValue) { + // If no value was provided to a variable with a default value, + // use the default value. + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if ((!hasValue || value === null) && isNonNullType(varType)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + errors.push( + new GraphQLError( + hasValue + ? `Variable "$${varName}" of non-null type ` + + `"${inspect(varType)}" must not be null.` + : `Variable "$${varName}" of required type ` + + `"${inspect(varType)}" was not provided.`, + [varDefNode], + ), + ); + } else if (hasValue) { + if (value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + const coerced = coerceValue(value, varType, varDefNode); + const coercionErrors = coerced.errors; + if (coercionErrors) { + for (const error of coercionErrors) { + error.message = + `Variable "$${varName}" got invalid value ${inspect(value)}; ` + + error.message; + } + errors.push(...coercionErrors); + } else { + coercedValues[varName] = coerced.value; + } + } + } + } + } + return errors.length === 0 + ? { errors: undefined, coerced: coercedValues } + : { errors, coerced: undefined }; +} + +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getArgumentValues( + def: GraphQLField<*, *> | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: ?ObjMap, +): { [argument: string]: mixed } { + const coercedValues = {}; + const argDefs = def.args; + const argNodes = node.arguments; + if (!argDefs || !argNodes) { + return coercedValues; + } + const argNodeMap = keyMap(argNodes, arg => arg.name.value); + for (let i = 0; i < argDefs.length; i++) { + const argDef = argDefs[i]; + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + let hasValue; + let isNull; + if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + const variableName = argumentNode.value.name.value; + hasValue = variableValues && hasOwnProperty(variableValues, variableName); + isNull = variableValues && variableValues[variableName] === null; + } else { + hasValue = argumentNode != null; + isNull = argumentNode && argumentNode.value.kind === Kind.NULL; + } + + if (!hasValue && argDef.defaultValue !== undefined) { + // If no argument was provided where the definition has a default value, + // use the default value. + coercedValues[name] = argDef.defaultValue; + } else if ((!hasValue || isNull) && isNonNullType(argType)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if (isNull) { + throw new GraphQLError( + `Argument "${name}" of non-null type "${inspect(argType)}" ` + + 'must not be null.', + [argumentNode.value], + ); + } else if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + const variableName = argumentNode.value.name.value; + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + `was provided the variable "$${variableName}" ` + + 'which was not provided a runtime value.', + [argumentNode.value], + ); + } else { + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + 'was not provided.', + [node], + ); + } + } else if (hasValue) { + if (argumentNode.value.kind === Kind.NULL) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[name] = null; + } else if (argumentNode.value.kind === Kind.VARIABLE) { + const variableName = argumentNode.value.name.value; + invariant(variableValues, 'Must exist for hasValue to be true.'); + // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + coercedValues[name] = variableValues[variableName]; + } else { + const valueNode = argumentNode.value; + const coercedValue = valueFromAST(valueNode, argType, variableValues); + if (coercedValue === undefined) { + // Note: ValuesOfCorrectType validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new GraphQLError( + `Argument "${name}" has invalid value ${print(valueNode)}.`, + [argumentNode.value], + ); + } + coercedValues[name] = coercedValue; + } + } + } + return coercedValues; +} + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getDirectiveValues( + directiveDef: GraphQLDirective, + node: { +directives?: $ReadOnlyArray }, + variableValues?: ?ObjMap, +): void | { [argument: string]: mixed } { + const directiveNode = + node.directives && + find( + node.directives, + directive => directive.name.value === directiveDef.name, + ); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj: mixed, prop: string): boolean { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/graphql/execution/values.mjs b/node_modules/graphql/execution/values.mjs new file mode 100644 index 00000000..b87623c8 --- /dev/null +++ b/node_modules/graphql/execution/values.mjs @@ -0,0 +1,216 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; +import find from '../jsutils/find'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import { coerceValue } from '../utilities/coerceValue'; +import { typeFromAST } from '../utilities/typeFromAST'; +import { valueFromAST } from '../utilities/valueFromAST'; +import { Kind } from '../language/kinds'; +import { print } from '../language/printer'; +import { isInputType, isNonNullType } from '../type/definition'; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, a GraphQLError will be thrown. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ +export function getVariableValues(schema, varDefNodes, inputs) { + var errors = []; + var coercedValues = {}; + + for (var i = 0; i < varDefNodes.length; i++) { + var varDefNode = varDefNodes[i]; + var varName = varDefNode.variable.name.value; + var varType = typeFromAST(schema, varDefNode.type); + + if (!isInputType(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + errors.push(new GraphQLError("Variable \"$".concat(varName, "\" expected value of type ") + "\"".concat(print(varDefNode.type), "\" which cannot be used as an input type."), [varDefNode.type])); + } else { + var hasValue = hasOwnProperty(inputs, varName); + var value = hasValue ? inputs[varName] : undefined; + + if (!hasValue && varDefNode.defaultValue) { + // If no value was provided to a variable with a default value, + // use the default value. + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if ((!hasValue || value === null) && isNonNullType(varType)) { + // If no value or a nullish value was provided to a variable with a + // non-null type (required), produce an error. + errors.push(new GraphQLError(hasValue ? "Variable \"$".concat(varName, "\" of non-null type ") + "\"".concat(inspect(varType), "\" must not be null.") : "Variable \"$".concat(varName, "\" of required type ") + "\"".concat(inspect(varType), "\" was not provided."), [varDefNode])); + } else if (hasValue) { + if (value === null) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[varName] = null; + } else { + // Otherwise, a non-null value was provided, coerce it to the expected + // type or report an error if coercion fails. + var coerced = coerceValue(value, varType, varDefNode); + var coercionErrors = coerced.errors; + + if (coercionErrors) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = coercionErrors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var error = _step.value; + error.message = "Variable \"$".concat(varName, "\" got invalid value ").concat(inspect(value), "; ") + error.message; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + errors.push.apply(errors, coercionErrors); + } else { + coercedValues[varName] = coerced.value; + } + } + } + } + } + + return errors.length === 0 ? { + errors: undefined, + coerced: coercedValues + } : { + errors: errors, + coerced: undefined + }; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + +export function getArgumentValues(def, node, variableValues) { + var coercedValues = {}; + var argDefs = def.args; + var argNodes = node.arguments; + + if (!argDefs || !argNodes) { + return coercedValues; + } + + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + + for (var i = 0; i < argDefs.length; i++) { + var argDef = argDefs[i]; + var name = argDef.name; + var argType = argDef.type; + var argumentNode = argNodeMap[name]; + var hasValue = void 0; + var isNull = void 0; + + if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + var variableName = argumentNode.value.name.value; + hasValue = variableValues && hasOwnProperty(variableValues, variableName); + isNull = variableValues && variableValues[variableName] === null; + } else { + hasValue = argumentNode != null; + isNull = argumentNode && argumentNode.value.kind === Kind.NULL; + } + + if (!hasValue && argDef.defaultValue !== undefined) { + // If no argument was provided where the definition has a default value, + // use the default value. + coercedValues[name] = argDef.defaultValue; + } else if ((!hasValue || isNull) && isNonNullType(argType)) { + // If no argument or a null value was provided to an argument with a + // non-null type (required), produce a field error. + if (isNull) { + throw new GraphQLError("Argument \"".concat(name, "\" of non-null type \"").concat(inspect(argType), "\" ") + 'must not be null.', [argumentNode.value]); + } else if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { + var _variableName = argumentNode.value.name.value; + throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + "was provided the variable \"$".concat(_variableName, "\" ") + 'which was not provided a runtime value.', [argumentNode.value]); + } else { + throw new GraphQLError("Argument \"".concat(name, "\" of required type \"").concat(inspect(argType), "\" ") + 'was not provided.', [node]); + } + } else if (hasValue) { + if (argumentNode.value.kind === Kind.NULL) { + // If the explicit value `null` was provided, an entry in the coerced + // values must exist as the value `null`. + coercedValues[name] = null; + } else if (argumentNode.value.kind === Kind.VARIABLE) { + var _variableName2 = argumentNode.value.name.value; + !variableValues ? invariant(0, 'Must exist for hasValue to be true.') : void 0; // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + coercedValues[name] = variableValues[_variableName2]; + } else { + var valueNode = argumentNode.value; + var coercedValue = valueFromAST(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectType validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new GraphQLError("Argument \"".concat(name, "\" has invalid value ").concat(print(valueNode), "."), [argumentNode.value]); + } + + coercedValues[name] = coercedValue; + } + } + } + + return coercedValues; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: The returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + */ + +export function getDirectiveValues(directiveDef, node, variableValues) { + var directiveNode = node.directives && find(node.directives, function (directive) { + return directive.name.value === directiveDef.name; + }); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} \ No newline at end of file diff --git a/node_modules/graphql/graphql.js b/node_modules/graphql/graphql.js new file mode 100644 index 00000000..42992f0b --- /dev/null +++ b/node_modules/graphql/graphql.js @@ -0,0 +1,87 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.graphql = graphql; +exports.graphqlSync = graphqlSync; + +var _validate = require("./type/validate"); + +var _parser = require("./language/parser"); + +var _validate2 = require("./validation/validate"); + +var _execute = require("./execution/execute"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + var _arguments = arguments; + + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(function (resolve) { + return resolve( // Extract arguments from object args if provided. + _arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver)); + }); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + + +function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous. + + if (result.then) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // Validate Schema + var schemaValidationErrors = (0, _validate.validateSchema)(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + + var document; + + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + + var validationErrors = (0, _validate2.validate)(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + + return (0, _execute.execute)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} \ No newline at end of file diff --git a/node_modules/graphql/graphql.js.flow b/node_modules/graphql/graphql.js.flow new file mode 100644 index 00000000..ab930166 --- /dev/null +++ b/node_modules/graphql/graphql.js.flow @@ -0,0 +1,209 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { validateSchema } from './type/validate'; +import { parse } from './language/parser'; +import { validate } from './validation/validate'; +import { execute } from './execution/execute'; +import type { ObjMap } from './jsutils/ObjMap'; +import type { Source } from './language/source'; +import type { GraphQLFieldResolver } from './type/definition'; +import type { GraphQLSchema } from './type/schema'; +import type { ExecutionResult } from './execution/execute'; +import type { MaybePromise } from './jsutils/MaybePromise'; + +/** + * This is the primary entry point function for fulfilling GraphQL operations + * by parsing, validating, and executing a GraphQL document along side a + * GraphQL schema. + * + * More sophisticated GraphQL servers, such as those which persist queries, + * may wish to separate the validation and execution phases to a static time + * tooling step, and a server runtime step. + * + * Accepts either an object with named arguments, or individual arguments: + * + * schema: + * The GraphQL type system to use when validating and executing a query. + * source: + * A GraphQL language formatted string representing the requested operation. + * rootValue: + * The value provided as the first argument to resolver functions on the top + * level type (e.g. the query object type). + * contextValue: + * The context value is provided as an argument to resolver functions after + * field arguments. It is used to pass shared information useful at any point + * during executing this query, for example the currently logged in user and + * connections to databases or other services. + * variableValues: + * A mapping of variable name to runtime value to use for all variables + * defined in the requestString. + * operationName: + * The name of the operation to use if requestString contains multiple + * possible operations. Can be omitted if requestString contains only + * one operation. + * fieldResolver: + * A resolver function to use when one is not provided by the schema. + * If not provided, the default field resolver is used (which looks for a + * value or method on the source value with the field's name). + */ +export type GraphQLArgs = {| + schema: GraphQLSchema, + source: string | Source, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +|}; +declare function graphql(GraphQLArgs, ..._: []): Promise; +/* eslint-disable no-redeclare */ +declare function graphql( + schema: GraphQLSchema, + source: Source | string, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): Promise; +export function graphql( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(resolve => + resolve( + // Extract arguments from object args if provided. + arguments.length === 1 + ? graphqlImpl( + argsOrSchema.schema, + argsOrSchema.source, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + ) + : graphqlImpl( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ), + ), + ); +} + +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ +declare function graphqlSync(GraphQLArgs, ..._: []): ExecutionResult; +/* eslint-disable no-redeclare */ +declare function graphqlSync( + schema: GraphQLSchema, + source: Source | string, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): ExecutionResult; +export function graphqlSync( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + const result = + arguments.length === 1 + ? graphqlImpl( + argsOrSchema.schema, + argsOrSchema.source, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + ) + : graphqlImpl( + argsOrSchema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Assert that the execution was synchronous. + if (result.then) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl( + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, +): MaybePromise { + // Validate Schema + const schemaValidationErrors = validateSchema(schema); + if (schemaValidationErrors.length > 0) { + return { errors: schemaValidationErrors }; + } + + // Parse + let document; + try { + document = parse(source); + } catch (syntaxError) { + return { errors: [syntaxError] }; + } + + // Validate + const validationErrors = validate(schema, document); + if (validationErrors.length > 0) { + return { errors: validationErrors }; + } + + // Execute + return execute( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); +} diff --git a/node_modules/graphql/graphql.mjs b/node_modules/graphql/graphql.mjs new file mode 100644 index 00000000..af7509a0 --- /dev/null +++ b/node_modules/graphql/graphql.mjs @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { validateSchema } from './type/validate'; +import { parse } from './language/parser'; +import { validate } from './validation/validate'; +import { execute } from './execution/execute'; +export function graphql(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + var _arguments = arguments; + + /* eslint-enable no-redeclare */ + // Always return a Promise for a consistent API. + return new Promise(function (resolve) { + return resolve( // Extract arguments from object args if provided. + _arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver)); + }); +} +/** + * The graphqlSync function also fulfills GraphQL operations by parsing, + * validating, and executing a GraphQL document along side a GraphQL schema. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + */ + +export function graphqlSync(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + var result = arguments.length === 1 ? graphqlImpl(argsOrSchema.schema, argsOrSchema.source, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver) : graphqlImpl(argsOrSchema, source, rootValue, contextValue, variableValues, operationName, fieldResolver); // Assert that the execution was synchronous. + + if (result.then) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(schema, source, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // Validate Schema + var schemaValidationErrors = validateSchema(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors + }; + } // Parse + + + var document; + + try { + document = parse(source); + } catch (syntaxError) { + return { + errors: [syntaxError] + }; + } // Validate + + + var validationErrors = validate(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors + }; + } // Execute + + + return execute(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); +} \ No newline at end of file diff --git a/node_modules/graphql/index.js b/node_modules/graphql/index.js new file mode 100644 index 00000000..c6e8f0c8 --- /dev/null +++ b/node_modules/graphql/index.js @@ -0,0 +1,1071 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "graphql", { + enumerable: true, + get: function get() { + return _graphql.graphql; + } +}); +Object.defineProperty(exports, "graphqlSync", { + enumerable: true, + get: function get() { + return _graphql.graphqlSync; + } +}); +Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function get() { + return _type.GraphQLSchema; + } +}); +Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function get() { + return _type.GraphQLScalarType; + } +}); +Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function get() { + return _type.GraphQLObjectType; + } +}); +Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function get() { + return _type.GraphQLInterfaceType; + } +}); +Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function get() { + return _type.GraphQLUnionType; + } +}); +Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function get() { + return _type.GraphQLEnumType; + } +}); +Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function get() { + return _type.GraphQLInputObjectType; + } +}); +Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function get() { + return _type.GraphQLList; + } +}); +Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function get() { + return _type.GraphQLNonNull; + } +}); +Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLDirective; + } +}); +Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function get() { + return _type.TypeKind; + } +}); +Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function get() { + return _type.specifiedScalarTypes; + } +}); +Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function get() { + return _type.GraphQLInt; + } +}); +Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function get() { + return _type.GraphQLFloat; + } +}); +Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function get() { + return _type.GraphQLString; + } +}); +Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function get() { + return _type.GraphQLBoolean; + } +}); +Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function get() { + return _type.GraphQLID; + } +}); +Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function get() { + return _type.specifiedDirectives; + } +}); +Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLIncludeDirective; + } +}); +Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLSkipDirective; + } +}); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function get() { + return _type.GraphQLDeprecatedDirective; + } +}); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function get() { + return _type.DEFAULT_DEPRECATION_REASON; + } +}); +Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function get() { + return _type.SchemaMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function get() { + return _type.TypeMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function get() { + return _type.TypeNameMetaFieldDef; + } +}); +Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function get() { + return _type.introspectionTypes; + } +}); +Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function get() { + return _type.__Schema; + } +}); +Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function get() { + return _type.__Directive; + } +}); +Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function get() { + return _type.__DirectiveLocation; + } +}); +Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function get() { + return _type.__Type; + } +}); +Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function get() { + return _type.__Field; + } +}); +Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function get() { + return _type.__InputValue; + } +}); +Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function get() { + return _type.__EnumValue; + } +}); +Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function get() { + return _type.__TypeKind; + } +}); +Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function get() { + return _type.isSchema; + } +}); +Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function get() { + return _type.isDirective; + } +}); +Object.defineProperty(exports, "isType", { + enumerable: true, + get: function get() { + return _type.isType; + } +}); +Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function get() { + return _type.isScalarType; + } +}); +Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function get() { + return _type.isObjectType; + } +}); +Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function get() { + return _type.isInterfaceType; + } +}); +Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function get() { + return _type.isUnionType; + } +}); +Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function get() { + return _type.isEnumType; + } +}); +Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function get() { + return _type.isInputObjectType; + } +}); +Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function get() { + return _type.isListType; + } +}); +Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function get() { + return _type.isNonNullType; + } +}); +Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function get() { + return _type.isInputType; + } +}); +Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function get() { + return _type.isOutputType; + } +}); +Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function get() { + return _type.isLeafType; + } +}); +Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function get() { + return _type.isCompositeType; + } +}); +Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function get() { + return _type.isAbstractType; + } +}); +Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function get() { + return _type.isWrappingType; + } +}); +Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function get() { + return _type.isNullableType; + } +}); +Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function get() { + return _type.isNamedType; + } +}); +Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function get() { + return _type.isRequiredArgument; + } +}); +Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function get() { + return _type.isRequiredInputField; + } +}); +Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function get() { + return _type.isSpecifiedScalarType; + } +}); +Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function get() { + return _type.isIntrospectionType; + } +}); +Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function get() { + return _type.isSpecifiedDirective; + } +}); +Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function get() { + return _type.assertType; + } +}); +Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function get() { + return _type.assertScalarType; + } +}); +Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function get() { + return _type.assertObjectType; + } +}); +Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function get() { + return _type.assertInterfaceType; + } +}); +Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function get() { + return _type.assertUnionType; + } +}); +Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function get() { + return _type.assertEnumType; + } +}); +Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function get() { + return _type.assertInputObjectType; + } +}); +Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function get() { + return _type.assertListType; + } +}); +Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function get() { + return _type.assertNonNullType; + } +}); +Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function get() { + return _type.assertInputType; + } +}); +Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function get() { + return _type.assertOutputType; + } +}); +Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function get() { + return _type.assertLeafType; + } +}); +Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function get() { + return _type.assertCompositeType; + } +}); +Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function get() { + return _type.assertAbstractType; + } +}); +Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function get() { + return _type.assertWrappingType; + } +}); +Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function get() { + return _type.assertNullableType; + } +}); +Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function get() { + return _type.assertNamedType; + } +}); +Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function get() { + return _type.getNullableType; + } +}); +Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function get() { + return _type.getNamedType; + } +}); +Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function get() { + return _type.validateSchema; + } +}); +Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function get() { + return _type.assertValidSchema; + } +}); +Object.defineProperty(exports, "Source", { + enumerable: true, + get: function get() { + return _language.Source; + } +}); +Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function get() { + return _language.getLocation; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _language.parse; + } +}); +Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function get() { + return _language.parseValue; + } +}); +Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function get() { + return _language.parseType; + } +}); +Object.defineProperty(exports, "print", { + enumerable: true, + get: function get() { + return _language.print; + } +}); +Object.defineProperty(exports, "visit", { + enumerable: true, + get: function get() { + return _language.visit; + } +}); +Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function get() { + return _language.visitInParallel; + } +}); +Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function get() { + return _language.visitWithTypeInfo; + } +}); +Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function get() { + return _language.getVisitFn; + } +}); +Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function get() { + return _language.Kind; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _language.TokenKind; + } +}); +Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function get() { + return _language.DirectiveLocation; + } +}); +Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function get() { + return _language.BREAK; + } +}); +Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isDefinitionNode; + } +}); +Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isExecutableDefinitionNode; + } +}); +Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function get() { + return _language.isSelectionNode; + } +}); +Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function get() { + return _language.isValueNode; + } +}); +Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function get() { + return _language.isTypeNode; + } +}); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isTypeSystemDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function get() { + return _language.isTypeDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function get() { + return _language.isTypeSystemExtensionNode; + } +}); +Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function get() { + return _language.isTypeExtensionNode; + } +}); +Object.defineProperty(exports, "execute", { + enumerable: true, + get: function get() { + return _execution.execute; + } +}); +Object.defineProperty(exports, "defaultFieldResolver", { + enumerable: true, + get: function get() { + return _execution.defaultFieldResolver; + } +}); +Object.defineProperty(exports, "responsePathAsArray", { + enumerable: true, + get: function get() { + return _execution.responsePathAsArray; + } +}); +Object.defineProperty(exports, "getDirectiveValues", { + enumerable: true, + get: function get() { + return _execution.getDirectiveValues; + } +}); +Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function get() { + return _subscription.subscribe; + } +}); +Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function get() { + return _subscription.createSourceEventStream; + } +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validation.validate; + } +}); +Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function get() { + return _validation.ValidationContext; + } +}); +Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function get() { + return _validation.specifiedRules; + } +}); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function get() { + return _validation.FieldsOnCorrectTypeRule; + } +}); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function get() { + return _validation.FragmentsOnCompositeTypesRule; + } +}); +Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function get() { + return _validation.KnownArgumentNamesRule; + } +}); +Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function get() { + return _validation.KnownDirectivesRule; + } +}); +Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function get() { + return _validation.KnownFragmentNamesRule; + } +}); +Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function get() { + return _validation.KnownTypeNamesRule; + } +}); +Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function get() { + return _validation.LoneAnonymousOperationRule; + } +}); +Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function get() { + return _validation.NoFragmentCyclesRule; + } +}); +Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function get() { + return _validation.NoUndefinedVariablesRule; + } +}); +Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function get() { + return _validation.NoUnusedFragmentsRule; + } +}); +Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function get() { + return _validation.NoUnusedVariablesRule; + } +}); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function get() { + return _validation.OverlappingFieldsCanBeMergedRule; + } +}); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function get() { + return _validation.PossibleFragmentSpreadsRule; + } +}); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function get() { + return _validation.ProvidedRequiredArgumentsRule; + } +}); +Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function get() { + return _validation.ScalarLeafsRule; + } +}); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function get() { + return _validation.SingleFieldSubscriptionsRule; + } +}); +Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueArgumentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function get() { + return _validation.UniqueDirectivesPerLocationRule; + } +}); +Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueFragmentNamesRule; + } +}); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueInputFieldNamesRule; + } +}); +Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueOperationNamesRule; + } +}); +Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function get() { + return _validation.UniqueVariableNamesRule; + } +}); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function get() { + return _validation.ValuesOfCorrectTypeRule; + } +}); +Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function get() { + return _validation.VariablesAreInputTypesRule; + } +}); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function get() { + return _validation.VariablesInAllowedPositionRule; + } +}); +Object.defineProperty(exports, "GraphQLError", { + enumerable: true, + get: function get() { + return _error.GraphQLError; + } +}); +Object.defineProperty(exports, "formatError", { + enumerable: true, + get: function get() { + return _error.formatError; + } +}); +Object.defineProperty(exports, "printError", { + enumerable: true, + get: function get() { + return _error.printError; + } +}); +Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function get() { + return _utilities.getIntrospectionQuery; + } +}); +Object.defineProperty(exports, "introspectionQuery", { + enumerable: true, + get: function get() { + return _utilities.introspectionQuery; + } +}); +Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function get() { + return _utilities.getOperationAST; + } +}); +Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function get() { + return _utilities.getOperationRootType; + } +}); +Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function get() { + return _utilities.introspectionFromSchema; + } +}); +Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function get() { + return _utilities.buildClientSchema; + } +}); +Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function get() { + return _utilities.buildASTSchema; + } +}); +Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function get() { + return _utilities.buildSchema; + } +}); +Object.defineProperty(exports, "getDescription", { + enumerable: true, + get: function get() { + return _utilities.getDescription; + } +}); +Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function get() { + return _utilities.extendSchema; + } +}); +Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function get() { + return _utilities.lexicographicSortSchema; + } +}); +Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function get() { + return _utilities.printSchema; + } +}); +Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function get() { + return _utilities.printIntrospectionSchema; + } +}); +Object.defineProperty(exports, "printType", { + enumerable: true, + get: function get() { + return _utilities.printType; + } +}); +Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function get() { + return _utilities.typeFromAST; + } +}); +Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function get() { + return _utilities.valueFromAST; + } +}); +Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function get() { + return _utilities.valueFromASTUntyped; + } +}); +Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function get() { + return _utilities.astFromValue; + } +}); +Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function get() { + return _utilities.TypeInfo; + } +}); +Object.defineProperty(exports, "coerceValue", { + enumerable: true, + get: function get() { + return _utilities.coerceValue; + } +}); +Object.defineProperty(exports, "isValidJSValue", { + enumerable: true, + get: function get() { + return _utilities.isValidJSValue; + } +}); +Object.defineProperty(exports, "isValidLiteralValue", { + enumerable: true, + get: function get() { + return _utilities.isValidLiteralValue; + } +}); +Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function get() { + return _utilities.concatAST; + } +}); +Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function get() { + return _utilities.separateOperations; + } +}); +Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function get() { + return _utilities.isEqualType; + } +}); +Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function get() { + return _utilities.isTypeSubTypeOf; + } +}); +Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function get() { + return _utilities.doTypesOverlap; + } +}); +Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function get() { + return _utilities.assertValidName; + } +}); +Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function get() { + return _utilities.isValidNameError; + } +}); +Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function get() { + return _utilities.findBreakingChanges; + } +}); +Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function get() { + return _utilities.findDangerousChanges; + } +}); +Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function get() { + return _utilities.BreakingChangeType; + } +}); +Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function get() { + return _utilities.DangerousChangeType; + } +}); +Object.defineProperty(exports, "findDeprecatedUsages", { + enumerable: true, + get: function get() { + return _utilities.findDeprecatedUsages; + } +}); + +var _graphql = require("./graphql"); + +var _type = require("./type"); + +var _language = require("./language"); + +var _execution = require("./execution"); + +var _subscription = require("./subscription"); + +var _validation = require("./validation"); + +var _error = require("./error"); + +var _utilities = require("./utilities"); \ No newline at end of file diff --git a/node_modules/graphql/index.js.flow b/node_modules/graphql/index.js.flow new file mode 100644 index 00000000..3c4ee540 --- /dev/null +++ b/node_modules/graphql/index.js.flow @@ -0,0 +1,429 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ + +// The primary entry point into fulfilling a GraphQL request. +export type { GraphQLArgs } from './graphql'; +export { graphql, graphqlSync } from './graphql'; + +// Create and operate on GraphQL type definitions and schema. +export { + GraphQLSchema, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + GraphQLDirective, + // "Enum" of Type Kinds + TypeKind, + // Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, + // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Predicates + isSchema, + isDirective, + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + isSpecifiedScalarType, + isIntrospectionType, + isSpecifiedDirective, + // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Validate GraphQL schema. + validateSchema, + assertValidSchema, +} from './type'; + +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLSchemaConfig, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLDirectiveConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './type'; + +// Parse and operate on GraphQL language source files. +export { + Source, + getLocation, + // Parse + parse, + parseValue, + parseType, + // Print + print, + // Visit + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + Kind, + TokenKind, + DirectiveLocation, + BREAK, + // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './language'; + +export type { + Lexer, + ParseOptions, + SourceLocation, + // Visitor utilities + ASTVisitor, + Visitor, + VisitFn, + VisitorKeyMap, + // AST nodes + Location, + Token, + ASTNode, + ASTKindToNode, + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + KindEnum, + TokenKindEnum, + DirectiveLocationEnum, +} from './language'; + +// Execute GraphQL queries. +export { + execute, + defaultFieldResolver, + responsePathAsArray, + getDirectiveValues, +} from './execution'; + +export type { ExecutionArgs, ExecutionResult } from './execution'; + +export { subscribe, createSourceEventStream } from './subscription'; + +// Validate GraphQL queries. +export { + validate, + ValidationContext, + // All validation rules in the GraphQL Specification. + specifiedRules, + // Individual validation rules. + FieldsOnCorrectTypeRule, + FragmentsOnCompositeTypesRule, + KnownArgumentNamesRule, + KnownDirectivesRule, + KnownFragmentNamesRule, + KnownTypeNamesRule, + LoneAnonymousOperationRule, + NoFragmentCyclesRule, + NoUndefinedVariablesRule, + NoUnusedFragmentsRule, + NoUnusedVariablesRule, + OverlappingFieldsCanBeMergedRule, + PossibleFragmentSpreadsRule, + ProvidedRequiredArgumentsRule, + ScalarLeafsRule, + SingleFieldSubscriptionsRule, + UniqueArgumentNamesRule, + UniqueDirectivesPerLocationRule, + UniqueFragmentNamesRule, + UniqueInputFieldNamesRule, + UniqueOperationNamesRule, + UniqueVariableNamesRule, + ValuesOfCorrectTypeRule, + VariablesAreInputTypesRule, + VariablesInAllowedPositionRule, +} from './validation'; + +export type { ValidationRule } from './validation'; + +// Create, format, and print GraphQL errors. +export { GraphQLError, formatError, printError } from './error'; + +export type { GraphQLFormattedError } from './error'; + +// Utilities for operating on GraphQL type schema and parsed sources. +export { + // Produce the GraphQL query recommended for a full schema introspection. + // Accepts optional IntrospectionOptions. + getIntrospectionQuery, + // @deprecated: use getIntrospectionQuery - will be removed in v15 + introspectionQuery, + // Gets the target Operation from a Document + getOperationAST, + // Gets the Type for the target Operation AST. + getOperationRootType, + // Convert a GraphQLSchema to an IntrospectionQuery + introspectionFromSchema, + // Build a GraphQLSchema from an introspection result. + buildClientSchema, + // Build a GraphQLSchema from a parsed GraphQL Schema language AST. + buildASTSchema, + // Build a GraphQLSchema from a GraphQL schema language document. + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, + // Extends an existing GraphQLSchema from a parsed GraphQL Schema + // language AST. + extendSchema, + // Sort a GraphQLSchema. + lexicographicSortSchema, + // Print a GraphQLSchema to GraphQL Schema language. + printSchema, + // Prints the built-in introspection schema in the Schema Language + // format. + printIntrospectionSchema, + // Print a GraphQLType to GraphQL Schema language. + printType, + // Create a GraphQLType from a GraphQL language AST. + typeFromAST, + // Create a JavaScript value from a GraphQL language AST with a Type. + valueFromAST, + // Create a JavaScript value from a GraphQL language AST without a Type. + valueFromASTUntyped, + // Create a GraphQL language AST from a JavaScript value. + astFromValue, + // A helper to use within recursive-descent visitors which need to be aware of + // the GraphQL type system. + TypeInfo, + // Coerces a JavaScript value to a GraphQL type, or produces errors. + coerceValue, + // @deprecated use coerceValue - will be removed in v15 + isValidJSValue, + // @deprecated use validation - will be removed in v15 + isValidLiteralValue, + // Concatenates multiple AST together. + concatAST, + // Separates an AST into an AST per Operation. + separateOperations, + // Comparators for types + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, + // Asserts a string is a valid GraphQL name. + assertValidName, + // Determine if a string is a valid GraphQL name. + isValidNameError, + // Compares two GraphQLSchemas and detects breaking changes. + findBreakingChanges, + findDangerousChanges, + BreakingChangeType, + DangerousChangeType, + // Report all deprecated usage within a GraphQL document. + findDeprecatedUsages, +} from './utilities'; + +export type { + BuildSchemaOptions, + BreakingChange, + DangerousChange, + IntrospectionOptions, + IntrospectionDirective, + IntrospectionEnumType, + IntrospectionEnumValue, + IntrospectionField, + IntrospectionInputObjectType, + IntrospectionInputType, + IntrospectionInputTypeRef, + IntrospectionInputValue, + IntrospectionInterfaceType, + IntrospectionListTypeRef, + IntrospectionNamedTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionObjectType, + IntrospectionOutputType, + IntrospectionOutputTypeRef, + IntrospectionQuery, + IntrospectionScalarType, + IntrospectionSchema, + IntrospectionType, + IntrospectionTypeRef, + IntrospectionUnionType, +} from './utilities'; diff --git a/node_modules/graphql/index.mjs b/node_modules/graphql/index.mjs new file mode 100644 index 00000000..35f72d22 --- /dev/null +++ b/node_modules/graphql/index.mjs @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * GraphQL.js provides a reference implementation for the GraphQL specification + * but is also a useful utility for operating on GraphQL files and building + * sophisticated tools. + * + * This primary module exports a general purpose function for fulfilling all + * steps of the GraphQL specification in a single operation, but also includes + * utilities for every part of the GraphQL specification: + * + * - Parsing the GraphQL language. + * - Building a GraphQL type schema. + * - Validating a GraphQL request against a type schema. + * - Executing a GraphQL request against a type schema. + * + * This also includes utility functions for operating on GraphQL types and + * GraphQL documents to facilitate building tools. + * + * You may also import from each sub-directory directly. For example, the + * following two import statements are equivalent: + * + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + */ +// The primary entry point into fulfilling a GraphQL request. +export { graphql, graphqlSync } from './graphql'; // Create and operate on GraphQL type definitions and schema. + +export { GraphQLSchema, // Definitions +GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, GraphQLDirective, // "Enum" of Type Kinds +TypeKind, // Scalars +specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID, // Built-in Directives defined by the Spec +specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, // Constant Deprecation Reason +DEFAULT_DEPRECATION_REASON, // Meta-field definitions. +SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, // GraphQL Types for introspection. +introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind, // Predicates +isSchema, isDirective, isType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isInputType, isOutputType, isLeafType, isCompositeType, isAbstractType, isWrappingType, isNullableType, isNamedType, isRequiredArgument, isRequiredInputField, isSpecifiedScalarType, isIntrospectionType, isSpecifiedDirective, // Assertions +assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType, // Un-modifiers +getNullableType, getNamedType, // Validate GraphQL schema. +validateSchema, assertValidSchema } from './type'; +// Parse and operate on GraphQL language source files. +export { Source, getLocation, // Parse +parse, parseValue, parseType, // Print +print, // Visit +visit, visitInParallel, visitWithTypeInfo, getVisitFn, Kind, TokenKind, DirectiveLocation, BREAK, // Predicates +isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from './language'; +// Execute GraphQL queries. +export { execute, defaultFieldResolver, responsePathAsArray, getDirectiveValues } from './execution'; +export { subscribe, createSourceEventStream } from './subscription'; // Validate GraphQL queries. + +export { validate, ValidationContext, // All validation rules in the GraphQL Specification. +specifiedRules, // Individual validation rules. +FieldsOnCorrectTypeRule, FragmentsOnCompositeTypesRule, KnownArgumentNamesRule, KnownDirectivesRule, KnownFragmentNamesRule, KnownTypeNamesRule, LoneAnonymousOperationRule, NoFragmentCyclesRule, NoUndefinedVariablesRule, NoUnusedFragmentsRule, NoUnusedVariablesRule, OverlappingFieldsCanBeMergedRule, PossibleFragmentSpreadsRule, ProvidedRequiredArgumentsRule, ScalarLeafsRule, SingleFieldSubscriptionsRule, UniqueArgumentNamesRule, UniqueDirectivesPerLocationRule, UniqueFragmentNamesRule, UniqueInputFieldNamesRule, UniqueOperationNamesRule, UniqueVariableNamesRule, ValuesOfCorrectTypeRule, VariablesAreInputTypesRule, VariablesInAllowedPositionRule } from './validation'; +// Create, format, and print GraphQL errors. +export { GraphQLError, formatError, printError } from './error'; +// Utilities for operating on GraphQL type schema and parsed sources. +export { // Produce the GraphQL query recommended for a full schema introspection. +// Accepts optional IntrospectionOptions. +getIntrospectionQuery, // @deprecated: use getIntrospectionQuery - will be removed in v15 +introspectionQuery, // Gets the target Operation from a Document +getOperationAST, // Gets the Type for the target Operation AST. +getOperationRootType, // Convert a GraphQLSchema to an IntrospectionQuery +introspectionFromSchema, // Build a GraphQLSchema from an introspection result. +buildClientSchema, // Build a GraphQLSchema from a parsed GraphQL Schema language AST. +buildASTSchema, // Build a GraphQLSchema from a GraphQL schema language document. +buildSchema, // @deprecated: Get the description from a schema AST node and supports legacy +// syntax for specifying descriptions - will be removed in v16 +getDescription, // Extends an existing GraphQLSchema from a parsed GraphQL Schema +// language AST. +extendSchema, // Sort a GraphQLSchema. +lexicographicSortSchema, // Print a GraphQLSchema to GraphQL Schema language. +printSchema, // Prints the built-in introspection schema in the Schema Language +// format. +printIntrospectionSchema, // Print a GraphQLType to GraphQL Schema language. +printType, // Create a GraphQLType from a GraphQL language AST. +typeFromAST, // Create a JavaScript value from a GraphQL language AST with a Type. +valueFromAST, // Create a JavaScript value from a GraphQL language AST without a Type. +valueFromASTUntyped, // Create a GraphQL language AST from a JavaScript value. +astFromValue, // A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +TypeInfo, // Coerces a JavaScript value to a GraphQL type, or produces errors. +coerceValue, // @deprecated use coerceValue - will be removed in v15 +isValidJSValue, // @deprecated use validation - will be removed in v15 +isValidLiteralValue, // Concatenates multiple AST together. +concatAST, // Separates an AST into an AST per Operation. +separateOperations, // Comparators for types +isEqualType, isTypeSubTypeOf, doTypesOverlap, // Asserts a string is a valid GraphQL name. +assertValidName, // Determine if a string is a valid GraphQL name. +isValidNameError, // Compares two GraphQLSchemas and detects breaking changes. +findBreakingChanges, findDangerousChanges, BreakingChangeType, DangerousChangeType, // Report all deprecated usage within a GraphQL document. +findDeprecatedUsages } from './utilities'; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/MaybePromise.js b/node_modules/graphql/jsutils/MaybePromise.js new file mode 100644 index 00000000..9a390c31 --- /dev/null +++ b/node_modules/graphql/jsutils/MaybePromise.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/MaybePromise.js.flow b/node_modules/graphql/jsutils/MaybePromise.js.flow new file mode 100644 index 00000000..c4b6b6e2 --- /dev/null +++ b/node_modules/graphql/jsutils/MaybePromise.js.flow @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export type MaybePromise<+T> = Promise | T; diff --git a/node_modules/graphql/jsutils/MaybePromise.mjs b/node_modules/graphql/jsutils/MaybePromise.mjs new file mode 100644 index 00000000..e69de29b diff --git a/node_modules/graphql/jsutils/ObjMap.js b/node_modules/graphql/jsutils/ObjMap.js new file mode 100644 index 00000000..9a390c31 --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/ObjMap.js.flow b/node_modules/graphql/jsutils/ObjMap.js.flow new file mode 100644 index 00000000..140e60fe --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.js.flow @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export type ObjMap = { [key: string]: T, __proto__: null }; diff --git a/node_modules/graphql/jsutils/ObjMap.mjs b/node_modules/graphql/jsutils/ObjMap.mjs new file mode 100644 index 00000000..e69de29b diff --git a/node_modules/graphql/jsutils/dedent.js b/node_modules/graphql/jsutils/dedent.js new file mode 100644 index 00000000..cf310560 --- /dev/null +++ b/node_modules/graphql/jsutils/dedent.js @@ -0,0 +1,66 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = dedent; + +var _invariant = _interopRequireDefault(require("./invariant")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * fixes indentation by removing leading spaces and tabs from each line + */ +function fixIndent(str) { + var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline + .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs + + var indentMatch = /^[ \t]*/.exec(trimmedStr); + !Array.isArray(indentMatch) ? (0, _invariant.default)(0) : void 0; + var indent = indentMatch[0]; // figure out indent + + return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent +} +/** + * An ES6 string tag that fixes indentation. Also removes leading newlines + * and trailing spaces and tabs, but keeps trailing newlines. + * + * Example usage: + * const str = dedent` + * { + * test + * } + * `; + * str === "{\n test\n}\n"; + */ + + +function dedent(strings) { + for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + values[_key - 1] = arguments[_key]; + } + + // when used as an ordinary function, allow passing a singleton string + var strArray = typeof strings === 'string' ? [strings] : strings; + var numValues = values.length; + var str = strArray.reduce(function (prev, cur, index) { + var next = prev + cur; + + if (index < numValues) { + next += values[index]; // interpolation + } + + return next; + }, ''); + return fixIndent(str); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/dedent.js.flow b/node_modules/graphql/jsutils/dedent.js.flow new file mode 100644 index 00000000..540f65eb --- /dev/null +++ b/node_modules/graphql/jsutils/dedent.js.flow @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from './invariant'; + +/** + * fixes indentation by removing leading spaces and tabs from each line + */ +function fixIndent(str: string): string { + const trimmedStr = str + .replace(/^\n*/m, '') // remove leading newline + .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs + const indentMatch = /^[ \t]*/.exec(trimmedStr); + invariant(Array.isArray(indentMatch)); + const indent = indentMatch[0]; // figure out indent + return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent +} + +/** + * An ES6 string tag that fixes indentation. Also removes leading newlines + * and trailing spaces and tabs, but keeps trailing newlines. + * + * Example usage: + * const str = dedent` + * { + * test + * } + * `; + * str === "{\n test\n}\n"; + */ +export default function dedent( + strings: string | Array, + ...values: Array +): string { + // when used as an ordinary function, allow passing a singleton string + const strArray = typeof strings === 'string' ? [strings] : strings; + const numValues = values.length; + + const str = strArray.reduce((prev, cur, index) => { + let next = prev + cur; + if (index < numValues) { + next += values[index]; // interpolation + } + return next; + }, ''); + + return fixIndent(str); +} diff --git a/node_modules/graphql/jsutils/dedent.mjs b/node_modules/graphql/jsutils/dedent.mjs new file mode 100644 index 00000000..87eb3c92 --- /dev/null +++ b/node_modules/graphql/jsutils/dedent.mjs @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from './invariant'; +/** + * fixes indentation by removing leading spaces and tabs from each line + */ + +function fixIndent(str) { + var trimmedStr = str.replace(/^\n*/m, '') // remove leading newline + .replace(/[ \t]*$/, ''); // remove trailing spaces and tabs + + var indentMatch = /^[ \t]*/.exec(trimmedStr); + !Array.isArray(indentMatch) ? invariant(0) : void 0; + var indent = indentMatch[0]; // figure out indent + + return trimmedStr.replace(RegExp('^' + indent, 'mg'), ''); // remove indent +} +/** + * An ES6 string tag that fixes indentation. Also removes leading newlines + * and trailing spaces and tabs, but keeps trailing newlines. + * + * Example usage: + * const str = dedent` + * { + * test + * } + * `; + * str === "{\n test\n}\n"; + */ + + +export default function dedent(strings) { + for (var _len = arguments.length, values = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + values[_key - 1] = arguments[_key]; + } + + // when used as an ordinary function, allow passing a singleton string + var strArray = typeof strings === 'string' ? [strings] : strings; + var numValues = values.length; + var str = strArray.reduce(function (prev, cur, index) { + var next = prev + cur; + + if (index < numValues) { + next += values[index]; // interpolation + } + + return next; + }, ''); + return fixIndent(str); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToJSON.js b/node_modules/graphql/jsutils/defineToJSON.js new file mode 100644 index 00000000..b5a25130 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToJSON.js @@ -0,0 +1,23 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = applyToJSON; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToJSON()` function defines toJSON() and inspect() prototype + * methods which are aliases for toString(). + */ +function applyToJSON(classObject) { + classObject.prototype.toJSON = classObject.prototype.inspect = classObject.prototype.toString; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToJSON.js.flow b/node_modules/graphql/jsutils/defineToJSON.js.flow new file mode 100644 index 00000000..fde3f6c3 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToJSON.js.flow @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The `applyToJSON()` function defines toJSON() and inspect() prototype + * methods which are aliases for toString(). + */ +export default function applyToJSON(classObject: Class): void { + classObject.prototype.toJSON = classObject.prototype.inspect = + classObject.prototype.toString; +} diff --git a/node_modules/graphql/jsutils/defineToJSON.mjs b/node_modules/graphql/jsutils/defineToJSON.mjs new file mode 100644 index 00000000..ba22494d --- /dev/null +++ b/node_modules/graphql/jsutils/defineToJSON.mjs @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToJSON()` function defines toJSON() and inspect() prototype + * methods which are aliases for toString(). + */ +export default function applyToJSON(classObject) { + classObject.prototype.toJSON = classObject.prototype.inspect = classObject.prototype.toString; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToStringTag.js b/node_modules/graphql/jsutils/defineToStringTag.js new file mode 100644 index 00000000..fedef318 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToStringTag.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = applyToStringTag; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToStringTag()` function checks first to see if the runtime + * supports the `Symbol` class and then if the `Symbol.toStringTag` constant + * is defined as a `Symbol` instance. If both conditions are met, the + * Symbol.toStringTag property is defined as a getter that returns the + * supplied class constructor's name. + * + * @method applyToStringTag + * + * @param {Class} classObject a class such as Object, String, Number but + * typically one of your own creation through the class keyword; `class A {}`, + * for example. + */ +function applyToStringTag(classObject) { + if (typeof Symbol === 'function' && Symbol.toStringTag) { + Object.defineProperty(classObject.prototype, Symbol.toStringTag, { + get: function get() { + return this.constructor.name; + } + }); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/defineToStringTag.js.flow b/node_modules/graphql/jsutils/defineToStringTag.js.flow new file mode 100644 index 00000000..f539cde2 --- /dev/null +++ b/node_modules/graphql/jsutils/defineToStringTag.js.flow @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The `applyToStringTag()` function checks first to see if the runtime + * supports the `Symbol` class and then if the `Symbol.toStringTag` constant + * is defined as a `Symbol` instance. If both conditions are met, the + * Symbol.toStringTag property is defined as a getter that returns the + * supplied class constructor's name. + * + * @method applyToStringTag + * + * @param {Class} classObject a class such as Object, String, Number but + * typically one of your own creation through the class keyword; `class A {}`, + * for example. + */ +export default function applyToStringTag(classObject: Class): void { + if (typeof Symbol === 'function' && Symbol.toStringTag) { + Object.defineProperty(classObject.prototype, Symbol.toStringTag, { + get() { + return this.constructor.name; + }, + }); + } +} diff --git a/node_modules/graphql/jsutils/defineToStringTag.mjs b/node_modules/graphql/jsutils/defineToStringTag.mjs new file mode 100644 index 00000000..ed0d728d --- /dev/null +++ b/node_modules/graphql/jsutils/defineToStringTag.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The `applyToStringTag()` function checks first to see if the runtime + * supports the `Symbol` class and then if the `Symbol.toStringTag` constant + * is defined as a `Symbol` instance. If both conditions are met, the + * Symbol.toStringTag property is defined as a getter that returns the + * supplied class constructor's name. + * + * @method applyToStringTag + * + * @param {Class} classObject a class such as Object, String, Number but + * typically one of your own creation through the class keyword; `class A {}`, + * for example. + */ +export default function applyToStringTag(classObject) { + if (typeof Symbol === 'function' && Symbol.toStringTag) { + Object.defineProperty(classObject.prototype, Symbol.toStringTag, { + get: function get() { + return this.constructor.name; + } + }); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/find.js b/node_modules/graphql/jsutils/find.js new file mode 100644 index 00000000..78b08776 --- /dev/null +++ b/node_modules/graphql/jsutils/find.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = find; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function find(list, predicate) { + for (var i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/find.js.flow b/node_modules/graphql/jsutils/find.js.flow new file mode 100644 index 00000000..ba608d90 --- /dev/null +++ b/node_modules/graphql/jsutils/find.js.flow @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export default function find( + list: $ReadOnlyArray, + predicate: (item: T) => boolean, +): ?T { + for (let i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} diff --git a/node_modules/graphql/jsutils/find.mjs b/node_modules/graphql/jsutils/find.mjs new file mode 100644 index 00000000..965b53f2 --- /dev/null +++ b/node_modules/graphql/jsutils/find.mjs @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export default function find(list, predicate) { + for (var i = 0; i < list.length; i++) { + if (predicate(list[i])) { + return list[i]; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/inspect.js b/node_modules/graphql/jsutils/inspect.js new file mode 100644 index 00000000..ef08c44d --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = inspect; + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Used to print values in error messages. + */ +function inspect(value) { + switch (_typeof(value)) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? "[function ".concat(value.name, "]") : '[function]'; + + case 'object': + if (value) { + if (typeof value.inspect === 'function') { + return value.inspect(); + } else if (Array.isArray(value)) { + return '[' + value.map(inspect).join(', ') + ']'; + } + + var properties = Object.keys(value).map(function (k) { + return "".concat(k, ": ").concat(inspect(value[k])); + }).join(', '); + return properties ? '{ ' + properties + ' }' : '{}'; + } + + return String(value); + + default: + return String(value); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/inspect.js.flow b/node_modules/graphql/jsutils/inspect.js.flow new file mode 100644 index 00000000..f2c32d88 --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.js.flow @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Used to print values in error messages. + */ +export default function inspect(value: mixed): string { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + case 'object': + if (value) { + if (typeof value.inspect === 'function') { + return value.inspect(); + } else if (Array.isArray(value)) { + return '[' + value.map(inspect).join(', ') + ']'; + } + + const properties = Object.keys(value) + .map(k => `${k}: ${inspect(value[k])}`) + .join(', '); + return properties ? '{ ' + properties + ' }' : '{}'; + } + return String(value); + default: + return String(value); + } +} diff --git a/node_modules/graphql/jsutils/inspect.mjs b/node_modules/graphql/jsutils/inspect.mjs new file mode 100644 index 00000000..e6dceccd --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.mjs @@ -0,0 +1,42 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Used to print values in error messages. + */ +export default function inspect(value) { + switch (_typeof(value)) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? "[function ".concat(value.name, "]") : '[function]'; + + case 'object': + if (value) { + if (typeof value.inspect === 'function') { + return value.inspect(); + } else if (Array.isArray(value)) { + return '[' + value.map(inspect).join(', ') + ']'; + } + + var properties = Object.keys(value).map(function (k) { + return "".concat(k, ": ").concat(inspect(value[k])); + }).join(', '); + return properties ? '{ ' + properties + ' }' : '{}'; + } + + return String(value); + + default: + return String(value); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/instanceOf.js b/node_modules/graphql/jsutils/instanceOf.js new file mode 100644 index 00000000..497147a5 --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +var _default = process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + return value instanceof constructor; +} : // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (value) { + var valueClass = value.constructor; + var className = constructor.name; + + if (className && valueClass && valueClass.name === className) { + throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.")); + } + } + + return false; +}; + +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/instanceOf.js.flow b/node_modules/graphql/jsutils/instanceOf.js.flow new file mode 100644 index 00000000..1cb4d2af --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.js.flow @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ +declare function instanceOf( + value: mixed, + constructor: mixed, +): boolean %checks(value instanceof constructor); + +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +export default (process.env.NODE_ENV === 'production' + ? // eslint-disable-next-line no-shadow + function instanceOf(value: mixed, constructor: mixed) { + return value instanceof constructor; + } + : // eslint-disable-next-line no-shadow + function instanceOf(value: any, constructor: any) { + if (value instanceof constructor) { + return true; + } + if (value) { + const valueClass = value.constructor; + const className = constructor.name; + if (className && valueClass && valueClass.name === className) { + throw new Error( + `Cannot use ${className} "${value}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`, + ); + } + } + return false; + }); diff --git a/node_modules/graphql/jsutils/instanceOf.mjs b/node_modules/graphql/jsutils/instanceOf.mjs new file mode 100644 index 00000000..f8ad237b --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.mjs @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + */ +// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production +// See: https://webpack.js.org/guides/production/ +export default process.env.NODE_ENV === 'production' ? // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + return value instanceof constructor; +} : // eslint-disable-next-line no-shadow +function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (value) { + var valueClass = value.constructor; + var className = constructor.name; + + if (className && valueClass && valueClass.name === className) { + throw new Error("Cannot use ".concat(className, " \"").concat(value, "\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.")); + } + } + + return false; +}; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/invariant.js b/node_modules/graphql/jsutils/invariant.js new file mode 100644 index 00000000..f62b28eb --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.js @@ -0,0 +1,21 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = invariant; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function invariant(condition, message) { + /* istanbul ignore else */ + if (!condition) { + throw new Error(message); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/invariant.js.flow b/node_modules/graphql/jsutils/invariant.js.flow new file mode 100644 index 00000000..f4a51efb --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.js.flow @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export default function invariant(condition: mixed, message: string) { + /* istanbul ignore else */ + if (!condition) { + throw new Error(message); + } +} diff --git a/node_modules/graphql/jsutils/invariant.mjs b/node_modules/graphql/jsutils/invariant.mjs new file mode 100644 index 00000000..a5b5ace0 --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.mjs @@ -0,0 +1,14 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export default function invariant(condition, message) { + /* istanbul ignore else */ + if (!condition) { + throw new Error(message); + } +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isFinite.js b/node_modules/graphql/jsutils/isFinite.js new file mode 100644 index 00000000..5e5aa0ce --- /dev/null +++ b/node_modules/graphql/jsutils/isFinite.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isFinite = Number.isFinite || function (value) { + return typeof value === 'number' && isFinite(value); +}; + +var _default = isFinite; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isFinite.js.flow b/node_modules/graphql/jsutils/isFinite.js.flow new file mode 100644 index 00000000..a874a2d8 --- /dev/null +++ b/node_modules/graphql/jsutils/isFinite.js.flow @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +declare function isFinite(value: mixed): boolean %checks(typeof value === + 'number'); + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +const isFinite = + Number.isFinite || + function(value) { + return typeof value === 'number' && isFinite(value); + }; +export default isFinite; diff --git a/node_modules/graphql/jsutils/isFinite.mjs b/node_modules/graphql/jsutils/isFinite.mjs new file mode 100644 index 00000000..f6e317b4 --- /dev/null +++ b/node_modules/graphql/jsutils/isFinite.mjs @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isFinite = Number.isFinite || function (value) { + return typeof value === 'number' && isFinite(value); +}; + +export default isFinite; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInteger.js b/node_modules/graphql/jsutils/isInteger.js new file mode 100644 index 00000000..6628bd1d --- /dev/null +++ b/node_modules/graphql/jsutils/isInteger.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isInteger = Number.isInteger || function (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +}; + +var _default = isInteger; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInteger.js.flow b/node_modules/graphql/jsutils/isInteger.js.flow new file mode 100644 index 00000000..3e897d6f --- /dev/null +++ b/node_modules/graphql/jsutils/isInteger.js.flow @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +declare function isInteger(value: mixed): boolean %checks(typeof value === + 'number'); + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +const isInteger = + Number.isInteger || + function(value) { + return ( + typeof value === 'number' && + isFinite(value) && + Math.floor(value) === value + ); + }; +export default isInteger; diff --git a/node_modules/graphql/jsutils/isInteger.mjs b/node_modules/graphql/jsutils/isInteger.mjs new file mode 100644 index 00000000..b4a324b0 --- /dev/null +++ b/node_modules/graphql/jsutils/isInteger.mjs @@ -0,0 +1,16 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/4441 +var isInteger = Number.isInteger || function (value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; +}; + +export default isInteger; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInvalid.js b/node_modules/graphql/jsutils/isInvalid.js new file mode 100644 index 00000000..0025c6a2 --- /dev/null +++ b/node_modules/graphql/jsutils/isInvalid.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isInvalid; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +function isInvalid(value) { + return value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isInvalid.js.flow b/node_modules/graphql/jsutils/isInvalid.js.flow new file mode 100644 index 00000000..9ddbfed5 --- /dev/null +++ b/node_modules/graphql/jsutils/isInvalid.js.flow @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +export default function isInvalid(value: mixed): boolean %checks { + return value === undefined || value !== value; +} diff --git a/node_modules/graphql/jsutils/isInvalid.mjs b/node_modules/graphql/jsutils/isInvalid.mjs new file mode 100644 index 00000000..af36e077 --- /dev/null +++ b/node_modules/graphql/jsutils/isInvalid.mjs @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is undefined, or NaN. + */ +export default function isInvalid(value) { + return value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isNullish.js b/node_modules/graphql/jsutils/isNullish.js new file mode 100644 index 00000000..d7cf0300 --- /dev/null +++ b/node_modules/graphql/jsutils/isNullish.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isNullish; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +function isNullish(value) { + return value === null || value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isNullish.js.flow b/node_modules/graphql/jsutils/isNullish.js.flow new file mode 100644 index 00000000..aedd6c86 --- /dev/null +++ b/node_modules/graphql/jsutils/isNullish.js.flow @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +export default function isNullish(value: mixed): boolean %checks { + return value === null || value === undefined || value !== value; +} diff --git a/node_modules/graphql/jsutils/isNullish.mjs b/node_modules/graphql/jsutils/isNullish.mjs new file mode 100644 index 00000000..7a2e92da --- /dev/null +++ b/node_modules/graphql/jsutils/isNullish.mjs @@ -0,0 +1,15 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if a value is null, undefined, or NaN. + */ +export default function isNullish(value) { + return value === null || value === undefined || value !== value; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isPromise.js b/node_modules/graphql/jsutils/isPromise.js new file mode 100644 index 00000000..0feb12bb --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.js @@ -0,0 +1,24 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = isPromise; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +// eslint-disable-next-line no-redeclare +function isPromise(value) { + return Boolean(value && typeof value.then === 'function'); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/isPromise.js.flow b/node_modules/graphql/jsutils/isPromise.js.flow new file mode 100644 index 00000000..d53c9eea --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.js.flow @@ -0,0 +1,20 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +declare function isPromise(value: mixed): boolean %checks(value instanceof + Promise); + +// eslint-disable-next-line no-redeclare +export default function isPromise(value) { + return Boolean(value && typeof value.then === 'function'); +} diff --git a/node_modules/graphql/jsutils/isPromise.mjs b/node_modules/graphql/jsutils/isPromise.mjs new file mode 100644 index 00000000..9705fcb4 --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + */ +// eslint-disable-next-line no-redeclare +export default function isPromise(value) { + return Boolean(value && typeof value.then === 'function'); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyMap.js b/node_modules/graphql/jsutils/keyMap.js new file mode 100644 index 00000000..6d4250f6 --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.js @@ -0,0 +1,44 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyMap; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +function keyMap(list, keyFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = item, map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyMap.js.flow b/node_modules/graphql/jsutils/keyMap.js.flow new file mode 100644 index 00000000..58fce2f7 --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.js.flow @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +export default function keyMap( + list: $ReadOnlyArray, + keyFn: (item: T) => string, +): ObjMap { + return list.reduce( + (map, item) => ((map[keyFn(item)] = item), map), + Object.create(null), + ); +} diff --git a/node_modules/graphql/jsutils/keyMap.mjs b/node_modules/graphql/jsutils/keyMap.mjs new file mode 100644 index 00000000..9df8eb09 --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.mjs @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: { name: 'Jon', num: '555-1234' }, + * // Jenny: { name: 'Jenny', num: '867-5309' } } + * const entriesByName = keyMap( + * phoneBook, + * entry => entry.name + * ) + * + * // { name: 'Jenny', num: '857-6309' } + * const jennyEntry = entriesByName['Jenny'] + * + */ +export default function keyMap(list, keyFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = item, map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyValMap.js b/node_modules/graphql/jsutils/keyValMap.js new file mode 100644 index 00000000..d12801d2 --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.js @@ -0,0 +1,38 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = keyValMap; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +function keyValMap(list, keyFn, valFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = valFn(item), map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/keyValMap.js.flow b/node_modules/graphql/jsutils/keyValMap.js.flow new file mode 100644 index 00000000..7917f3cc --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.js.flow @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +export default function keyValMap( + list: $ReadOnlyArray, + keyFn: (item: T) => string, + valFn: (item: T) => V, +): ObjMap { + return list.reduce( + (map, item) => ((map[keyFn(item)] = valFn(item)), map), + Object.create(null), + ); +} diff --git a/node_modules/graphql/jsutils/keyValMap.mjs b/node_modules/graphql/jsutils/keyValMap.mjs new file mode 100644 index 00000000..eae73e89 --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' } + * ] + * + * // { Jon: '555-1234', Jenny: '867-5309' } + * const phonesByName = keyValMap( + * phoneBook, + * entry => entry.name, + * entry => entry.num + * ) + * + */ +export default function keyValMap(list, keyFn, valFn) { + return list.reduce(function (map, item) { + return map[keyFn(item)] = valFn(item), map; + }, Object.create(null)); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/memoize3.js b/node_modules/graphql/jsutils/memoize3.js new file mode 100644 index 00000000..e079629f --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.js @@ -0,0 +1,57 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = memoize3; + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Memoizes the provided three-argument function. + */ +function memoize3(fn) { + var cache0; + + function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + + var cache1 = cache0.get(a1); + var cache2; + + if (cache1) { + cache2 = cache1.get(a2); + + if (cache2) { + var cachedValue = cache2.get(a3); + + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + var newValue = fn.apply(this, arguments); + cache2.set(a3, newValue); + return newValue; + } + + return memoized; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/memoize3.js.flow b/node_modules/graphql/jsutils/memoize3.js.flow new file mode 100644 index 00000000..37e3951d --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.js.flow @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Memoizes the provided three-argument function. + */ +export default function memoize3 any>( + fn: T, +): T { + let cache0; + function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + let cache1 = cache0.get(a1); + let cache2; + if (cache1) { + cache2 = cache1.get(a2); + if (cache2) { + const cachedValue = cache2.get(a3); + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + const newValue = fn.apply(this, arguments); + cache2.set(a3, newValue); + return newValue; + } + return (memoized: any); +} diff --git a/node_modules/graphql/jsutils/memoize3.mjs b/node_modules/graphql/jsutils/memoize3.mjs new file mode 100644 index 00000000..c82432be --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.mjs @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Memoizes the provided three-argument function. + */ +export default function memoize3(fn) { + var cache0; + + function memoized(a1, a2, a3) { + if (!cache0) { + cache0 = new WeakMap(); + } + + var cache1 = cache0.get(a1); + var cache2; + + if (cache1) { + cache2 = cache1.get(a2); + + if (cache2) { + var cachedValue = cache2.get(a3); + + if (cachedValue !== undefined) { + return cachedValue; + } + } + } else { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + if (!cache2) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + var newValue = fn.apply(this, arguments); + cache2.set(a3, newValue); + return newValue; + } + + return memoized; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/objectValues.js b/node_modules/graphql/jsutils/objectValues.js new file mode 100644 index 00000000..c43e3893 --- /dev/null +++ b/node_modules/graphql/jsutils/objectValues.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221 +var objectValues = Object.values || function (obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); +}; + +var _default = objectValues; +exports.default = _default; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/objectValues.js.flow b/node_modules/graphql/jsutils/objectValues.js.flow new file mode 100644 index 00000000..d6bab482 --- /dev/null +++ b/node_modules/graphql/jsutils/objectValues.js.flow @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +declare function objectValues(obj: ObjMap): Array; + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221 +const objectValues = + Object.values || (obj => Object.keys(obj).map(key => obj[key])); +export default objectValues; diff --git a/node_modules/graphql/jsutils/objectValues.mjs b/node_modules/graphql/jsutils/objectValues.mjs new file mode 100644 index 00000000..8a08ca3c --- /dev/null +++ b/node_modules/graphql/jsutils/objectValues.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/* eslint-disable no-redeclare */ +// $FlowFixMe workaround for: https://github.com/facebook/flow/issues/2221 +var objectValues = Object.values || function (obj) { + return Object.keys(obj).map(function (key) { + return obj[key]; + }); +}; + +export default objectValues; \ No newline at end of file diff --git a/node_modules/graphql/jsutils/orList.js b/node_modules/graphql/jsutils/orList.js new file mode 100644 index 00000000..d52df380 --- /dev/null +++ b/node_modules/graphql/jsutils/orList.js @@ -0,0 +1,26 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = orList; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var MAX_LENGTH = 5; +/** + * Given [ A, B, C ] return 'A, B, or C'. + */ + +function orList(items) { + var selected = items.slice(0, MAX_LENGTH); + return selected.reduce(function (list, quoted, index) { + return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/orList.js.flow b/node_modules/graphql/jsutils/orList.js.flow new file mode 100644 index 00000000..dc63e0db --- /dev/null +++ b/node_modules/graphql/jsutils/orList.js.flow @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +const MAX_LENGTH = 5; + +/** + * Given [ A, B, C ] return 'A, B, or C'. + */ +export default function orList(items: $ReadOnlyArray): string { + const selected = items.slice(0, MAX_LENGTH); + return selected.reduce( + (list, quoted, index) => + list + + (selected.length > 2 ? ', ' : ' ') + + (index === selected.length - 1 ? 'or ' : '') + + quoted, + ); +} diff --git a/node_modules/graphql/jsutils/orList.mjs b/node_modules/graphql/jsutils/orList.mjs new file mode 100644 index 00000000..3c68746b --- /dev/null +++ b/node_modules/graphql/jsutils/orList.mjs @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var MAX_LENGTH = 5; +/** + * Given [ A, B, C ] return 'A, B, or C'. + */ + +export default function orList(items) { + var selected = items.slice(0, MAX_LENGTH); + return selected.reduce(function (list, quoted, index) { + return list + (selected.length > 2 ? ', ' : ' ') + (index === selected.length - 1 ? 'or ' : '') + quoted; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseForObject.js b/node_modules/graphql/jsutils/promiseForObject.js new file mode 100644 index 00000000..55328b27 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.js @@ -0,0 +1,35 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = promiseForObject; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +function promiseForObject(object) { + var keys = Object.keys(object); + var valuesAndPromises = keys.map(function (name) { + return object[name]; + }); + return Promise.all(valuesAndPromises).then(function (values) { + return values.reduce(function (resolvedObject, value, i) { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseForObject.js.flow b/node_modules/graphql/jsutils/promiseForObject.js.flow new file mode 100644 index 00000000..74d17876 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.js.flow @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from './ObjMap'; + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +export default function promiseForObject( + object: ObjMap>, +): Promise> { + const keys = Object.keys(object); + const valuesAndPromises = keys.map(name => object[name]); + return Promise.all(valuesAndPromises).then(values => + values.reduce((resolvedObject, value, i) => { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)), + ); +} diff --git a/node_modules/graphql/jsutils/promiseForObject.mjs b/node_modules/graphql/jsutils/promiseForObject.mjs new file mode 100644 index 00000000..356ede35 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.mjs @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + */ +export default function promiseForObject(object) { + var keys = Object.keys(object); + var valuesAndPromises = keys.map(function (name) { + return object[name]; + }); + return Promise.all(valuesAndPromises).then(function (values) { + return values.reduce(function (resolvedObject, value, i) { + resolvedObject[keys[i]] = value; + return resolvedObject; + }, Object.create(null)); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseReduce.js b/node_modules/graphql/jsutils/promiseReduce.js new file mode 100644 index 00000000..9ed206af --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = promiseReduce; + +var _isPromise = _interopRequireDefault(require("./isPromise")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +function promiseReduce(values, callback, initialValue) { + return values.reduce(function (previous, value) { + return (0, _isPromise.default)(previous) ? previous.then(function (resolved) { + return callback(resolved, value); + }) : callback(previous, value); + }, initialValue); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/promiseReduce.js.flow b/node_modules/graphql/jsutils/promiseReduce.js.flow new file mode 100644 index 00000000..a09837b8 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.js.flow @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import isPromise from './isPromise'; +import type { MaybePromise } from './MaybePromise'; + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +export default function promiseReduce( + values: $ReadOnlyArray, + callback: (U, T) => MaybePromise, + initialValue: MaybePromise, +): MaybePromise { + return values.reduce( + (previous, value) => + isPromise(previous) + ? previous.then(resolved => callback(resolved, value)) + : callback(previous, value), + initialValue, + ); +} diff --git a/node_modules/graphql/jsutils/promiseReduce.mjs b/node_modules/graphql/jsutils/promiseReduce.mjs new file mode 100644 index 00000000..8fb79191 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.mjs @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import isPromise from './isPromise'; + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + */ +export default function promiseReduce(values, callback, initialValue) { + return values.reduce(function (previous, value) { + return isPromise(previous) ? previous.then(function (resolved) { + return callback(resolved, value); + }) : callback(previous, value); + }, initialValue); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/quotedOrList.js b/node_modules/graphql/jsutils/quotedOrList.js new file mode 100644 index 00000000..826fc02e --- /dev/null +++ b/node_modules/graphql/jsutils/quotedOrList.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = quotedOrList; + +var _orList = _interopRequireDefault(require("./orList")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ +function quotedOrList(items) { + return (0, _orList.default)(items.map(function (item) { + return "\"".concat(item, "\""); + })); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/quotedOrList.js.flow b/node_modules/graphql/jsutils/quotedOrList.js.flow new file mode 100644 index 00000000..f5670388 --- /dev/null +++ b/node_modules/graphql/jsutils/quotedOrList.js.flow @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import orList from './orList'; + +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ +export default function quotedOrList(items: $ReadOnlyArray): string { + return orList(items.map(item => `"${item}"`)); +} diff --git a/node_modules/graphql/jsutils/quotedOrList.mjs b/node_modules/graphql/jsutils/quotedOrList.mjs new file mode 100644 index 00000000..6cff7805 --- /dev/null +++ b/node_modules/graphql/jsutils/quotedOrList.mjs @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import orList from './orList'; +/** + * Given [ A, B, C ] return '"A", "B", or "C"'. + */ + +export default function quotedOrList(items) { + return orList(items.map(function (item) { + return "\"".concat(item, "\""); + })); +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/suggestionList.js b/node_modules/graphql/jsutils/suggestionList.js new file mode 100644 index 00000000..42072b39 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.js @@ -0,0 +1,96 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = suggestionList; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +function suggestionList(input, options) { + var optionsByDistance = Object.create(null); + var oLength = options.length; + var inputThreshold = input.length / 2; + + for (var i = 0; i < oLength; i++) { + var distance = lexicalDistance(input, options[i]); + var threshold = Math.max(inputThreshold, options[i].length / 2, 1); + + if (distance <= threshold) { + optionsByDistance[options[i]] = distance; + } + } + + return Object.keys(optionsByDistance).sort(function (a, b) { + return optionsByDistance[a] - optionsByDistance[b]; + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @param {string} a + * @param {string} b + * @return {int} distance in number of edits + */ + + +function lexicalDistance(aStr, bStr) { + if (aStr === bStr) { + return 0; + } + + var i; + var j; + var d = []; + var a = aStr.toLowerCase(); + var b = bStr.toLowerCase(); + var aLength = a.length; + var bLength = b.length; // Any case change counts as a single edit + + if (a === b) { + return 1; + } + + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + var cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + + return d[aLength][bLength]; +} \ No newline at end of file diff --git a/node_modules/graphql/jsutils/suggestionList.js.flow b/node_modules/graphql/jsutils/suggestionList.js.flow new file mode 100644 index 00000000..e800d03a --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.js.flow @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +export default function suggestionList( + input: string, + options: $ReadOnlyArray, +): Array { + const optionsByDistance = Object.create(null); + const oLength = options.length; + const inputThreshold = input.length / 2; + for (let i = 0; i < oLength; i++) { + const distance = lexicalDistance(input, options[i]); + const threshold = Math.max(inputThreshold, options[i].length / 2, 1); + if (distance <= threshold) { + optionsByDistance[options[i]] = distance; + } + } + return Object.keys(optionsByDistance).sort( + (a, b) => optionsByDistance[a] - optionsByDistance[b], + ); +} + +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @param {string} a + * @param {string} b + * @return {int} distance in number of edits + */ +function lexicalDistance(aStr, bStr) { + if (aStr === bStr) { + return 0; + } + + let i; + let j; + const d = []; + const a = aStr.toLowerCase(); + const b = bStr.toLowerCase(); + const aLength = a.length; + const bLength = b.length; + + // Any case change counts as a single edit + if (a === b) { + return 1; + } + + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + + d[i][j] = Math.min( + d[i - 1][j] + 1, + d[i][j - 1] + 1, + d[i - 1][j - 1] + cost, + ); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + + return d[aLength][bLength]; +} diff --git a/node_modules/graphql/jsutils/suggestionList.mjs b/node_modules/graphql/jsutils/suggestionList.mjs new file mode 100644 index 00000000..229d5578 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.mjs @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + */ +export default function suggestionList(input, options) { + var optionsByDistance = Object.create(null); + var oLength = options.length; + var inputThreshold = input.length / 2; + + for (var i = 0; i < oLength; i++) { + var distance = lexicalDistance(input, options[i]); + var threshold = Math.max(inputThreshold, options[i].length / 2, 1); + + if (distance <= threshold) { + optionsByDistance[options[i]] = distance; + } + } + + return Object.keys(optionsByDistance).sort(function (a, b) { + return optionsByDistance[a] - optionsByDistance[b]; + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @param {string} a + * @param {string} b + * @return {int} distance in number of edits + */ + +function lexicalDistance(aStr, bStr) { + if (aStr === bStr) { + return 0; + } + + var i; + var j; + var d = []; + var a = aStr.toLowerCase(); + var b = bStr.toLowerCase(); + var aLength = a.length; + var bLength = b.length; // Any case change counts as a single edit + + if (a === b) { + return 1; + } + + for (i = 0; i <= aLength; i++) { + d[i] = [i]; + } + + for (j = 1; j <= bLength; j++) { + d[0][j] = j; + } + + for (i = 1; i <= aLength; i++) { + for (j = 1; j <= bLength; j++) { + var cost = a[i - 1] === b[j - 1] ? 0 : 1; + d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + cost); + } + } + } + + return d[aLength][bLength]; +} \ No newline at end of file diff --git a/node_modules/graphql/language/ast.js b/node_modules/graphql/language/ast.js new file mode 100644 index 00000000..9a390c31 --- /dev/null +++ b/node_modules/graphql/language/ast.js @@ -0,0 +1 @@ +"use strict"; \ No newline at end of file diff --git a/node_modules/graphql/language/ast.js.flow b/node_modules/graphql/language/ast.js.flow new file mode 100644 index 00000000..22169c32 --- /dev/null +++ b/node_modules/graphql/language/ast.js.flow @@ -0,0 +1,581 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Source } from './source'; +import type { TokenKindEnum } from './lexer'; + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export type Location = { + /** + * The character offset at which this Node begins. + */ + +start: number, + + /** + * The character offset at which this Node ends. + */ + +end: number, + + /** + * The Token at which this Node begins. + */ + +startToken: Token, + + /** + * The Token at which this Node ends. + */ + +endToken: Token, + + /** + * The Source document the AST represents. + */ + +source: Source, +}; + +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +export type Token = { + /** + * The kind of Token. + */ + +kind: TokenKindEnum, + + /** + * The character offset at which this Node begins. + */ + +start: number, + + /** + * The character offset at which this Node ends. + */ + +end: number, + + /** + * The 1-indexed line number on which this Token appears. + */ + +line: number, + + /** + * The 1-indexed column number at which this Token begins. + */ + +column: number, + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + */ + +value: string | void, + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + +prev: Token | null, + +next: Token | null, +}; + +/** + * The list of all possible AST node types. + */ +export type ASTNode = + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +/** + * Utility type listing all nodes indexed by their kind. + */ +export type ASTKindToNode = {| + Name: NameNode, + Document: DocumentNode, + OperationDefinition: OperationDefinitionNode, + VariableDefinition: VariableDefinitionNode, + Variable: VariableNode, + SelectionSet: SelectionSetNode, + Field: FieldNode, + Argument: ArgumentNode, + FragmentSpread: FragmentSpreadNode, + InlineFragment: InlineFragmentNode, + FragmentDefinition: FragmentDefinitionNode, + IntValue: IntValueNode, + FloatValue: FloatValueNode, + StringValue: StringValueNode, + BooleanValue: BooleanValueNode, + NullValue: NullValueNode, + EnumValue: EnumValueNode, + ListValue: ListValueNode, + ObjectValue: ObjectValueNode, + ObjectField: ObjectFieldNode, + Directive: DirectiveNode, + NamedType: NamedTypeNode, + ListType: ListTypeNode, + NonNullType: NonNullTypeNode, + SchemaDefinition: SchemaDefinitionNode, + OperationTypeDefinition: OperationTypeDefinitionNode, + ScalarTypeDefinition: ScalarTypeDefinitionNode, + ObjectTypeDefinition: ObjectTypeDefinitionNode, + FieldDefinition: FieldDefinitionNode, + InputValueDefinition: InputValueDefinitionNode, + InterfaceTypeDefinition: InterfaceTypeDefinitionNode, + UnionTypeDefinition: UnionTypeDefinitionNode, + EnumTypeDefinition: EnumTypeDefinitionNode, + EnumValueDefinition: EnumValueDefinitionNode, + InputObjectTypeDefinition: InputObjectTypeDefinitionNode, + DirectiveDefinition: DirectiveDefinitionNode, + SchemaExtension: SchemaExtensionNode, + ScalarTypeExtension: ScalarTypeExtensionNode, + ObjectTypeExtension: ObjectTypeExtensionNode, + InterfaceTypeExtension: InterfaceTypeExtensionNode, + UnionTypeExtension: UnionTypeExtensionNode, + EnumTypeExtension: EnumTypeExtensionNode, + InputObjectTypeExtension: InputObjectTypeExtensionNode, +|}; + +// Name + +export type NameNode = { + +kind: 'Name', + +loc?: Location, + +value: string, +}; + +// Document + +export type DocumentNode = { + +kind: 'Document', + +loc?: Location, + +definitions: $ReadOnlyArray, +}; + +export type DefinitionNode = + | ExecutableDefinitionNode + | TypeSystemDefinitionNode + | TypeSystemExtensionNode; + +export type ExecutableDefinitionNode = + | OperationDefinitionNode + | FragmentDefinitionNode; + +export type OperationDefinitionNode = { + +kind: 'OperationDefinition', + +loc?: Location, + +operation: OperationTypeNode, + +name?: NameNode, + +variableDefinitions?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +selectionSet: SelectionSetNode, +}; + +export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; + +export type VariableDefinitionNode = { + +kind: 'VariableDefinition', + +loc?: Location, + +variable: VariableNode, + +type: TypeNode, + +defaultValue?: ValueNode, + +directives?: $ReadOnlyArray, +}; + +export type VariableNode = { + +kind: 'Variable', + +loc?: Location, + +name: NameNode, +}; + +export type SelectionSetNode = { + kind: 'SelectionSet', + loc?: Location, + selections: $ReadOnlyArray, +}; + +export type SelectionNode = FieldNode | FragmentSpreadNode | InlineFragmentNode; + +export type FieldNode = { + +kind: 'Field', + +loc?: Location, + +alias?: NameNode, + +name: NameNode, + +arguments?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +selectionSet?: SelectionSetNode, +}; + +export type ArgumentNode = { + +kind: 'Argument', + +loc?: Location, + +name: NameNode, + +value: ValueNode, +}; + +// Fragments + +export type FragmentSpreadNode = { + +kind: 'FragmentSpread', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type InlineFragmentNode = { + +kind: 'InlineFragment', + +loc?: Location, + +typeCondition?: NamedTypeNode, + +directives?: $ReadOnlyArray, + +selectionSet: SelectionSetNode, +}; + +export type FragmentDefinitionNode = { + +kind: 'FragmentDefinition', + +loc?: Location, + +name: NameNode, + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + +variableDefinitions?: $ReadOnlyArray, + +typeCondition: NamedTypeNode, + +directives?: $ReadOnlyArray, + +selectionSet: SelectionSetNode, +}; + +// Values + +export type ValueNode = + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; + +export type IntValueNode = { + +kind: 'IntValue', + +loc?: Location, + +value: string, +}; + +export type FloatValueNode = { + +kind: 'FloatValue', + +loc?: Location, + +value: string, +}; + +export type StringValueNode = { + +kind: 'StringValue', + +loc?: Location, + +value: string, + +block?: boolean, +}; + +export type BooleanValueNode = { + +kind: 'BooleanValue', + +loc?: Location, + +value: boolean, +}; + +export type NullValueNode = { + +kind: 'NullValue', + +loc?: Location, +}; + +export type EnumValueNode = { + +kind: 'EnumValue', + +loc?: Location, + +value: string, +}; + +export type ListValueNode = { + +kind: 'ListValue', + +loc?: Location, + +values: $ReadOnlyArray, +}; + +export type ObjectValueNode = { + +kind: 'ObjectValue', + +loc?: Location, + +fields: $ReadOnlyArray, +}; + +export type ObjectFieldNode = { + +kind: 'ObjectField', + +loc?: Location, + +name: NameNode, + +value: ValueNode, +}; + +// Directives + +export type DirectiveNode = { + +kind: 'Directive', + +loc?: Location, + +name: NameNode, + +arguments?: $ReadOnlyArray, +}; + +// Type Reference + +export type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; + +export type NamedTypeNode = { + +kind: 'NamedType', + +loc?: Location, + +name: NameNode, +}; + +export type ListTypeNode = { + +kind: 'ListType', + +loc?: Location, + +type: TypeNode, +}; + +export type NonNullTypeNode = { + +kind: 'NonNullType', + +loc?: Location, + +type: NamedTypeNode | ListTypeNode, +}; + +// Type System Definition + +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode + | TypeDefinitionNode + | DirectiveDefinitionNode; + +export type SchemaDefinitionNode = { + +kind: 'SchemaDefinition', + +loc?: Location, + +directives?: $ReadOnlyArray, + +operationTypes: $ReadOnlyArray, +}; + +export type OperationTypeDefinitionNode = { + +kind: 'OperationTypeDefinition', + +loc?: Location, + +operation: OperationTypeNode, + +type: NamedTypeNode, +}; + +// Type Definition + +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; + +export type ScalarTypeDefinitionNode = { + +kind: 'ScalarTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type ObjectTypeDefinitionNode = { + +kind: 'ObjectTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +interfaces?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type FieldDefinitionNode = { + +kind: 'FieldDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +arguments?: $ReadOnlyArray, + +type: TypeNode, + +directives?: $ReadOnlyArray, +}; + +export type InputValueDefinitionNode = { + +kind: 'InputValueDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +type: TypeNode, + +defaultValue?: ValueNode, + +directives?: $ReadOnlyArray, +}; + +export type InterfaceTypeDefinitionNode = { + +kind: 'InterfaceTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type UnionTypeDefinitionNode = { + +kind: 'UnionTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +types?: $ReadOnlyArray, +}; + +export type EnumTypeDefinitionNode = { + +kind: 'EnumTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +values?: $ReadOnlyArray, +}; + +export type EnumValueDefinitionNode = { + +kind: 'EnumValueDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type InputObjectTypeDefinitionNode = { + +kind: 'InputObjectTypeDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +// Directive Definitions + +export type DirectiveDefinitionNode = { + +kind: 'DirectiveDefinition', + +loc?: Location, + +description?: StringValueNode, + +name: NameNode, + +arguments?: $ReadOnlyArray, + +locations: $ReadOnlyArray, +}; + +// Type System Extensions + +export type TypeSystemExtensionNode = SchemaExtensionNode | TypeExtensionNode; + +export type SchemaExtensionNode = { + +kind: 'SchemaExtension', + +loc?: Location, + +directives?: $ReadOnlyArray, + +operationTypes?: $ReadOnlyArray, +}; + +// Type Extensions + +export type TypeExtensionNode = + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; + +export type ScalarTypeExtensionNode = { + +kind: 'ScalarTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, +}; + +export type ObjectTypeExtensionNode = { + +kind: 'ObjectTypeExtension', + +loc?: Location, + +name: NameNode, + +interfaces?: $ReadOnlyArray, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type InterfaceTypeExtensionNode = { + +kind: 'InterfaceTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; + +export type UnionTypeExtensionNode = { + +kind: 'UnionTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +types?: $ReadOnlyArray, +}; + +export type EnumTypeExtensionNode = { + +kind: 'EnumTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +values?: $ReadOnlyArray, +}; + +export type InputObjectTypeExtensionNode = { + +kind: 'InputObjectTypeExtension', + +loc?: Location, + +name: NameNode, + +directives?: $ReadOnlyArray, + +fields?: $ReadOnlyArray, +}; diff --git a/node_modules/graphql/language/ast.mjs b/node_modules/graphql/language/ast.mjs new file mode 100644 index 00000000..e69de29b diff --git a/node_modules/graphql/language/blockStringValue.js b/node_modules/graphql/language/blockStringValue.js new file mode 100644 index 00000000..d68146bc --- /dev/null +++ b/node_modules/graphql/language/blockStringValue.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = blockStringValue; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +function blockStringValue(rawString) { + // Expand a block string's raw value into independent lines. + var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first. + + var commonIndent = null; + + for (var i = 1; i < lines.length; i++) { + var line = lines[i]; + var indent = leadingWhitespace(line); + + if (indent < line.length && (commonIndent === null || indent < commonIndent)) { + commonIndent = indent; + + if (commonIndent === 0) { + break; + } + } + } + + if (commonIndent) { + for (var _i = 1; _i < lines.length; _i++) { + lines[_i] = lines[_i].slice(commonIndent); + } + } // Remove leading and trailing blank lines. + + + while (lines.length > 0 && isBlank(lines[0])) { + lines.shift(); + } + + while (lines.length > 0 && isBlank(lines[lines.length - 1])) { + lines.pop(); + } // Return a string of the lines joined with U+000A. + + + return lines.join('\n'); +} + +function leadingWhitespace(str) { + var i = 0; + + while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { + i++; + } + + return i; +} + +function isBlank(str) { + return leadingWhitespace(str) === str.length; +} \ No newline at end of file diff --git a/node_modules/graphql/language/blockStringValue.js.flow b/node_modules/graphql/language/blockStringValue.js.flow new file mode 100644 index 00000000..5b90bc05 --- /dev/null +++ b/node_modules/graphql/language/blockStringValue.js.flow @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +export default function blockStringValue(rawString: string): string { + // Expand a block string's raw value into independent lines. + const lines = rawString.split(/\r\n|[\n\r]/g); + + // Remove common indentation from all lines but first. + let commonIndent = null; + for (let i = 1; i < lines.length; i++) { + const line = lines[i]; + const indent = leadingWhitespace(line); + if ( + indent < line.length && + (commonIndent === null || indent < commonIndent) + ) { + commonIndent = indent; + if (commonIndent === 0) { + break; + } + } + } + + if (commonIndent) { + for (let i = 1; i < lines.length; i++) { + lines[i] = lines[i].slice(commonIndent); + } + } + + // Remove leading and trailing blank lines. + while (lines.length > 0 && isBlank(lines[0])) { + lines.shift(); + } + while (lines.length > 0 && isBlank(lines[lines.length - 1])) { + lines.pop(); + } + + // Return a string of the lines joined with U+000A. + return lines.join('\n'); +} + +function leadingWhitespace(str) { + let i = 0; + while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { + i++; + } + return i; +} + +function isBlank(str) { + return leadingWhitespace(str) === str.length; +} diff --git a/node_modules/graphql/language/blockStringValue.mjs b/node_modules/graphql/language/blockStringValue.mjs new file mode 100644 index 00000000..d28e619e --- /dev/null +++ b/node_modules/graphql/language/blockStringValue.mjs @@ -0,0 +1,66 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + */ +export default function blockStringValue(rawString) { + // Expand a block string's raw value into independent lines. + var lines = rawString.split(/\r\n|[\n\r]/g); // Remove common indentation from all lines but first. + + var commonIndent = null; + + for (var i = 1; i < lines.length; i++) { + var line = lines[i]; + var indent = leadingWhitespace(line); + + if (indent < line.length && (commonIndent === null || indent < commonIndent)) { + commonIndent = indent; + + if (commonIndent === 0) { + break; + } + } + } + + if (commonIndent) { + for (var _i = 1; _i < lines.length; _i++) { + lines[_i] = lines[_i].slice(commonIndent); + } + } // Remove leading and trailing blank lines. + + + while (lines.length > 0 && isBlank(lines[0])) { + lines.shift(); + } + + while (lines.length > 0 && isBlank(lines[lines.length - 1])) { + lines.pop(); + } // Return a string of the lines joined with U+000A. + + + return lines.join('\n'); +} + +function leadingWhitespace(str) { + var i = 0; + + while (i < str.length && (str[i] === ' ' || str[i] === '\t')) { + i++; + } + + return i; +} + +function isBlank(str) { + return leadingWhitespace(str) === str.length; +} \ No newline at end of file diff --git a/node_modules/graphql/language/directiveLocation.js b/node_modules/graphql/language/directiveLocation.js new file mode 100644 index 00000000..3221e97e --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DirectiveLocation = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed directive location values. + */ +var DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION' +}); +/** + * The enum type representing the directive location values. + */ + +exports.DirectiveLocation = DirectiveLocation; \ No newline at end of file diff --git a/node_modules/graphql/language/directiveLocation.js.flow b/node_modules/graphql/language/directiveLocation.js.flow new file mode 100644 index 00000000..e63ec67c --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.js.flow @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The set of allowed directive location values. + */ +export const DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', +}); + +/** + * The enum type representing the directive location values. + */ +export type DirectiveLocationEnum = $Values; diff --git a/node_modules/graphql/language/directiveLocation.mjs b/node_modules/graphql/language/directiveLocation.mjs new file mode 100644 index 00000000..45d897f8 --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.mjs @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed directive location values. + */ +export var DirectiveLocation = Object.freeze({ + // Request Definitions + QUERY: 'QUERY', + MUTATION: 'MUTATION', + SUBSCRIPTION: 'SUBSCRIPTION', + FIELD: 'FIELD', + FRAGMENT_DEFINITION: 'FRAGMENT_DEFINITION', + FRAGMENT_SPREAD: 'FRAGMENT_SPREAD', + INLINE_FRAGMENT: 'INLINE_FRAGMENT', + VARIABLE_DEFINITION: 'VARIABLE_DEFINITION', + // Type System Definitions + SCHEMA: 'SCHEMA', + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + FIELD_DEFINITION: 'FIELD_DEFINITION', + ARGUMENT_DEFINITION: 'ARGUMENT_DEFINITION', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + ENUM_VALUE: 'ENUM_VALUE', + INPUT_OBJECT: 'INPUT_OBJECT', + INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION' +}); +/** + * The enum type representing the directive location values. + */ \ No newline at end of file diff --git a/node_modules/graphql/language/index.js b/node_modules/graphql/language/index.js new file mode 100644 index 00000000..e698cd1b --- /dev/null +++ b/node_modules/graphql/language/index.js @@ -0,0 +1,167 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getLocation", { + enumerable: true, + get: function get() { + return _location.getLocation; + } +}); +Object.defineProperty(exports, "Kind", { + enumerable: true, + get: function get() { + return _kinds.Kind; + } +}); +Object.defineProperty(exports, "createLexer", { + enumerable: true, + get: function get() { + return _lexer.createLexer; + } +}); +Object.defineProperty(exports, "TokenKind", { + enumerable: true, + get: function get() { + return _lexer.TokenKind; + } +}); +Object.defineProperty(exports, "parse", { + enumerable: true, + get: function get() { + return _parser.parse; + } +}); +Object.defineProperty(exports, "parseValue", { + enumerable: true, + get: function get() { + return _parser.parseValue; + } +}); +Object.defineProperty(exports, "parseType", { + enumerable: true, + get: function get() { + return _parser.parseType; + } +}); +Object.defineProperty(exports, "print", { + enumerable: true, + get: function get() { + return _printer.print; + } +}); +Object.defineProperty(exports, "Source", { + enumerable: true, + get: function get() { + return _source.Source; + } +}); +Object.defineProperty(exports, "visit", { + enumerable: true, + get: function get() { + return _visitor.visit; + } +}); +Object.defineProperty(exports, "visitInParallel", { + enumerable: true, + get: function get() { + return _visitor.visitInParallel; + } +}); +Object.defineProperty(exports, "visitWithTypeInfo", { + enumerable: true, + get: function get() { + return _visitor.visitWithTypeInfo; + } +}); +Object.defineProperty(exports, "getVisitFn", { + enumerable: true, + get: function get() { + return _visitor.getVisitFn; + } +}); +Object.defineProperty(exports, "BREAK", { + enumerable: true, + get: function get() { + return _visitor.BREAK; + } +}); +Object.defineProperty(exports, "isDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isDefinitionNode; + } +}); +Object.defineProperty(exports, "isExecutableDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isExecutableDefinitionNode; + } +}); +Object.defineProperty(exports, "isSelectionNode", { + enumerable: true, + get: function get() { + return _predicates.isSelectionNode; + } +}); +Object.defineProperty(exports, "isValueNode", { + enumerable: true, + get: function get() { + return _predicates.isValueNode; + } +}); +Object.defineProperty(exports, "isTypeNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeNode; + } +}); +Object.defineProperty(exports, "isTypeSystemDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeSystemDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeDefinitionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeDefinitionNode; + } +}); +Object.defineProperty(exports, "isTypeSystemExtensionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeSystemExtensionNode; + } +}); +Object.defineProperty(exports, "isTypeExtensionNode", { + enumerable: true, + get: function get() { + return _predicates.isTypeExtensionNode; + } +}); +Object.defineProperty(exports, "DirectiveLocation", { + enumerable: true, + get: function get() { + return _directiveLocation.DirectiveLocation; + } +}); + +var _location = require("./location"); + +var _kinds = require("./kinds"); + +var _lexer = require("./lexer"); + +var _parser = require("./parser"); + +var _printer = require("./printer"); + +var _source = require("./source"); + +var _visitor = require("./visitor"); + +var _predicates = require("./predicates"); + +var _directiveLocation = require("./directiveLocation"); \ No newline at end of file diff --git a/node_modules/graphql/language/index.js.flow b/node_modules/graphql/language/index.js.flow new file mode 100644 index 00000000..8054718a --- /dev/null +++ b/node_modules/graphql/language/index.js.flow @@ -0,0 +1,104 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { getLocation } from './location'; +export type { SourceLocation } from './location'; +export { Kind } from './kinds'; +export type { KindEnum } from './kinds'; +export { createLexer, TokenKind } from './lexer'; +export { parse, parseValue, parseType } from './parser'; +export { print } from './printer'; +export { Source } from './source'; +export { + visit, + visitInParallel, + visitWithTypeInfo, + getVisitFn, + BREAK, +} from './visitor'; +export type { ASTVisitor, Visitor, VisitFn, VisitorKeyMap } from './visitor'; + +export type { Lexer, TokenKindEnum } from './lexer'; +export type { ParseOptions } from './parser'; + +export type { + Location, + Token, + ASTNode, + ASTKindToNode, + // Each kind of AST node + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; + +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, +} from './predicates'; + +export { DirectiveLocation } from './directiveLocation'; +export type { DirectiveLocationEnum } from './directiveLocation'; diff --git a/node_modules/graphql/language/index.mjs b/node_modules/graphql/language/index.mjs new file mode 100644 index 00000000..a2940e2a --- /dev/null +++ b/node_modules/graphql/language/index.mjs @@ -0,0 +1,17 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { getLocation } from './location'; +export { Kind } from './kinds'; +export { createLexer, TokenKind } from './lexer'; +export { parse, parseValue, parseType } from './parser'; +export { print } from './printer'; +export { Source } from './source'; +export { visit, visitInParallel, visitWithTypeInfo, getVisitFn, BREAK } from './visitor'; +export { isDefinitionNode, isExecutableDefinitionNode, isSelectionNode, isValueNode, isTypeNode, isTypeSystemDefinitionNode, isTypeDefinitionNode, isTypeSystemExtensionNode, isTypeExtensionNode } from './predicates'; +export { DirectiveLocation } from './directiveLocation'; \ No newline at end of file diff --git a/node_modules/graphql/language/kinds.js b/node_modules/graphql/language/kinds.js new file mode 100644 index 00000000..7eded7a3 --- /dev/null +++ b/node_modules/graphql/language/kinds.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Kind = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed kind values for AST nodes. + */ +var Kind = Object.freeze({ + // Name + NAME: 'Name', + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + // Directives + DIRECTIVE: 'Directive', + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension' +}); +/** + * The enum type representing the possible kind values of AST nodes. + */ + +exports.Kind = Kind; \ No newline at end of file diff --git a/node_modules/graphql/language/kinds.js.flow b/node_modules/graphql/language/kinds.js.flow new file mode 100644 index 00000000..ad46306b --- /dev/null +++ b/node_modules/graphql/language/kinds.js.flow @@ -0,0 +1,83 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +/** + * The set of allowed kind values for AST nodes. + */ +export const Kind = Object.freeze({ + // Name + NAME: 'Name', + + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + + // Directives + DIRECTIVE: 'Directive', + + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension', +}); + +/** + * The enum type representing the possible kind values of AST nodes. + */ +export type KindEnum = $Values; diff --git a/node_modules/graphql/language/kinds.mjs b/node_modules/graphql/language/kinds.mjs new file mode 100644 index 00000000..a973e661 --- /dev/null +++ b/node_modules/graphql/language/kinds.mjs @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * The set of allowed kind values for AST nodes. + */ +export var Kind = Object.freeze({ + // Name + NAME: 'Name', + // Document + DOCUMENT: 'Document', + OPERATION_DEFINITION: 'OperationDefinition', + VARIABLE_DEFINITION: 'VariableDefinition', + SELECTION_SET: 'SelectionSet', + FIELD: 'Field', + ARGUMENT: 'Argument', + // Fragments + FRAGMENT_SPREAD: 'FragmentSpread', + INLINE_FRAGMENT: 'InlineFragment', + FRAGMENT_DEFINITION: 'FragmentDefinition', + // Values + VARIABLE: 'Variable', + INT: 'IntValue', + FLOAT: 'FloatValue', + STRING: 'StringValue', + BOOLEAN: 'BooleanValue', + NULL: 'NullValue', + ENUM: 'EnumValue', + LIST: 'ListValue', + OBJECT: 'ObjectValue', + OBJECT_FIELD: 'ObjectField', + // Directives + DIRECTIVE: 'Directive', + // Types + NAMED_TYPE: 'NamedType', + LIST_TYPE: 'ListType', + NON_NULL_TYPE: 'NonNullType', + // Type System Definitions + SCHEMA_DEFINITION: 'SchemaDefinition', + OPERATION_TYPE_DEFINITION: 'OperationTypeDefinition', + // Type Definitions + SCALAR_TYPE_DEFINITION: 'ScalarTypeDefinition', + OBJECT_TYPE_DEFINITION: 'ObjectTypeDefinition', + FIELD_DEFINITION: 'FieldDefinition', + INPUT_VALUE_DEFINITION: 'InputValueDefinition', + INTERFACE_TYPE_DEFINITION: 'InterfaceTypeDefinition', + UNION_TYPE_DEFINITION: 'UnionTypeDefinition', + ENUM_TYPE_DEFINITION: 'EnumTypeDefinition', + ENUM_VALUE_DEFINITION: 'EnumValueDefinition', + INPUT_OBJECT_TYPE_DEFINITION: 'InputObjectTypeDefinition', + // Directive Definitions + DIRECTIVE_DEFINITION: 'DirectiveDefinition', + // Type System Extensions + SCHEMA_EXTENSION: 'SchemaExtension', + // Type Extensions + SCALAR_TYPE_EXTENSION: 'ScalarTypeExtension', + OBJECT_TYPE_EXTENSION: 'ObjectTypeExtension', + INTERFACE_TYPE_EXTENSION: 'InterfaceTypeExtension', + UNION_TYPE_EXTENSION: 'UnionTypeExtension', + ENUM_TYPE_EXTENSION: 'EnumTypeExtension', + INPUT_OBJECT_TYPE_EXTENSION: 'InputObjectTypeExtension' +}); +/** + * The enum type representing the possible kind values of AST nodes. + */ \ No newline at end of file diff --git a/node_modules/graphql/language/lexer.js b/node_modules/graphql/language/lexer.js new file mode 100644 index 00000000..1678775d --- /dev/null +++ b/node_modules/graphql/language/lexer.js @@ -0,0 +1,648 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.createLexer = createLexer; +exports.getTokenDesc = getTokenDesc; +exports.TokenKind = void 0; + +var _error = require("../error"); + +var _blockStringValue = _interopRequireDefault(require("./blockStringValue")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +function createLexer(source, options) { + var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null); + var lexer = { + source: source, + options: options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer, + lookahead: lookahead + }; + return lexer; +} + +function advanceLexer() { + this.lastToken = this.token; + var token = this.token = this.lookahead(); + return token; +} + +function lookahead() { + var token = this.token; + + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next || (token.next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + + return token; +} +/** + * The return type of createLexer. + */ + + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind = Object.freeze({ + SOF: '', + EOF: '', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment' +}); +/** + * The enum type representing the token kinds values. + */ + +exports.TokenKind = TokenKind; + +/** + * A helper function to describe a token as a string for debugging + */ +function getTokenDesc(token) { + var value = token.value; + return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind; +} + +var charCodeAt = String.prototype.charCodeAt; +var slice = String.prototype.slice; +/** + * Helper function for constructing the Token object. + */ + +function Tok(kind, start, end, line, column, prev, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; +}; + +function printCharCode(code) { + return (// NaN/undefined represents access beyond the end of the file. + isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII. + code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form. + "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"") + ); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments until it finds the next lexable + * token, then lexes punctuators immediately or calls the appropriate helper + * function for more complicated tokens. + */ + + +function readToken(lexer, prev) { + var source = lexer.source; + var body = source.body; + var bodyLength = body.length; + var pos = positionAfterWhitespace(body, prev.end, lexer); + var line = lexer.line; + var col = 1 + pos - lexer.lineStart; + + if (pos >= bodyLength) { + return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); + } + + var code = charCodeAt.call(body, pos); // SourceCharacter + + switch (code) { + // ! + case 33: + return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev); + // # + + case 35: + return readComment(source, pos, line, col, prev); + // $ + + case 36: + return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + // & + + case 38: + return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev); + // ( + + case 40: + return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + // ) + + case 41: + return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + // . + + case 46: + if (charCodeAt.call(body, pos + 1) === 46 && charCodeAt.call(body, pos + 2) === 46) { + return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + + break; + // : + + case 58: + return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev); + // = + + case 61: + return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + // @ + + case 64: + return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev); + // [ + + case 91: + return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + // ] + + case 93: + return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + // { + + case 123: + return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + // | + + case 124: + return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev); + // } + + case 125: + return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + // A-Z _ a-z + + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 88: + case 89: + case 90: + case 95: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + return readName(source, pos, line, col, prev); + // - 0-9 + + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return readNumber(source, pos, code, line, col, prev); + // " + + case 34: + if (charCodeAt.call(body, pos + 1) === 34 && charCodeAt.call(body, pos + 2) === 34) { + return readBlockString(source, pos, line, col, prev); + } + + return readString(source, pos, line, col, prev); + } + + throw (0, _error.syntaxError)(source, pos, unexpectedCharacterMessage(code)); +} +/** + * Report a message that an unexpected character was encountered. + */ + + +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return "Cannot contain the invalid character ".concat(printCharCode(code), "."); + } + + if (code === 39) { + // ' + return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?'; + } + + return "Cannot parse the unexpected character ".concat(printCharCode(code), "."); +} +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented character, then returns the position of that character for + * lexing. + */ + + +function positionAfterWhitespace(body, startPosition, lexer) { + var bodyLength = body.length; + var position = startPosition; + + while (position < bodyLength) { + var code = charCodeAt.call(body, position); // tab | space | comma | BOM + + if (code === 9 || code === 32 || code === 44 || code === 0xfeff) { + ++position; + } else if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (charCodeAt.call(body, position + 1) === 10) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + } else { + break; + } + } + + return position; +} +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ + + +function readComment(source, start, line, col, prev) { + var body = source.body; + var code; + var position = start; + + do { + code = charCodeAt.call(body, ++position); + } while (code !== null && ( // SourceCharacter but not LineTerminator + code > 0x001f || code === 0x0009)); + + return new Tok(TokenKind.COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position)); +} +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ + + +function readNumber(source, start, firstCode, line, col, prev) { + var body = source.body; + var code = firstCode; + var position = start; + var isFloat = false; + + if (code === 45) { + // - + code = charCodeAt.call(body, ++position); + } + + if (code === 48) { + // 0 + code = charCodeAt.call(body, ++position); + + if (code >= 48 && code <= 57) { + throw (0, _error.syntaxError)(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), ".")); + } + } else { + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 46) { + // . + isFloat = true; + code = charCodeAt.call(body, ++position); + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + code = charCodeAt.call(body, ++position); + + if (code === 43 || code === 45) { + // + - + code = charCodeAt.call(body, ++position); + } + + position = readDigits(source, position, code); + } + + return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, slice.call(body, start, position)); +} +/** + * Returns the new position in the source after reading digits. + */ + + +function readDigits(source, start, firstCode) { + var body = source.body; + var position = start; + var code = firstCode; + + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = charCodeAt.call(body, ++position); + } while (code >= 48 && code <= 57); // 0 - 9 + + + return position; + } + + throw (0, _error.syntaxError)(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); +} +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ + + +function readString(source, start, line, col, prev) { + var body = source.body; + var position = start + 1; + var chunkStart = position; + var code = 0; + var value = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null && // not LineTerminator + code !== 0x000a && code !== 0x000d) { + // Closing Quote (") + if (code === 34) { + value += slice.call(body, chunkStart, position); + return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009) { + throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + ++position; + + if (code === 92) { + // \ + value += slice.call(body, chunkStart, position - 1); + code = charCodeAt.call(body, position); + + switch (code) { + case 34: + value += '"'; + break; + + case 47: + value += '/'; + break; + + case 92: + value += '\\'; + break; + + case 98: + value += '\b'; + break; + + case 102: + value += '\f'; + break; + + case 110: + value += '\n'; + break; + + case 114: + value += '\r'; + break; + + case 116: + value += '\t'; + break; + + case 117: + // u + var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4)); + + if (charCode < 0) { + throw (0, _error.syntaxError)(source, position, 'Invalid character escape sequence: ' + "\\u".concat(body.slice(position + 1, position + 5), ".")); + } + + value += String.fromCharCode(charCode); + position += 4; + break; + + default: + throw (0, _error.syntaxError)(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), ".")); + } + + ++position; + chunkStart = position; + } + } + + throw (0, _error.syntaxError)(source, position, 'Unterminated string.'); +} +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ + + +function readBlockString(source, start, line, col, prev) { + var body = source.body; + var position = start + 3; + var chunkStart = position; + var code = 0; + var rawValue = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null) { + // Closing Triple-Quote (""") + if (code === 34 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34) { + rawValue += slice.call(body, chunkStart, position); + return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, (0, _blockStringValue.default)(rawValue)); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + throw (0, _error.syntaxError)(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } // Escape Triple-Quote (\""") + + + if (code === 92 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34 && charCodeAt.call(body, position + 3) === 34) { + rawValue += slice.call(body, chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw (0, _error.syntaxError)(source, position, 'Unterminated string.'); +} +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ + + +function uniCharCode(a, b, c, d) { + return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d); +} +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ + + +function char2hex(a) { + return a >= 48 && a <= 57 ? a - 48 // 0-9 + : a >= 65 && a <= 70 ? a - 55 // A-F + : a >= 97 && a <= 102 ? a - 87 // a-f + : -1; +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ + + +function readName(source, start, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var position = start + 1; + var code = 0; + + while (position !== bodyLength && (code = charCodeAt.call(body, position)) !== null && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122) // a-z + ) { + ++position; + } + + return new Tok(TokenKind.NAME, start, position, line, col, prev, slice.call(body, start, position)); +} \ No newline at end of file diff --git a/node_modules/graphql/language/lexer.js.flow b/node_modules/graphql/language/lexer.js.flow new file mode 100644 index 00000000..9eff1c25 --- /dev/null +++ b/node_modules/graphql/language/lexer.js.flow @@ -0,0 +1,752 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Token } from './ast'; +import type { Source } from './source'; +import { syntaxError } from '../error'; +import blockStringValue from './blockStringValue'; + +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export function createLexer( + source: Source, + options: TOptions, +): Lexer { + const startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null); + const lexer: Lexer = { + source, + options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer, + lookahead, + }; + return lexer; +} + +function advanceLexer() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; +} + +function lookahead() { + let token = this.token; + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next || ((token: any).next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + return token; +} + +/** + * The return type of createLexer. + */ +export type Lexer = { + source: Source, + options: TOptions, + + /** + * The previously focused non-ignored token. + */ + lastToken: Token, + + /** + * The currently focused non-ignored token. + */ + token: Token, + + /** + * The (1-indexed) line containing the current token. + */ + line: number, + + /** + * The character offset at which the current line begins. + */ + lineStart: number, + + /** + * Advances the token stream to the next non-ignored token. + */ + advance(): Token, + + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the Lexer's state. + */ + lookahead(): Token, +}; + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export const TokenKind = Object.freeze({ + SOF: '', + EOF: '', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment', +}); + +/** + * The enum type representing the token kinds values. + */ +export type TokenKindEnum = $Values; + +/** + * A helper function to describe a token as a string for debugging + */ +export function getTokenDesc(token: Token): string { + const value = token.value; + return value ? `${token.kind} "${value}"` : token.kind; +} + +const charCodeAt = String.prototype.charCodeAt; +const slice = String.prototype.slice; + +/** + * Helper function for constructing the Token object. + */ +function Tok( + kind: TokenKindEnum, + start: number, + end: number, + line: number, + column: number, + prev: Token | null, + value?: string, +) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; +} + +// Print a simplified form when appearing in JSON/util.inspect. +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; +}; + +function printCharCode(code) { + return ( + // NaN/undefined represents access beyond the end of the file. + isNaN(code) + ? TokenKind.EOF + : // Trust JSON for ASCII. + code < 0x007f + ? JSON.stringify(String.fromCharCode(code)) + : // Otherwise print the escaped form. + `"\\u${('00' + code.toString(16).toUpperCase()).slice(-4)}"` + ); +} + +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments until it finds the next lexable + * token, then lexes punctuators immediately or calls the appropriate helper + * function for more complicated tokens. + */ +function readToken(lexer: Lexer<*>, prev: Token): Token { + const source = lexer.source; + const body = source.body; + const bodyLength = body.length; + + const pos = positionAfterWhitespace(body, prev.end, lexer); + const line = lexer.line; + const col = 1 + pos - lexer.lineStart; + + if (pos >= bodyLength) { + return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); + } + + const code = charCodeAt.call(body, pos); + + // SourceCharacter + switch (code) { + // ! + case 33: + return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev); + // # + case 35: + return readComment(source, pos, line, col, prev); + // $ + case 36: + return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + // & + case 38: + return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev); + // ( + case 40: + return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + // ) + case 41: + return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + // . + case 46: + if ( + charCodeAt.call(body, pos + 1) === 46 && + charCodeAt.call(body, pos + 2) === 46 + ) { + return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + break; + // : + case 58: + return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev); + // = + case 61: + return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + // @ + case 64: + return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev); + // [ + case 91: + return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + // ] + case 93: + return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + // { + case 123: + return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + // | + case 124: + return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev); + // } + case 125: + return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + // A-Z _ a-z + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 88: + case 89: + case 90: + case 95: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + return readName(source, pos, line, col, prev); + // - 0-9 + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return readNumber(source, pos, code, line, col, prev); + // " + case 34: + if ( + charCodeAt.call(body, pos + 1) === 34 && + charCodeAt.call(body, pos + 2) === 34 + ) { + return readBlockString(source, pos, line, col, prev); + } + return readString(source, pos, line, col, prev); + } + + throw syntaxError(source, pos, unexpectedCharacterMessage(code)); +} + +/** + * Report a message that an unexpected character was encountered. + */ +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return `Cannot contain the invalid character ${printCharCode(code)}.`; + } + + if (code === 39) { + // ' + return ( + "Unexpected single quote character ('), did you mean to use " + + 'a double quote (")?' + ); + } + + return `Cannot parse the unexpected character ${printCharCode(code)}.`; +} + +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented character, then returns the position of that character for + * lexing. + */ +function positionAfterWhitespace( + body: string, + startPosition: number, + lexer: Lexer<*>, +): number { + const bodyLength = body.length; + let position = startPosition; + while (position < bodyLength) { + const code = charCodeAt.call(body, position); + // tab | space | comma | BOM + if (code === 9 || code === 32 || code === 44 || code === 0xfeff) { + ++position; + } else if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (charCodeAt.call(body, position + 1) === 10) { + position += 2; + } else { + ++position; + } + ++lexer.line; + lexer.lineStart = position; + } else { + break; + } + } + return position; +} + +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ +function readComment(source, start, line, col, prev): Token { + const body = source.body; + let code; + let position = start; + + do { + code = charCodeAt.call(body, ++position); + } while ( + code !== null && + // SourceCharacter but not LineTerminator + (code > 0x001f || code === 0x0009) + ); + + return new Tok( + TokenKind.COMMENT, + start, + position, + line, + col, + prev, + slice.call(body, start + 1, position), + ); +} + +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ +function readNumber(source, start, firstCode, line, col, prev): Token { + const body = source.body; + let code = firstCode; + let position = start; + let isFloat = false; + + if (code === 45) { + // - + code = charCodeAt.call(body, ++position); + } + + if (code === 48) { + // 0 + code = charCodeAt.call(body, ++position); + if (code >= 48 && code <= 57) { + throw syntaxError( + source, + position, + `Invalid number, unexpected digit after 0: ${printCharCode(code)}.`, + ); + } + } else { + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 46) { + // . + isFloat = true; + + code = charCodeAt.call(body, ++position); + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + + code = charCodeAt.call(body, ++position); + if (code === 43 || code === 45) { + // + - + code = charCodeAt.call(body, ++position); + } + position = readDigits(source, position, code); + } + + return new Tok( + isFloat ? TokenKind.FLOAT : TokenKind.INT, + start, + position, + line, + col, + prev, + slice.call(body, start, position), + ); +} + +/** + * Returns the new position in the source after reading digits. + */ +function readDigits(source, start, firstCode) { + const body = source.body; + let position = start; + let code = firstCode; + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = charCodeAt.call(body, ++position); + } while (code >= 48 && code <= 57); // 0 - 9 + return position; + } + throw syntaxError( + source, + position, + `Invalid number, expected digit but got: ${printCharCode(code)}.`, + ); +} + +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ +function readString(source, start, line, col, prev): Token { + const body = source.body; + let position = start + 1; + let chunkStart = position; + let code = 0; + let value = ''; + + while ( + position < body.length && + (code = charCodeAt.call(body, position)) !== null && + // not LineTerminator + code !== 0x000a && + code !== 0x000d + ) { + // Closing Quote (") + if (code === 34) { + value += slice.call(body, chunkStart, position); + return new Tok( + TokenKind.STRING, + start, + position + 1, + line, + col, + prev, + value, + ); + } + + // SourceCharacter + if (code < 0x0020 && code !== 0x0009) { + throw syntaxError( + source, + position, + `Invalid character within String: ${printCharCode(code)}.`, + ); + } + + ++position; + if (code === 92) { + // \ + value += slice.call(body, chunkStart, position - 1); + code = charCodeAt.call(body, position); + switch (code) { + case 34: + value += '"'; + break; + case 47: + value += '/'; + break; + case 92: + value += '\\'; + break; + case 98: + value += '\b'; + break; + case 102: + value += '\f'; + break; + case 110: + value += '\n'; + break; + case 114: + value += '\r'; + break; + case 116: + value += '\t'; + break; + case 117: // u + const charCode = uniCharCode( + charCodeAt.call(body, position + 1), + charCodeAt.call(body, position + 2), + charCodeAt.call(body, position + 3), + charCodeAt.call(body, position + 4), + ); + if (charCode < 0) { + throw syntaxError( + source, + position, + 'Invalid character escape sequence: ' + + `\\u${body.slice(position + 1, position + 5)}.`, + ); + } + value += String.fromCharCode(charCode); + position += 4; + break; + default: + throw syntaxError( + source, + position, + `Invalid character escape sequence: \\${String.fromCharCode( + code, + )}.`, + ); + } + ++position; + chunkStart = position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} + +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ +function readBlockString(source, start, line, col, prev): Token { + const body = source.body; + let position = start + 3; + let chunkStart = position; + let code = 0; + let rawValue = ''; + + while ( + position < body.length && + (code = charCodeAt.call(body, position)) !== null + ) { + // Closing Triple-Quote (""") + if ( + code === 34 && + charCodeAt.call(body, position + 1) === 34 && + charCodeAt.call(body, position + 2) === 34 + ) { + rawValue += slice.call(body, chunkStart, position); + return new Tok( + TokenKind.BLOCK_STRING, + start, + position + 3, + line, + col, + prev, + blockStringValue(rawValue), + ); + } + + // SourceCharacter + if ( + code < 0x0020 && + code !== 0x0009 && + code !== 0x000a && + code !== 0x000d + ) { + throw syntaxError( + source, + position, + `Invalid character within String: ${printCharCode(code)}.`, + ); + } + + // Escape Triple-Quote (\""") + if ( + code === 92 && + charCodeAt.call(body, position + 1) === 34 && + charCodeAt.call(body, position + 2) === 34 && + charCodeAt.call(body, position + 3) === 34 + ) { + rawValue += slice.call(body, chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} + +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ +function uniCharCode(a, b, c, d) { + return ( + (char2hex(a) << 12) | (char2hex(b) << 8) | (char2hex(c) << 4) | char2hex(d) + ); +} + +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ +function char2hex(a) { + return a >= 48 && a <= 57 + ? a - 48 // 0-9 + : a >= 65 && a <= 70 + ? a - 55 // A-F + : a >= 97 && a <= 102 + ? a - 87 // a-f + : -1; +} + +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ +function readName(source, start, line, col, prev): Token { + const body = source.body; + const bodyLength = body.length; + let position = start + 1; + let code = 0; + while ( + position !== bodyLength && + (code = charCodeAt.call(body, position)) !== null && + (code === 95 || // _ + (code >= 48 && code <= 57) || // 0-9 + (code >= 65 && code <= 90) || // A-Z + (code >= 97 && code <= 122)) // a-z + ) { + ++position; + } + return new Tok( + TokenKind.NAME, + start, + position, + line, + col, + prev, + slice.call(body, start, position), + ); +} diff --git a/node_modules/graphql/language/lexer.mjs b/node_modules/graphql/language/lexer.mjs new file mode 100644 index 00000000..31a438a4 --- /dev/null +++ b/node_modules/graphql/language/lexer.mjs @@ -0,0 +1,632 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { syntaxError } from '../error'; +import blockStringValue from './blockStringValue'; +/** + * Given a Source object, this returns a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ + +export function createLexer(source, options) { + var startOfFileToken = new Tok(TokenKind.SOF, 0, 0, 0, 0, null); + var lexer = { + source: source, + options: options, + lastToken: startOfFileToken, + token: startOfFileToken, + line: 1, + lineStart: 0, + advance: advanceLexer, + lookahead: lookahead + }; + return lexer; +} + +function advanceLexer() { + this.lastToken = this.token; + var token = this.token = this.lookahead(); + return token; +} + +function lookahead() { + var token = this.token; + + if (token.kind !== TokenKind.EOF) { + do { + // Note: next is only mutable during parsing, so we cast to allow this. + token = token.next || (token.next = readToken(this, token)); + } while (token.kind === TokenKind.COMMENT); + } + + return token; +} +/** + * The return type of createLexer. + */ + + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +export var TokenKind = Object.freeze({ + SOF: '', + EOF: '', + BANG: '!', + DOLLAR: '$', + AMP: '&', + PAREN_L: '(', + PAREN_R: ')', + SPREAD: '...', + COLON: ':', + EQUALS: '=', + AT: '@', + BRACKET_L: '[', + BRACKET_R: ']', + BRACE_L: '{', + PIPE: '|', + BRACE_R: '}', + NAME: 'Name', + INT: 'Int', + FLOAT: 'Float', + STRING: 'String', + BLOCK_STRING: 'BlockString', + COMMENT: 'Comment' +}); +/** + * The enum type representing the token kinds values. + */ + +/** + * A helper function to describe a token as a string for debugging + */ +export function getTokenDesc(token) { + var value = token.value; + return value ? "".concat(token.kind, " \"").concat(value, "\"") : token.kind; +} +var charCodeAt = String.prototype.charCodeAt; +var slice = String.prototype.slice; +/** + * Helper function for constructing the Token object. + */ + +function Tok(kind, start, end, line, column, prev, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; + this.value = value; + this.prev = prev; + this.next = null; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Tok.prototype.toJSON = Tok.prototype.inspect = function toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column + }; +}; + +function printCharCode(code) { + return (// NaN/undefined represents access beyond the end of the file. + isNaN(code) ? TokenKind.EOF : // Trust JSON for ASCII. + code < 0x007f ? JSON.stringify(String.fromCharCode(code)) : // Otherwise print the escaped form. + "\"\\u".concat(('00' + code.toString(16).toUpperCase()).slice(-4), "\"") + ); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace and comments until it finds the next lexable + * token, then lexes punctuators immediately or calls the appropriate helper + * function for more complicated tokens. + */ + + +function readToken(lexer, prev) { + var source = lexer.source; + var body = source.body; + var bodyLength = body.length; + var pos = positionAfterWhitespace(body, prev.end, lexer); + var line = lexer.line; + var col = 1 + pos - lexer.lineStart; + + if (pos >= bodyLength) { + return new Tok(TokenKind.EOF, bodyLength, bodyLength, line, col, prev); + } + + var code = charCodeAt.call(body, pos); // SourceCharacter + + switch (code) { + // ! + case 33: + return new Tok(TokenKind.BANG, pos, pos + 1, line, col, prev); + // # + + case 35: + return readComment(source, pos, line, col, prev); + // $ + + case 36: + return new Tok(TokenKind.DOLLAR, pos, pos + 1, line, col, prev); + // & + + case 38: + return new Tok(TokenKind.AMP, pos, pos + 1, line, col, prev); + // ( + + case 40: + return new Tok(TokenKind.PAREN_L, pos, pos + 1, line, col, prev); + // ) + + case 41: + return new Tok(TokenKind.PAREN_R, pos, pos + 1, line, col, prev); + // . + + case 46: + if (charCodeAt.call(body, pos + 1) === 46 && charCodeAt.call(body, pos + 2) === 46) { + return new Tok(TokenKind.SPREAD, pos, pos + 3, line, col, prev); + } + + break; + // : + + case 58: + return new Tok(TokenKind.COLON, pos, pos + 1, line, col, prev); + // = + + case 61: + return new Tok(TokenKind.EQUALS, pos, pos + 1, line, col, prev); + // @ + + case 64: + return new Tok(TokenKind.AT, pos, pos + 1, line, col, prev); + // [ + + case 91: + return new Tok(TokenKind.BRACKET_L, pos, pos + 1, line, col, prev); + // ] + + case 93: + return new Tok(TokenKind.BRACKET_R, pos, pos + 1, line, col, prev); + // { + + case 123: + return new Tok(TokenKind.BRACE_L, pos, pos + 1, line, col, prev); + // | + + case 124: + return new Tok(TokenKind.PIPE, pos, pos + 1, line, col, prev); + // } + + case 125: + return new Tok(TokenKind.BRACE_R, pos, pos + 1, line, col, prev); + // A-Z _ a-z + + case 65: + case 66: + case 67: + case 68: + case 69: + case 70: + case 71: + case 72: + case 73: + case 74: + case 75: + case 76: + case 77: + case 78: + case 79: + case 80: + case 81: + case 82: + case 83: + case 84: + case 85: + case 86: + case 87: + case 88: + case 89: + case 90: + case 95: + case 97: + case 98: + case 99: + case 100: + case 101: + case 102: + case 103: + case 104: + case 105: + case 106: + case 107: + case 108: + case 109: + case 110: + case 111: + case 112: + case 113: + case 114: + case 115: + case 116: + case 117: + case 118: + case 119: + case 120: + case 121: + case 122: + return readName(source, pos, line, col, prev); + // - 0-9 + + case 45: + case 48: + case 49: + case 50: + case 51: + case 52: + case 53: + case 54: + case 55: + case 56: + case 57: + return readNumber(source, pos, code, line, col, prev); + // " + + case 34: + if (charCodeAt.call(body, pos + 1) === 34 && charCodeAt.call(body, pos + 2) === 34) { + return readBlockString(source, pos, line, col, prev); + } + + return readString(source, pos, line, col, prev); + } + + throw syntaxError(source, pos, unexpectedCharacterMessage(code)); +} +/** + * Report a message that an unexpected character was encountered. + */ + + +function unexpectedCharacterMessage(code) { + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + return "Cannot contain the invalid character ".concat(printCharCode(code), "."); + } + + if (code === 39) { + // ' + return "Unexpected single quote character ('), did you mean to use " + 'a double quote (")?'; + } + + return "Cannot parse the unexpected character ".concat(printCharCode(code), "."); +} +/** + * Reads from body starting at startPosition until it finds a non-whitespace + * or commented character, then returns the position of that character for + * lexing. + */ + + +function positionAfterWhitespace(body, startPosition, lexer) { + var bodyLength = body.length; + var position = startPosition; + + while (position < bodyLength) { + var code = charCodeAt.call(body, position); // tab | space | comma | BOM + + if (code === 9 || code === 32 || code === 44 || code === 0xfeff) { + ++position; + } else if (code === 10) { + // new line + ++position; + ++lexer.line; + lexer.lineStart = position; + } else if (code === 13) { + // carriage return + if (charCodeAt.call(body, position + 1) === 10) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + } else { + break; + } + } + + return position; +} +/** + * Reads a comment token from the source file. + * + * #[\u0009\u0020-\uFFFF]* + */ + + +function readComment(source, start, line, col, prev) { + var body = source.body; + var code; + var position = start; + + do { + code = charCodeAt.call(body, ++position); + } while (code !== null && ( // SourceCharacter but not LineTerminator + code > 0x001f || code === 0x0009)); + + return new Tok(TokenKind.COMMENT, start, position, line, col, prev, slice.call(body, start + 1, position)); +} +/** + * Reads a number token from the source file, either a float + * or an int depending on whether a decimal point appears. + * + * Int: -?(0|[1-9][0-9]*) + * Float: -?(0|[1-9][0-9]*)(\.[0-9]+)?((E|e)(+|-)?[0-9]+)? + */ + + +function readNumber(source, start, firstCode, line, col, prev) { + var body = source.body; + var code = firstCode; + var position = start; + var isFloat = false; + + if (code === 45) { + // - + code = charCodeAt.call(body, ++position); + } + + if (code === 48) { + // 0 + code = charCodeAt.call(body, ++position); + + if (code >= 48 && code <= 57) { + throw syntaxError(source, position, "Invalid number, unexpected digit after 0: ".concat(printCharCode(code), ".")); + } + } else { + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 46) { + // . + isFloat = true; + code = charCodeAt.call(body, ++position); + position = readDigits(source, position, code); + code = charCodeAt.call(body, position); + } + + if (code === 69 || code === 101) { + // E e + isFloat = true; + code = charCodeAt.call(body, ++position); + + if (code === 43 || code === 45) { + // + - + code = charCodeAt.call(body, ++position); + } + + position = readDigits(source, position, code); + } + + return new Tok(isFloat ? TokenKind.FLOAT : TokenKind.INT, start, position, line, col, prev, slice.call(body, start, position)); +} +/** + * Returns the new position in the source after reading digits. + */ + + +function readDigits(source, start, firstCode) { + var body = source.body; + var position = start; + var code = firstCode; + + if (code >= 48 && code <= 57) { + // 0 - 9 + do { + code = charCodeAt.call(body, ++position); + } while (code >= 48 && code <= 57); // 0 - 9 + + + return position; + } + + throw syntaxError(source, position, "Invalid number, expected digit but got: ".concat(printCharCode(code), ".")); +} +/** + * Reads a string token from the source file. + * + * "([^"\\\u000A\u000D]|(\\(u[0-9a-fA-F]{4}|["\\/bfnrt])))*" + */ + + +function readString(source, start, line, col, prev) { + var body = source.body; + var position = start + 1; + var chunkStart = position; + var code = 0; + var value = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null && // not LineTerminator + code !== 0x000a && code !== 0x000d) { + // Closing Quote (") + if (code === 34) { + value += slice.call(body, chunkStart, position); + return new Tok(TokenKind.STRING, start, position + 1, line, col, prev, value); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009) { + throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } + + ++position; + + if (code === 92) { + // \ + value += slice.call(body, chunkStart, position - 1); + code = charCodeAt.call(body, position); + + switch (code) { + case 34: + value += '"'; + break; + + case 47: + value += '/'; + break; + + case 92: + value += '\\'; + break; + + case 98: + value += '\b'; + break; + + case 102: + value += '\f'; + break; + + case 110: + value += '\n'; + break; + + case 114: + value += '\r'; + break; + + case 116: + value += '\t'; + break; + + case 117: + // u + var charCode = uniCharCode(charCodeAt.call(body, position + 1), charCodeAt.call(body, position + 2), charCodeAt.call(body, position + 3), charCodeAt.call(body, position + 4)); + + if (charCode < 0) { + throw syntaxError(source, position, 'Invalid character escape sequence: ' + "\\u".concat(body.slice(position + 1, position + 5), ".")); + } + + value += String.fromCharCode(charCode); + position += 4; + break; + + default: + throw syntaxError(source, position, "Invalid character escape sequence: \\".concat(String.fromCharCode(code), ".")); + } + + ++position; + chunkStart = position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} +/** + * Reads a block string token from the source file. + * + * """("?"?(\\"""|\\(?!=""")|[^"\\]))*""" + */ + + +function readBlockString(source, start, line, col, prev) { + var body = source.body; + var position = start + 3; + var chunkStart = position; + var code = 0; + var rawValue = ''; + + while (position < body.length && (code = charCodeAt.call(body, position)) !== null) { + // Closing Triple-Quote (""") + if (code === 34 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34) { + rawValue += slice.call(body, chunkStart, position); + return new Tok(TokenKind.BLOCK_STRING, start, position + 3, line, col, prev, blockStringValue(rawValue)); + } // SourceCharacter + + + if (code < 0x0020 && code !== 0x0009 && code !== 0x000a && code !== 0x000d) { + throw syntaxError(source, position, "Invalid character within String: ".concat(printCharCode(code), ".")); + } // Escape Triple-Quote (\""") + + + if (code === 92 && charCodeAt.call(body, position + 1) === 34 && charCodeAt.call(body, position + 2) === 34 && charCodeAt.call(body, position + 3) === 34) { + rawValue += slice.call(body, chunkStart, position) + '"""'; + position += 4; + chunkStart = position; + } else { + ++position; + } + } + + throw syntaxError(source, position, 'Unterminated string.'); +} +/** + * Converts four hexadecimal chars to the integer that the + * string represents. For example, uniCharCode('0','0','0','f') + * will return 15, and uniCharCode('0','0','f','f') returns 255. + * + * Returns a negative number on error, if a char was invalid. + * + * This is implemented by noting that char2hex() returns -1 on error, + * which means the result of ORing the char2hex() will also be negative. + */ + + +function uniCharCode(a, b, c, d) { + return char2hex(a) << 12 | char2hex(b) << 8 | char2hex(c) << 4 | char2hex(d); +} +/** + * Converts a hex character to its integer value. + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 on error. + */ + + +function char2hex(a) { + return a >= 48 && a <= 57 ? a - 48 // 0-9 + : a >= 65 && a <= 70 ? a - 55 // A-F + : a >= 97 && a <= 102 ? a - 87 // a-f + : -1; +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * [_A-Za-z][_0-9A-Za-z]* + */ + + +function readName(source, start, line, col, prev) { + var body = source.body; + var bodyLength = body.length; + var position = start + 1; + var code = 0; + + while (position !== bodyLength && (code = charCodeAt.call(body, position)) !== null && (code === 95 || // _ + code >= 48 && code <= 57 || // 0-9 + code >= 65 && code <= 90 || // A-Z + code >= 97 && code <= 122) // a-z + ) { + ++position; + } + + return new Tok(TokenKind.NAME, start, position, line, col, prev, slice.call(body, start, position)); +} \ No newline at end of file diff --git a/node_modules/graphql/language/location.js b/node_modules/graphql/language/location.js new file mode 100644 index 00000000..1257b2fa --- /dev/null +++ b/node_modules/graphql/language/location.js @@ -0,0 +1,40 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getLocation = getLocation; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +function getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match; + + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + + return { + line: line, + column: column + }; +} \ No newline at end of file diff --git a/node_modules/graphql/language/location.js.flow b/node_modules/graphql/language/location.js.flow new file mode 100644 index 00000000..8029d5b8 --- /dev/null +++ b/node_modules/graphql/language/location.js.flow @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { Source } from './source'; + +/** + * Represents a location in a Source. + */ +export type SourceLocation = {| + +line: number, + +column: number, +|}; + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source: Source, position: number): SourceLocation { + const lineRegexp = /\r\n|[\n\r]/g; + let line = 1; + let column = position + 1; + let match; + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + return { line, column }; +} diff --git a/node_modules/graphql/language/location.mjs b/node_modules/graphql/language/location.mjs new file mode 100644 index 00000000..023d5dcc --- /dev/null +++ b/node_modules/graphql/language/location.mjs @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Represents a location in a Source. + */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + */ +export function getLocation(source, position) { + var lineRegexp = /\r\n|[\n\r]/g; + var line = 1; + var column = position + 1; + var match; + + while ((match = lineRegexp.exec(source.body)) && match.index < position) { + line += 1; + column = position + 1 - (match.index + match[0].length); + } + + return { + line: line, + column: column + }; +} \ No newline at end of file diff --git a/node_modules/graphql/language/parser.js b/node_modules/graphql/language/parser.js new file mode 100644 index 00000000..9cda8d75 --- /dev/null +++ b/node_modules/graphql/language/parser.js @@ -0,0 +1,1527 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parse = parse; +exports.parseValue = parseValue; +exports.parseType = parseType; +exports.parseConstValue = parseConstValue; +exports.parseTypeReference = parseTypeReference; +exports.parseNamedType = parseNamedType; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _source = require("./source"); + +var _error = require("../error"); + +var _lexer = require("./lexer"); + +var _kinds = require("./kinds"); + +var _directiveLocation = require("./directiveLocation"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +function parse(source, options) { + var sourceObj = typeof source === 'string' ? new _source.Source(source) : source; + + if (!(sourceObj instanceof _source.Source)) { + throw new TypeError("Must provide Source. Received: ".concat((0, _inspect.default)(sourceObj))); + } + + var lexer = (0, _lexer.createLexer)(sourceObj, options || {}); + return parseDocument(lexer); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + + +function parseValue(source, options) { + var sourceObj = typeof source === 'string' ? new _source.Source(source) : source; + var lexer = (0, _lexer.createLexer)(sourceObj, options || {}); + expect(lexer, _lexer.TokenKind.SOF); + var value = parseValueLiteral(lexer, false); + expect(lexer, _lexer.TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + + +function parseType(source, options) { + var sourceObj = typeof source === 'string' ? new _source.Source(source) : source; + var lexer = (0, _lexer.createLexer)(sourceObj, options || {}); + expect(lexer, _lexer.TokenKind.SOF); + var type = parseTypeReference(lexer); + expect(lexer, _lexer.TokenKind.EOF); + return type; +} +/** + * Converts a name lex token into a name parse node. + */ + + +function parseName(lexer) { + var token = expect(lexer, _lexer.TokenKind.NAME); + return { + kind: _kinds.Kind.NAME, + value: token.value, + loc: loc(lexer, token) + }; +} // Implements the parsing rules in the Document section. + +/** + * Document : Definition+ + */ + + +function parseDocument(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.DOCUMENT, + definitions: many(lexer, _lexer.TokenKind.SOF, parseDefinition, _lexer.TokenKind.EOF), + loc: loc(lexer, start) + }; +} +/** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + */ + + +function parseDefinition(lexer) { + if (peek(lexer, _lexer.TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + case 'fragment': + return parseExecutableDefinition(lexer); + + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return parseTypeSystemDefinition(lexer); + + case 'extend': + return parseTypeSystemExtension(lexer); + } + } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return parseExecutableDefinition(lexer); + } else if (peekDescription(lexer)) { + return parseTypeSystemDefinition(lexer); + } + + throw unexpected(lexer); +} +/** + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + + +function parseExecutableDefinition(lexer) { + if (peek(lexer, _lexer.TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + } + } else if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + throw unexpected(lexer); +} // Implements the parsing rules in the Operations section. + +/** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + + +function parseOperationDefinition(lexer) { + var start = lexer.token; + + if (peek(lexer, _lexer.TokenKind.BRACE_L)) { + return { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + var operation = parseOperationType(lexer); + var name; + + if (peek(lexer, _lexer.TokenKind.NAME)) { + name = parseName(lexer); + } + + return { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * OperationType : one of query mutation subscription + */ + + +function parseOperationType(lexer) { + var operationToken = expect(lexer, _lexer.TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return 'query'; + + case 'mutation': + return 'mutation'; + + case 'subscription': + return 'subscription'; + } + + throw unexpected(lexer, operationToken); +} +/** + * VariableDefinitions : ( VariableDefinition+ ) + */ + + +function parseVariableDefinitions(lexer) { + return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, parseVariableDefinition, _lexer.TokenKind.PAREN_R) : []; +} +/** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + +function parseVariableDefinition(lexer) { + var start = lexer.token; + + if (lexer.options.experimentalVariableDefinitionDirectives) { + return { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + directives: parseDirectives(lexer, true), + loc: loc(lexer, start) + }; + } + + return { + kind: _kinds.Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, _lexer.TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, _lexer.TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Variable : $ Name + */ + + +function parseVariable(lexer) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.DOLLAR); + return { + kind: _kinds.Kind.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} +/** + * SelectionSet : { Selection+ } + */ + + +function parseSelectionSet(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.SELECTION_SET, + selections: many(lexer, _lexer.TokenKind.BRACE_L, parseSelection, _lexer.TokenKind.BRACE_R), + loc: loc(lexer, start) + }; +} +/** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + +function parseSelection(lexer) { + return peek(lexer, _lexer.TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer); +} +/** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + +function parseField(lexer) { + var start = lexer.token; + var nameOrAlias = parseName(lexer); + var alias; + var name; + + if (skip(lexer, _lexer.TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + name = nameOrAlias; + } + + return { + kind: _kinds.Kind.FIELD, + alias: alias, + name: name, + arguments: parseArguments(lexer, false), + directives: parseDirectives(lexer, false), + selectionSet: peek(lexer, _lexer.TokenKind.BRACE_L) ? parseSelectionSet(lexer) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + +function parseArguments(lexer, isConst) { + var item = isConst ? parseConstArgument : parseArgument; + return peek(lexer, _lexer.TokenKind.PAREN_L) ? many(lexer, _lexer.TokenKind.PAREN_L, item, _lexer.TokenKind.PAREN_R) : []; +} +/** + * Argument[Const] : Name : Value[?Const] + */ + + +function parseArgument(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, false)), + loc: loc(lexer, start) + }; +} + +function parseConstArgument(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseConstValue(lexer)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Fragments section. + +/** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + + +function parseFragment(lexer) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.SPREAD); + + if (peek(lexer, _lexer.TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer, false), + loc: loc(lexer, start) + }; + } + + var typeCondition; + + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + + return { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: typeCondition, + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + +function parseFragmentDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'fragment'); // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (lexer.options.experimentalFragmentVariables) { + return { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + variableDefinitions: parseVariableDefinitions(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + return { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentName : Name but not `on` + */ + + +function parseFragmentName(lexer) { + if (lexer.token.value === 'on') { + throw unexpected(lexer); + } + + return parseName(lexer); +} // Implements the parsing rules in the Values section. + +/** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + + +function parseValueLiteral(lexer, isConst) { + var token = lexer.token; + + switch (token.kind) { + case _lexer.TokenKind.BRACKET_L: + return parseList(lexer, isConst); + + case _lexer.TokenKind.BRACE_L: + return parseObject(lexer, isConst); + + case _lexer.TokenKind.INT: + lexer.advance(); + return { + kind: _kinds.Kind.INT, + value: token.value, + loc: loc(lexer, token) + }; + + case _lexer.TokenKind.FLOAT: + lexer.advance(); + return { + kind: _kinds.Kind.FLOAT, + value: token.value, + loc: loc(lexer, token) + }; + + case _lexer.TokenKind.STRING: + case _lexer.TokenKind.BLOCK_STRING: + return parseStringLiteral(lexer); + + case _lexer.TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: _kinds.Kind.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token) + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: _kinds.Kind.NULL, + loc: loc(lexer, token) + }; + } + + lexer.advance(); + return { + kind: _kinds.Kind.ENUM, + value: token.value, + loc: loc(lexer, token) + }; + + case _lexer.TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + + break; + } + + throw unexpected(lexer); +} + +function parseStringLiteral(lexer) { + var token = lexer.token; + lexer.advance(); + return { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _lexer.TokenKind.BLOCK_STRING, + loc: loc(lexer, token) + }; +} + +function parseConstValue(lexer) { + return parseValueLiteral(lexer, true); +} + +function parseValueValue(lexer) { + return parseValueLiteral(lexer, false); +} +/** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + + +function parseList(lexer, isConst) { + var start = lexer.token; + var item = isConst ? parseConstValue : parseValueValue; + return { + kind: _kinds.Kind.LIST, + values: any(lexer, _lexer.TokenKind.BRACKET_L, item, _lexer.TokenKind.BRACKET_R), + loc: loc(lexer, start) + }; +} +/** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + + +function parseObject(lexer, isConst) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.BRACE_L); + var fields = []; + + while (!skip(lexer, _lexer.TokenKind.BRACE_R)) { + fields.push(parseObjectField(lexer, isConst)); + } + + return { + kind: _kinds.Kind.OBJECT, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ObjectField[Const] : Name : Value[?Const] + */ + + +function parseObjectField(lexer, isConst) { + var start = lexer.token; + return { + kind: _kinds.Kind.OBJECT_FIELD, + name: parseName(lexer), + value: (expect(lexer, _lexer.TokenKind.COLON), parseValueLiteral(lexer, isConst)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Directives section. + +/** + * Directives[Const] : Directive[?Const]+ + */ + + +function parseDirectives(lexer, isConst) { + var directives = []; + + while (peek(lexer, _lexer.TokenKind.AT)) { + directives.push(parseDirective(lexer, isConst)); + } + + return directives; +} +/** + * Directive[Const] : @ Name Arguments[?Const]? + */ + + +function parseDirective(lexer, isConst) { + var start = lexer.token; + expect(lexer, _lexer.TokenKind.AT); + return { + kind: _kinds.Kind.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer, isConst), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Types section. + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + + +function parseTypeReference(lexer) { + var start = lexer.token; + var type; + + if (skip(lexer, _lexer.TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, _lexer.TokenKind.BRACKET_R); + type = { + kind: _kinds.Kind.LIST_TYPE, + type: type, + loc: loc(lexer, start) + }; + } else { + type = parseNamedType(lexer); + } + + if (skip(lexer, _lexer.TokenKind.BANG)) { + return { + kind: _kinds.Kind.NON_NULL_TYPE, + type: type, + loc: loc(lexer, start) + }; + } + + return type; +} +/** + * NamedType : Name + */ + + +function parseNamedType(lexer) { + var start = lexer.token; + return { + kind: _kinds.Kind.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + + +function parseTypeSystemDefinition(lexer) { + // Many definitions begin with a description and require a lookahead. + var keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token; + + if (keywordToken.kind === _lexer.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaDefinition(lexer); + + case 'scalar': + return parseScalarTypeDefinition(lexer); + + case 'type': + return parseObjectTypeDefinition(lexer); + + case 'interface': + return parseInterfaceTypeDefinition(lexer); + + case 'union': + return parseUnionTypeDefinition(lexer); + + case 'enum': + return parseEnumTypeDefinition(lexer); + + case 'input': + return parseInputObjectTypeDefinition(lexer); + + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +function peekDescription(lexer) { + return peek(lexer, _lexer.TokenKind.STRING) || peek(lexer, _lexer.TokenKind.BLOCK_STRING); +} +/** + * Description : StringValue + */ + + +function parseDescription(lexer) { + if (peekDescription(lexer)) { + return parseStringLiteral(lexer); + } +} +/** + * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ } + */ + + +function parseSchemaDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R); + return { + kind: _kinds.Kind.SCHEMA_DEFINITION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * OperationTypeDefinition : OperationType : NamedType + */ + + +function parseOperationTypeDefinition(lexer) { + var start = lexer.token; + var operation = parseOperationType(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseNamedType(lexer); + return { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + + +function parseScalarTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + + +function parseObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + + +function parseImplementsInterfaces(lexer) { + var types = []; + + if (lexer.token.value === 'implements') { + lexer.advance(); // Optional leading ampersand + + skip(lexer, _lexer.TokenKind.AMP); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, _lexer.TokenKind.AMP) || // Legacy support for the SDL? + lexer.options.allowLegacySDLImplementsInterfaces && peek(lexer, _lexer.TokenKind.NAME)); + } + + return types; +} +/** + * FieldsDefinition : { FieldDefinition+ } + */ + + +function parseFieldsDefinition(lexer) { + // Legacy support for the SDL? + if (lexer.options.allowLegacySDLEmptyFields && peek(lexer, _lexer.TokenKind.BRACE_L) && lexer.lookahead().kind === _lexer.TokenKind.BRACE_R) { + lexer.advance(); + lexer.advance(); + return []; + } + + return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseFieldDefinition, _lexer.TokenKind.BRACE_R) : []; +} +/** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + + +function parseFieldDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseTypeReference(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.FIELD_DEFINITION, + description: description, + name: name, + arguments: args, + type: type, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + + +function parseArgumentDefs(lexer) { + if (!peek(lexer, _lexer.TokenKind.PAREN_L)) { + return []; + } + + return many(lexer, _lexer.TokenKind.PAREN_L, parseInputValueDef, _lexer.TokenKind.PAREN_R); +} +/** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + + +function parseInputValueDef(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + expect(lexer, _lexer.TokenKind.COLON); + var type = parseTypeReference(lexer); + var defaultValue; + + if (skip(lexer, _lexer.TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description: description, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + + +function parseInterfaceTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + + +function parseUnionTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + return { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + + +function parseUnionMemberTypes(lexer) { + var types = []; + + if (skip(lexer, _lexer.TokenKind.EQUALS)) { + // Optional leading pipe + skip(lexer, _lexer.TokenKind.PIPE); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, _lexer.TokenKind.PIPE)); + } + + return types; +} +/** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + + +function parseEnumTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + return { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + + +function parseEnumValuesDefinition(lexer) { + return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseEnumValueDefinition, _lexer.TokenKind.BRACE_R) : []; +} +/** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + + +function parseEnumValueDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + + +function parseInputObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + return { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + + +function parseInputFieldsDefinition(lexer) { + return peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseInputValueDef, _lexer.TokenKind.BRACE_R) : []; +} +/** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + + +function parseTypeSystemExtension(lexer) { + var keywordToken = lexer.lookahead(); + + if (keywordToken.kind === _lexer.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaExtension(lexer); + + case 'scalar': + return parseScalarTypeExtension(lexer); + + case 'type': + return parseObjectTypeExtension(lexer); + + case 'interface': + return parseInterfaceTypeExtension(lexer); + + case 'union': + return parseUnionTypeExtension(lexer); + + case 'enum': + return parseEnumTypeExtension(lexer); + + case 'input': + return parseInputObjectTypeExtension(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} +/** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + + +function parseSchemaExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = peek(lexer, _lexer.TokenKind.BRACE_L) ? many(lexer, _lexer.TokenKind.BRACE_L, parseOperationTypeDefinition, _lexer.TokenKind.BRACE_R) : []; + + if (directives.length === 0 && operationTypes.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + + +function parseScalarTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + + if (directives.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + + +function parseObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeExtension : + * - extend interface Name Directives[Const]? FieldsDefinition + * - extend interface Name Directives[Const] + */ + + +function parseInterfaceTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + + +function parseUnionTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + + if (directives.length === 0 && types.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + + +function parseEnumTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + + if (directives.length === 0 && values.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + + +function parseInputObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations + */ + + +function parseDirectiveDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'directive'); + expect(lexer, _lexer.TokenKind.AT); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expectKeyword(lexer, 'on'); + var locations = parseDirectiveLocations(lexer); + return { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description: description, + name: name, + arguments: args, + locations: locations, + loc: loc(lexer, start) + }; +} +/** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + + +function parseDirectiveLocations(lexer) { + // Optional leading pipe + skip(lexer, _lexer.TokenKind.PIPE); + var locations = []; + + do { + locations.push(parseDirectiveLocation(lexer)); + } while (skip(lexer, _lexer.TokenKind.PIPE)); + + return locations; +} +/* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + + +function parseDirectiveLocation(lexer) { + var start = lexer.token; + var name = parseName(lexer); + + if (_directiveLocation.DirectiveLocation.hasOwnProperty(name.value)) { + return name; + } + + throw unexpected(lexer, start); +} // Core parsing utility functions + +/** + * Returns a location object, used to identify the place in + * the source that created a given parsed object. + */ + + +function loc(lexer, startToken) { + if (!lexer.options.noLocation) { + return new Loc(startToken, lexer.lastToken, lexer.source); + } +} + +function Loc(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + return { + start: this.start, + end: this.end + }; +}; +/** + * Determines if the next token is of a given kind + */ + + +function peek(lexer, kind) { + return lexer.token.kind === kind; +} +/** + * If the next token is of the given kind, return true after advancing + * the lexer. Otherwise, do not change the parser state and return false. + */ + + +function skip(lexer, kind) { + var match = lexer.token.kind === kind; + + if (match) { + lexer.advance(); + } + + return match; +} +/** + * If the next token is of the given kind, return that token after advancing + * the lexer. Otherwise, do not change the parser state and throw an error. + */ + + +function expect(lexer, kind) { + var token = lexer.token; + + if (token.kind === kind) { + lexer.advance(); + return token; + } + + throw (0, _error.syntaxError)(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat((0, _lexer.getTokenDesc)(token))); +} +/** + * If the next token is a keyword with the given value, return that token after + * advancing the lexer. Otherwise, do not change the parser state and return + * false. + */ + + +function expectKeyword(lexer, value) { + var token = lexer.token; + + if (token.kind === _lexer.TokenKind.NAME && token.value === value) { + lexer.advance(); + return token; + } + + throw (0, _error.syntaxError)(lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat((0, _lexer.getTokenDesc)(token))); +} +/** + * Helper function for creating an error when an unexpected lexed token + * is encountered. + */ + + +function unexpected(lexer, atToken) { + var token = atToken || lexer.token; + return (0, _error.syntaxError)(lexer.source, token.start, "Unexpected ".concat((0, _lexer.getTokenDesc)(token))); +} +/** + * Returns a possibly empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function any(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = []; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} +/** + * Returns a non-empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function many(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = [parseFn(lexer)]; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} \ No newline at end of file diff --git a/node_modules/graphql/language/parser.js.flow b/node_modules/graphql/language/parser.js.flow new file mode 100644 index 00000000..37ba2e1f --- /dev/null +++ b/node_modules/graphql/language/parser.js.flow @@ -0,0 +1,1583 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import { Source } from './source'; +import { syntaxError } from '../error'; +import type { GraphQLError } from '../error'; +import { createLexer, TokenKind, getTokenDesc } from './lexer'; +import type { Lexer, TokenKindEnum } from './lexer'; +import type { + Location, + Token, + NameNode, + VariableNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + OperationTypeNode, + VariableDefinitionNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + StringValueNode, + ListValueNode, + ObjectValueNode, + ObjectFieldNode, + DirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, +} from './ast'; + +import { Kind } from './kinds'; +import { DirectiveLocation } from './directiveLocation'; + +/** + * Configuration options to control parser behavior + */ +export type ParseOptions = { + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean, + + /** + * If enabled, the parser will parse empty fields sets in the Schema + * Definition Language. Otherwise, the parser will follow the current + * specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLEmptyFields?: boolean, + + /** + * If enabled, the parser will parse implemented interfaces with no `&` + * character between each interface. Otherwise, the parser will follow the + * current specification. + * + * This option is provided to ease adoption of the final SDL specification + * and will be removed in v16. + */ + allowLegacySDLImplementsInterfaces?: boolean, + + /** + * EXPERIMENTAL: + * + * If enabled, the parser will understand and parse variable definitions + * contained in a fragment definition. They'll be represented in the + * `variableDefinitions` field of the FragmentDefinitionNode. + * + * The syntax is identical to normal, query-defined variables. For example: + * + * fragment A($var: Boolean = false) on T { + * ... + * } + * + * Note: this feature is experimental and may change or be removed in the + * future. + */ + experimentalFragmentVariables?: boolean, + + /** + * EXPERIMENTAL: + * + * If enabled, the parser understands directives on variable definitions: + * + * query Foo($var: String = "abc" @variable_definition_directive) { + * ... + * } + */ + experimentalVariableDefinitionDirectives?: boolean, +}; + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse( + source: string | Source, + options?: ParseOptions, +): DocumentNode { + const sourceObj = typeof source === 'string' ? new Source(source) : source; + if (!(sourceObj instanceof Source)) { + throw new TypeError(`Must provide Source. Received: ${inspect(sourceObj)}`); + } + const lexer = createLexer(sourceObj, options || {}); + return parseDocument(lexer); +} + +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ +export function parseValue( + source: string | Source, + options?: ParseOptions, +): ValueNode { + const sourceObj = typeof source === 'string' ? new Source(source) : source; + const lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + const value = parseValueLiteral(lexer, false); + expect(lexer, TokenKind.EOF); + return value; +} + +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ +export function parseType( + source: string | Source, + options?: ParseOptions, +): TypeNode { + const sourceObj = typeof source === 'string' ? new Source(source) : source; + const lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + const type = parseTypeReference(lexer); + expect(lexer, TokenKind.EOF); + return type; +} + +/** + * Converts a name lex token into a name parse node. + */ +function parseName(lexer: Lexer<*>): NameNode { + const token = expect(lexer, TokenKind.NAME); + return { + kind: Kind.NAME, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; +} + +// Implements the parsing rules in the Document section. + +/** + * Document : Definition+ + */ +function parseDocument(lexer: Lexer<*>): DocumentNode { + const start = lexer.token; + return { + kind: Kind.DOCUMENT, + definitions: many(lexer, TokenKind.SOF, parseDefinition, TokenKind.EOF), + loc: loc(lexer, start), + }; +} + +/** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + */ +function parseDefinition(lexer: Lexer<*>): DefinitionNode { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + case 'fragment': + return parseExecutableDefinition(lexer); + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return parseTypeSystemDefinition(lexer); + case 'extend': + return parseTypeSystemExtension(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseExecutableDefinition(lexer); + } else if (peekDescription(lexer)) { + return parseTypeSystemDefinition(lexer); + } + + throw unexpected(lexer); +} + +/** + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ +function parseExecutableDefinition(lexer: Lexer<*>): ExecutableDefinitionNode { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + throw unexpected(lexer); +} + +// Implements the parsing rules in the Operations section. + +/** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ +function parseOperationDefinition(lexer: Lexer<*>): OperationDefinitionNode { + const start = lexer.token; + if (peek(lexer, TokenKind.BRACE_L)) { + return { + kind: Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; + } + const operation = parseOperationType(lexer); + let name; + if (peek(lexer, TokenKind.NAME)) { + name = parseName(lexer); + } + return { + kind: Kind.OPERATION_DEFINITION, + operation, + name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; +} + +/** + * OperationType : one of query mutation subscription + */ +function parseOperationType(lexer: Lexer<*>): OperationTypeNode { + const operationToken = expect(lexer, TokenKind.NAME); + switch (operationToken.value) { + case 'query': + return 'query'; + case 'mutation': + return 'mutation'; + case 'subscription': + return 'subscription'; + } + + throw unexpected(lexer, operationToken); +} + +/** + * VariableDefinitions : ( VariableDefinition+ ) + */ +function parseVariableDefinitions( + lexer: Lexer<*>, +): Array { + return peek(lexer, TokenKind.PAREN_L) + ? many(lexer, TokenKind.PAREN_L, parseVariableDefinition, TokenKind.PAREN_R) + : []; +} + +/** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ +function parseVariableDefinition(lexer: Lexer<*>): VariableDefinitionNode { + const start = lexer.token; + if (lexer.options.experimentalVariableDefinitionDirectives) { + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) + ? parseValueLiteral(lexer, true) + : undefined, + directives: parseDirectives(lexer, true), + loc: loc(lexer, start), + }; + } + + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) + ? parseValueLiteral(lexer, true) + : undefined, + loc: loc(lexer, start), + }; +} + +/** + * Variable : $ Name + */ +function parseVariable(lexer: Lexer<*>): VariableNode { + const start = lexer.token; + expect(lexer, TokenKind.DOLLAR); + return { + kind: Kind.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start), + }; +} + +/** + * SelectionSet : { Selection+ } + */ +function parseSelectionSet(lexer: Lexer<*>): SelectionSetNode { + const start = lexer.token; + return { + kind: Kind.SELECTION_SET, + selections: many( + lexer, + TokenKind.BRACE_L, + parseSelection, + TokenKind.BRACE_R, + ), + loc: loc(lexer, start), + }; +} + +/** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ +function parseSelection(lexer: Lexer<*>): SelectionNode { + return peek(lexer, TokenKind.SPREAD) + ? parseFragment(lexer) + : parseField(lexer); +} + +/** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ +function parseField(lexer: Lexer<*>): FieldNode { + const start = lexer.token; + + const nameOrAlias = parseName(lexer); + let alias; + let name; + if (skip(lexer, TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + name = nameOrAlias; + } + + return { + kind: Kind.FIELD, + alias, + name, + arguments: parseArguments(lexer, false), + directives: parseDirectives(lexer, false), + selectionSet: peek(lexer, TokenKind.BRACE_L) + ? parseSelectionSet(lexer) + : undefined, + loc: loc(lexer, start), + }; +} + +/** + * Arguments[Const] : ( Argument[?Const]+ ) + */ +function parseArguments( + lexer: Lexer<*>, + isConst: boolean, +): Array { + const item = isConst ? parseConstArgument : parseArgument; + return peek(lexer, TokenKind.PAREN_L) + ? many(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R) + : []; +} + +/** + * Argument[Const] : Name : Value[?Const] + */ +function parseArgument(lexer: Lexer<*>): ArgumentNode { + const start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, false)), + loc: loc(lexer, start), + }; +} + +function parseConstArgument(lexer: Lexer<*>): ArgumentNode { + const start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseConstValue(lexer)), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Fragments section. + +/** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ +function parseFragment( + lexer: Lexer<*>, +): FragmentSpreadNode | InlineFragmentNode { + const start = lexer.token; + expect(lexer, TokenKind.SPREAD); + if (peek(lexer, TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: Kind.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer, false), + loc: loc(lexer, start), + }; + } + let typeCondition; + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + return { + kind: Kind.INLINE_FRAGMENT, + typeCondition, + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; +} + +/** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ +function parseFragmentDefinition(lexer: Lexer<*>): FragmentDefinitionNode { + const start = lexer.token; + expectKeyword(lexer, 'fragment'); + // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + if (lexer.options.experimentalFragmentVariables) { + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + variableDefinitions: parseVariableDefinitions(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; + } + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start), + }; +} + +/** + * FragmentName : Name but not `on` + */ +function parseFragmentName(lexer: Lexer<*>): NameNode { + if (lexer.token.value === 'on') { + throw unexpected(lexer); + } + return parseName(lexer); +} + +// Implements the parsing rules in the Values section. + +/** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ +function parseValueLiteral(lexer: Lexer<*>, isConst: boolean): ValueNode { + const token = lexer.token; + switch (token.kind) { + case TokenKind.BRACKET_L: + return parseList(lexer, isConst); + case TokenKind.BRACE_L: + return parseObject(lexer, isConst); + case TokenKind.INT: + lexer.advance(); + return { + kind: Kind.INT, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; + case TokenKind.FLOAT: + lexer.advance(); + return { + kind: Kind.FLOAT, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return parseStringLiteral(lexer); + case TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: Kind.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token), + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: Kind.NULL, + loc: loc(lexer, token), + }; + } + lexer.advance(); + return { + kind: Kind.ENUM, + value: ((token.value: any): string), + loc: loc(lexer, token), + }; + case TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + break; + } + throw unexpected(lexer); +} + +function parseStringLiteral(lexer: Lexer<*>): StringValueNode { + const token = lexer.token; + lexer.advance(); + return { + kind: Kind.STRING, + value: ((token.value: any): string), + block: token.kind === TokenKind.BLOCK_STRING, + loc: loc(lexer, token), + }; +} + +export function parseConstValue(lexer: Lexer<*>): ValueNode { + return parseValueLiteral(lexer, true); +} + +function parseValueValue(lexer: Lexer<*>): ValueNode { + return parseValueLiteral(lexer, false); +} + +/** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ +function parseList(lexer: Lexer<*>, isConst: boolean): ListValueNode { + const start = lexer.token; + const item = isConst ? parseConstValue : parseValueValue; + return { + kind: Kind.LIST, + values: any(lexer, TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + loc: loc(lexer, start), + }; +} + +/** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ +function parseObject(lexer: Lexer<*>, isConst: boolean): ObjectValueNode { + const start = lexer.token; + expect(lexer, TokenKind.BRACE_L); + const fields = []; + while (!skip(lexer, TokenKind.BRACE_R)) { + fields.push(parseObjectField(lexer, isConst)); + } + return { + kind: Kind.OBJECT, + fields, + loc: loc(lexer, start), + }; +} + +/** + * ObjectField[Const] : Name : Value[?Const] + */ +function parseObjectField(lexer: Lexer<*>, isConst: boolean): ObjectFieldNode { + const start = lexer.token; + return { + kind: Kind.OBJECT_FIELD, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, isConst)), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Directives section. + +/** + * Directives[Const] : Directive[?Const]+ + */ +function parseDirectives( + lexer: Lexer<*>, + isConst: boolean, +): Array { + const directives = []; + while (peek(lexer, TokenKind.AT)) { + directives.push(parseDirective(lexer, isConst)); + } + return directives; +} + +/** + * Directive[Const] : @ Name Arguments[?Const]? + */ +function parseDirective(lexer: Lexer<*>, isConst: boolean): DirectiveNode { + const start = lexer.token; + expect(lexer, TokenKind.AT); + return { + kind: Kind.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer, isConst), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Types section. + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ +export function parseTypeReference(lexer: Lexer<*>): TypeNode { + const start = lexer.token; + let type; + if (skip(lexer, TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, TokenKind.BRACKET_R); + type = ({ + kind: Kind.LIST_TYPE, + type, + loc: loc(lexer, start), + }: ListTypeNode); + } else { + type = parseNamedType(lexer); + } + if (skip(lexer, TokenKind.BANG)) { + return ({ + kind: Kind.NON_NULL_TYPE, + type, + loc: loc(lexer, start), + }: NonNullTypeNode); + } + return type; +} + +/** + * NamedType : Name + */ +export function parseNamedType(lexer: Lexer<*>): NamedTypeNode { + const start = lexer.token; + return { + kind: Kind.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start), + }; +} + +// Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ +function parseTypeSystemDefinition(lexer: Lexer<*>): TypeSystemDefinitionNode { + // Many definitions begin with a description and require a lookahead. + const keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token; + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaDefinition(lexer); + case 'scalar': + return parseScalarTypeDefinition(lexer); + case 'type': + return parseObjectTypeDefinition(lexer); + case 'interface': + return parseInterfaceTypeDefinition(lexer); + case 'union': + return parseUnionTypeDefinition(lexer); + case 'enum': + return parseEnumTypeDefinition(lexer); + case 'input': + return parseInputObjectTypeDefinition(lexer); + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +function peekDescription(lexer: Lexer<*>): boolean { + return peek(lexer, TokenKind.STRING) || peek(lexer, TokenKind.BLOCK_STRING); +} + +/** + * Description : StringValue + */ +function parseDescription(lexer: Lexer<*>): void | StringValueNode { + if (peekDescription(lexer)) { + return parseStringLiteral(lexer); + } +} + +/** + * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ } + */ +function parseSchemaDefinition(lexer: Lexer<*>): SchemaDefinitionNode { + const start = lexer.token; + expectKeyword(lexer, 'schema'); + const directives = parseDirectives(lexer, true); + const operationTypes = many( + lexer, + TokenKind.BRACE_L, + parseOperationTypeDefinition, + TokenKind.BRACE_R, + ); + return { + kind: Kind.SCHEMA_DEFINITION, + directives, + operationTypes, + loc: loc(lexer, start), + }; +} + +/** + * OperationTypeDefinition : OperationType : NamedType + */ +function parseOperationTypeDefinition( + lexer: Lexer<*>, +): OperationTypeDefinitionNode { + const start = lexer.token; + const operation = parseOperationType(lexer); + expect(lexer, TokenKind.COLON); + const type = parseNamedType(lexer); + return { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + loc: loc(lexer, start), + }; +} + +/** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ +function parseScalarTypeDefinition(lexer: Lexer<*>): ScalarTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'scalar'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + return { + kind: Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + loc: loc(lexer, start), + }; +} + +/** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ +function parseObjectTypeDefinition(lexer: Lexer<*>): ObjectTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'type'); + const name = parseName(lexer); + const interfaces = parseImplementsInterfaces(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + return { + kind: Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ +function parseImplementsInterfaces(lexer: Lexer<*>): Array { + const types = []; + if (lexer.token.value === 'implements') { + lexer.advance(); + // Optional leading ampersand + skip(lexer, TokenKind.AMP); + do { + types.push(parseNamedType(lexer)); + } while ( + skip(lexer, TokenKind.AMP) || + // Legacy support for the SDL? + (lexer.options.allowLegacySDLImplementsInterfaces && + peek(lexer, TokenKind.NAME)) + ); + } + return types; +} + +/** + * FieldsDefinition : { FieldDefinition+ } + */ +function parseFieldsDefinition(lexer: Lexer<*>): Array { + // Legacy support for the SDL? + if ( + lexer.options.allowLegacySDLEmptyFields && + peek(lexer, TokenKind.BRACE_L) && + lexer.lookahead().kind === TokenKind.BRACE_R + ) { + lexer.advance(); + lexer.advance(); + return []; + } + return peek(lexer, TokenKind.BRACE_L) + ? many(lexer, TokenKind.BRACE_L, parseFieldDefinition, TokenKind.BRACE_R) + : []; +} + +/** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ +function parseFieldDefinition(lexer: Lexer<*>): FieldDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + const name = parseName(lexer); + const args = parseArgumentDefs(lexer); + expect(lexer, TokenKind.COLON); + const type = parseTypeReference(lexer); + const directives = parseDirectives(lexer, true); + return { + kind: Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + loc: loc(lexer, start), + }; +} + +/** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ +function parseArgumentDefs(lexer: Lexer<*>): Array { + if (!peek(lexer, TokenKind.PAREN_L)) { + return []; + } + return many(lexer, TokenKind.PAREN_L, parseInputValueDef, TokenKind.PAREN_R); +} + +/** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ +function parseInputValueDef(lexer: Lexer<*>): InputValueDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + const name = parseName(lexer); + expect(lexer, TokenKind.COLON); + const type = parseTypeReference(lexer); + let defaultValue; + if (skip(lexer, TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + const directives = parseDirectives(lexer, true); + return { + kind: Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + loc: loc(lexer, start), + }; +} + +/** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ +function parseInterfaceTypeDefinition( + lexer: Lexer<*>, +): InterfaceTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'interface'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + return { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ +function parseUnionTypeDefinition(lexer: Lexer<*>): UnionTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'union'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const types = parseUnionMemberTypes(lexer); + return { + kind: Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + loc: loc(lexer, start), + }; +} + +/** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ +function parseUnionMemberTypes(lexer: Lexer<*>): Array { + const types = []; + if (skip(lexer, TokenKind.EQUALS)) { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + } + return types; +} + +/** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ +function parseEnumTypeDefinition(lexer: Lexer<*>): EnumTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'enum'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const values = parseEnumValuesDefinition(lexer); + return { + kind: Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + loc: loc(lexer, start), + }; +} + +/** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ +function parseEnumValuesDefinition( + lexer: Lexer<*>, +): Array { + return peek(lexer, TokenKind.BRACE_L) + ? many( + lexer, + TokenKind.BRACE_L, + parseEnumValueDefinition, + TokenKind.BRACE_R, + ) + : []; +} + +/** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ +function parseEnumValueDefinition(lexer: Lexer<*>): EnumValueDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + return { + kind: Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + loc: loc(lexer, start), + }; +} + +/** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ +function parseInputObjectTypeDefinition( + lexer: Lexer<*>, +): InputObjectTypeDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'input'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseInputFieldsDefinition(lexer); + return { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * InputFieldsDefinition : { InputValueDefinition+ } + */ +function parseInputFieldsDefinition( + lexer: Lexer<*>, +): Array { + return peek(lexer, TokenKind.BRACE_L) + ? many(lexer, TokenKind.BRACE_L, parseInputValueDef, TokenKind.BRACE_R) + : []; +} + +/** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ +function parseTypeSystemExtension(lexer: Lexer<*>): TypeSystemExtensionNode { + const keywordToken = lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaExtension(lexer); + case 'scalar': + return parseScalarTypeExtension(lexer); + case 'type': + return parseObjectTypeExtension(lexer); + case 'interface': + return parseInterfaceTypeExtension(lexer); + case 'union': + return parseUnionTypeExtension(lexer); + case 'enum': + return parseEnumTypeExtension(lexer); + case 'input': + return parseInputObjectTypeExtension(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +/** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ +function parseSchemaExtension(lexer: Lexer<*>): SchemaExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'schema'); + const directives = parseDirectives(lexer, true); + const operationTypes = peek(lexer, TokenKind.BRACE_L) + ? many( + lexer, + TokenKind.BRACE_L, + parseOperationTypeDefinition, + TokenKind.BRACE_R, + ) + : []; + if (directives.length === 0 && operationTypes.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + loc: loc(lexer, start), + }; +} + +/** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ +function parseScalarTypeExtension(lexer: Lexer<*>): ScalarTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'scalar'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + if (directives.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + loc: loc(lexer, start), + }; +} + +/** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ +function parseObjectTypeExtension(lexer: Lexer<*>): ObjectTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'type'); + const name = parseName(lexer); + const interfaces = parseImplementsInterfaces(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw unexpected(lexer); + } + return { + kind: Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * InterfaceTypeExtension : + * - extend interface Name Directives[Const]? FieldsDefinition + * - extend interface Name Directives[Const] + */ +function parseInterfaceTypeExtension( + lexer: Lexer<*>, +): InterfaceTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'interface'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseFieldsDefinition(lexer); + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ +function parseUnionTypeExtension(lexer: Lexer<*>): UnionTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'union'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const types = parseUnionMemberTypes(lexer); + if (directives.length === 0 && types.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + loc: loc(lexer, start), + }; +} + +/** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ +function parseEnumTypeExtension(lexer: Lexer<*>): EnumTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'enum'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const values = parseEnumValuesDefinition(lexer); + if (directives.length === 0 && values.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + loc: loc(lexer, start), + }; +} + +/** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ +function parseInputObjectTypeExtension( + lexer: Lexer<*>, +): InputObjectTypeExtensionNode { + const start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'input'); + const name = parseName(lexer); + const directives = parseDirectives(lexer, true); + const fields = parseInputFieldsDefinition(lexer); + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + return { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + loc: loc(lexer, start), + }; +} + +/** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations + */ +function parseDirectiveDefinition(lexer: Lexer<*>): DirectiveDefinitionNode { + const start = lexer.token; + const description = parseDescription(lexer); + expectKeyword(lexer, 'directive'); + expect(lexer, TokenKind.AT); + const name = parseName(lexer); + const args = parseArgumentDefs(lexer); + expectKeyword(lexer, 'on'); + const locations = parseDirectiveLocations(lexer); + return { + kind: Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + locations, + loc: loc(lexer, start), + }; +} + +/** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ +function parseDirectiveLocations(lexer: Lexer<*>): Array { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + const locations = []; + do { + locations.push(parseDirectiveLocation(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + return locations; +} + +/* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ +function parseDirectiveLocation(lexer: Lexer<*>): NameNode { + const start = lexer.token; + const name = parseName(lexer); + if (DirectiveLocation.hasOwnProperty(name.value)) { + return name; + } + throw unexpected(lexer, start); +} + +// Core parsing utility functions + +/** + * Returns a location object, used to identify the place in + * the source that created a given parsed object. + */ +function loc(lexer: Lexer<*>, startToken: Token): Location | void { + if (!lexer.options.noLocation) { + return new Loc(startToken, lexer.lastToken, lexer.source); + } +} + +function Loc(startToken: Token, endToken: Token, source: Source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; +} + +// Print a simplified form when appearing in JSON/util.inspect. +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + return { start: this.start, end: this.end }; +}; + +/** + * Determines if the next token is of a given kind + */ +function peek(lexer: Lexer<*>, kind: TokenKindEnum): boolean { + return lexer.token.kind === kind; +} + +/** + * If the next token is of the given kind, return true after advancing + * the lexer. Otherwise, do not change the parser state and return false. + */ +function skip(lexer: Lexer<*>, kind: TokenKindEnum): boolean { + const match = lexer.token.kind === kind; + if (match) { + lexer.advance(); + } + return match; +} + +/** + * If the next token is of the given kind, return that token after advancing + * the lexer. Otherwise, do not change the parser state and throw an error. + */ +function expect(lexer: Lexer<*>, kind: TokenKindEnum): Token { + const token = lexer.token; + if (token.kind === kind) { + lexer.advance(); + return token; + } + throw syntaxError( + lexer.source, + token.start, + `Expected ${kind}, found ${getTokenDesc(token)}`, + ); +} + +/** + * If the next token is a keyword with the given value, return that token after + * advancing the lexer. Otherwise, do not change the parser state and return + * false. + */ +function expectKeyword(lexer: Lexer<*>, value: string): Token { + const token = lexer.token; + if (token.kind === TokenKind.NAME && token.value === value) { + lexer.advance(); + return token; + } + throw syntaxError( + lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}`, + ); +} + +/** + * Helper function for creating an error when an unexpected lexed token + * is encountered. + */ +function unexpected(lexer: Lexer<*>, atToken?: ?Token): GraphQLError { + const token = atToken || lexer.token; + return syntaxError( + lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}`, + ); +} + +/** + * Returns a possibly empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ +function any( + lexer: Lexer<*>, + openKind: TokenKindEnum, + parseFn: (lexer: Lexer<*>) => T, + closeKind: TokenKindEnum, +): Array { + expect(lexer, openKind); + const nodes = []; + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + return nodes; +} + +/** + * Returns a non-empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ +function many( + lexer: Lexer<*>, + openKind: TokenKindEnum, + parseFn: (lexer: Lexer<*>) => T, + closeKind: TokenKindEnum, +): Array { + expect(lexer, openKind); + const nodes = [parseFn(lexer)]; + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + return nodes; +} diff --git a/node_modules/graphql/language/parser.mjs b/node_modules/graphql/language/parser.mjs new file mode 100644 index 00000000..ed071155 --- /dev/null +++ b/node_modules/graphql/language/parser.mjs @@ -0,0 +1,1505 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +import { Source } from './source'; +import { syntaxError } from '../error'; +import { createLexer, TokenKind, getTokenDesc } from './lexer'; +import { Kind } from './kinds'; +import { DirectiveLocation } from './directiveLocation'; +/** + * Configuration options to control parser behavior + */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + */ +export function parse(source, options) { + var sourceObj = typeof source === 'string' ? new Source(source) : source; + + if (!(sourceObj instanceof Source)) { + throw new TypeError("Must provide Source. Received: ".concat(inspect(sourceObj))); + } + + var lexer = createLexer(sourceObj, options || {}); + return parseDocument(lexer); +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + */ + +export function parseValue(source, options) { + var sourceObj = typeof source === 'string' ? new Source(source) : source; + var lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + var value = parseValueLiteral(lexer, false); + expect(lexer, TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + */ + +export function parseType(source, options) { + var sourceObj = typeof source === 'string' ? new Source(source) : source; + var lexer = createLexer(sourceObj, options || {}); + expect(lexer, TokenKind.SOF); + var type = parseTypeReference(lexer); + expect(lexer, TokenKind.EOF); + return type; +} +/** + * Converts a name lex token into a name parse node. + */ + +function parseName(lexer) { + var token = expect(lexer, TokenKind.NAME); + return { + kind: Kind.NAME, + value: token.value, + loc: loc(lexer, token) + }; +} // Implements the parsing rules in the Document section. + +/** + * Document : Definition+ + */ + + +function parseDocument(lexer) { + var start = lexer.token; + return { + kind: Kind.DOCUMENT, + definitions: many(lexer, TokenKind.SOF, parseDefinition, TokenKind.EOF), + loc: loc(lexer, start) + }; +} +/** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + */ + + +function parseDefinition(lexer) { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + case 'fragment': + return parseExecutableDefinition(lexer); + + case 'schema': + case 'scalar': + case 'type': + case 'interface': + case 'union': + case 'enum': + case 'input': + case 'directive': + return parseTypeSystemDefinition(lexer); + + case 'extend': + return parseTypeSystemExtension(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseExecutableDefinition(lexer); + } else if (peekDescription(lexer)) { + return parseTypeSystemDefinition(lexer); + } + + throw unexpected(lexer); +} +/** + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + */ + + +function parseExecutableDefinition(lexer) { + if (peek(lexer, TokenKind.NAME)) { + switch (lexer.token.value) { + case 'query': + case 'mutation': + case 'subscription': + return parseOperationDefinition(lexer); + + case 'fragment': + return parseFragmentDefinition(lexer); + } + } else if (peek(lexer, TokenKind.BRACE_L)) { + return parseOperationDefinition(lexer); + } + + throw unexpected(lexer); +} // Implements the parsing rules in the Operations section. + +/** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + */ + + +function parseOperationDefinition(lexer) { + var start = lexer.token; + + if (peek(lexer, TokenKind.BRACE_L)) { + return { + kind: Kind.OPERATION_DEFINITION, + operation: 'query', + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + var operation = parseOperationType(lexer); + var name; + + if (peek(lexer, TokenKind.NAME)) { + name = parseName(lexer); + } + + return { + kind: Kind.OPERATION_DEFINITION, + operation: operation, + name: name, + variableDefinitions: parseVariableDefinitions(lexer), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * OperationType : one of query mutation subscription + */ + + +function parseOperationType(lexer) { + var operationToken = expect(lexer, TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return 'query'; + + case 'mutation': + return 'mutation'; + + case 'subscription': + return 'subscription'; + } + + throw unexpected(lexer, operationToken); +} +/** + * VariableDefinitions : ( VariableDefinition+ ) + */ + + +function parseVariableDefinitions(lexer) { + return peek(lexer, TokenKind.PAREN_L) ? many(lexer, TokenKind.PAREN_L, parseVariableDefinition, TokenKind.PAREN_R) : []; +} +/** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + */ + + +function parseVariableDefinition(lexer) { + var start = lexer.token; + + if (lexer.options.experimentalVariableDefinitionDirectives) { + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + directives: parseDirectives(lexer, true), + loc: loc(lexer, start) + }; + } + + return { + kind: Kind.VARIABLE_DEFINITION, + variable: parseVariable(lexer), + type: (expect(lexer, TokenKind.COLON), parseTypeReference(lexer)), + defaultValue: skip(lexer, TokenKind.EQUALS) ? parseValueLiteral(lexer, true) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Variable : $ Name + */ + + +function parseVariable(lexer) { + var start = lexer.token; + expect(lexer, TokenKind.DOLLAR); + return { + kind: Kind.VARIABLE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} +/** + * SelectionSet : { Selection+ } + */ + + +function parseSelectionSet(lexer) { + var start = lexer.token; + return { + kind: Kind.SELECTION_SET, + selections: many(lexer, TokenKind.BRACE_L, parseSelection, TokenKind.BRACE_R), + loc: loc(lexer, start) + }; +} +/** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + */ + + +function parseSelection(lexer) { + return peek(lexer, TokenKind.SPREAD) ? parseFragment(lexer) : parseField(lexer); +} +/** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + */ + + +function parseField(lexer) { + var start = lexer.token; + var nameOrAlias = parseName(lexer); + var alias; + var name; + + if (skip(lexer, TokenKind.COLON)) { + alias = nameOrAlias; + name = parseName(lexer); + } else { + name = nameOrAlias; + } + + return { + kind: Kind.FIELD, + alias: alias, + name: name, + arguments: parseArguments(lexer, false), + directives: parseDirectives(lexer, false), + selectionSet: peek(lexer, TokenKind.BRACE_L) ? parseSelectionSet(lexer) : undefined, + loc: loc(lexer, start) + }; +} +/** + * Arguments[Const] : ( Argument[?Const]+ ) + */ + + +function parseArguments(lexer, isConst) { + var item = isConst ? parseConstArgument : parseArgument; + return peek(lexer, TokenKind.PAREN_L) ? many(lexer, TokenKind.PAREN_L, item, TokenKind.PAREN_R) : []; +} +/** + * Argument[Const] : Name : Value[?Const] + */ + + +function parseArgument(lexer) { + var start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, false)), + loc: loc(lexer, start) + }; +} + +function parseConstArgument(lexer) { + var start = lexer.token; + return { + kind: Kind.ARGUMENT, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseConstValue(lexer)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Fragments section. + +/** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + */ + + +function parseFragment(lexer) { + var start = lexer.token; + expect(lexer, TokenKind.SPREAD); + + if (peek(lexer, TokenKind.NAME) && lexer.token.value !== 'on') { + return { + kind: Kind.FRAGMENT_SPREAD, + name: parseFragmentName(lexer), + directives: parseDirectives(lexer, false), + loc: loc(lexer, start) + }; + } + + var typeCondition; + + if (lexer.token.value === 'on') { + lexer.advance(); + typeCondition = parseNamedType(lexer); + } + + return { + kind: Kind.INLINE_FRAGMENT, + typeCondition: typeCondition, + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + */ + + +function parseFragmentDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'fragment'); // Experimental support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (lexer.options.experimentalFragmentVariables) { + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + variableDefinitions: parseVariableDefinitions(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; + } + + return { + kind: Kind.FRAGMENT_DEFINITION, + name: parseFragmentName(lexer), + typeCondition: (expectKeyword(lexer, 'on'), parseNamedType(lexer)), + directives: parseDirectives(lexer, false), + selectionSet: parseSelectionSet(lexer), + loc: loc(lexer, start) + }; +} +/** + * FragmentName : Name but not `on` + */ + + +function parseFragmentName(lexer) { + if (lexer.token.value === 'on') { + throw unexpected(lexer); + } + + return parseName(lexer); +} // Implements the parsing rules in the Values section. + +/** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + */ + + +function parseValueLiteral(lexer, isConst) { + var token = lexer.token; + + switch (token.kind) { + case TokenKind.BRACKET_L: + return parseList(lexer, isConst); + + case TokenKind.BRACE_L: + return parseObject(lexer, isConst); + + case TokenKind.INT: + lexer.advance(); + return { + kind: Kind.INT, + value: token.value, + loc: loc(lexer, token) + }; + + case TokenKind.FLOAT: + lexer.advance(); + return { + kind: Kind.FLOAT, + value: token.value, + loc: loc(lexer, token) + }; + + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return parseStringLiteral(lexer); + + case TokenKind.NAME: + if (token.value === 'true' || token.value === 'false') { + lexer.advance(); + return { + kind: Kind.BOOLEAN, + value: token.value === 'true', + loc: loc(lexer, token) + }; + } else if (token.value === 'null') { + lexer.advance(); + return { + kind: Kind.NULL, + loc: loc(lexer, token) + }; + } + + lexer.advance(); + return { + kind: Kind.ENUM, + value: token.value, + loc: loc(lexer, token) + }; + + case TokenKind.DOLLAR: + if (!isConst) { + return parseVariable(lexer); + } + + break; + } + + throw unexpected(lexer); +} + +function parseStringLiteral(lexer) { + var token = lexer.token; + lexer.advance(); + return { + kind: Kind.STRING, + value: token.value, + block: token.kind === TokenKind.BLOCK_STRING, + loc: loc(lexer, token) + }; +} + +export function parseConstValue(lexer) { + return parseValueLiteral(lexer, true); +} + +function parseValueValue(lexer) { + return parseValueLiteral(lexer, false); +} +/** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + */ + + +function parseList(lexer, isConst) { + var start = lexer.token; + var item = isConst ? parseConstValue : parseValueValue; + return { + kind: Kind.LIST, + values: any(lexer, TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + loc: loc(lexer, start) + }; +} +/** + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + */ + + +function parseObject(lexer, isConst) { + var start = lexer.token; + expect(lexer, TokenKind.BRACE_L); + var fields = []; + + while (!skip(lexer, TokenKind.BRACE_R)) { + fields.push(parseObjectField(lexer, isConst)); + } + + return { + kind: Kind.OBJECT, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ObjectField[Const] : Name : Value[?Const] + */ + + +function parseObjectField(lexer, isConst) { + var start = lexer.token; + return { + kind: Kind.OBJECT_FIELD, + name: parseName(lexer), + value: (expect(lexer, TokenKind.COLON), parseValueLiteral(lexer, isConst)), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Directives section. + +/** + * Directives[Const] : Directive[?Const]+ + */ + + +function parseDirectives(lexer, isConst) { + var directives = []; + + while (peek(lexer, TokenKind.AT)) { + directives.push(parseDirective(lexer, isConst)); + } + + return directives; +} +/** + * Directive[Const] : @ Name Arguments[?Const]? + */ + + +function parseDirective(lexer, isConst) { + var start = lexer.token; + expect(lexer, TokenKind.AT); + return { + kind: Kind.DIRECTIVE, + name: parseName(lexer), + arguments: parseArguments(lexer, isConst), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Types section. + +/** + * Type : + * - NamedType + * - ListType + * - NonNullType + */ + + +export function parseTypeReference(lexer) { + var start = lexer.token; + var type; + + if (skip(lexer, TokenKind.BRACKET_L)) { + type = parseTypeReference(lexer); + expect(lexer, TokenKind.BRACKET_R); + type = { + kind: Kind.LIST_TYPE, + type: type, + loc: loc(lexer, start) + }; + } else { + type = parseNamedType(lexer); + } + + if (skip(lexer, TokenKind.BANG)) { + return { + kind: Kind.NON_NULL_TYPE, + type: type, + loc: loc(lexer, start) + }; + } + + return type; +} +/** + * NamedType : Name + */ + +export function parseNamedType(lexer) { + var start = lexer.token; + return { + kind: Kind.NAMED_TYPE, + name: parseName(lexer), + loc: loc(lexer, start) + }; +} // Implements the parsing rules in the Type Definition section. + +/** + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + */ + +function parseTypeSystemDefinition(lexer) { + // Many definitions begin with a description and require a lookahead. + var keywordToken = peekDescription(lexer) ? lexer.lookahead() : lexer.token; + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaDefinition(lexer); + + case 'scalar': + return parseScalarTypeDefinition(lexer); + + case 'type': + return parseObjectTypeDefinition(lexer); + + case 'interface': + return parseInterfaceTypeDefinition(lexer); + + case 'union': + return parseUnionTypeDefinition(lexer); + + case 'enum': + return parseEnumTypeDefinition(lexer); + + case 'input': + return parseInputObjectTypeDefinition(lexer); + + case 'directive': + return parseDirectiveDefinition(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} + +function peekDescription(lexer) { + return peek(lexer, TokenKind.STRING) || peek(lexer, TokenKind.BLOCK_STRING); +} +/** + * Description : StringValue + */ + + +function parseDescription(lexer) { + if (peekDescription(lexer)) { + return parseStringLiteral(lexer); + } +} +/** + * SchemaDefinition : schema Directives[Const]? { OperationTypeDefinition+ } + */ + + +function parseSchemaDefinition(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = many(lexer, TokenKind.BRACE_L, parseOperationTypeDefinition, TokenKind.BRACE_R); + return { + kind: Kind.SCHEMA_DEFINITION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * OperationTypeDefinition : OperationType : NamedType + */ + + +function parseOperationTypeDefinition(lexer) { + var start = lexer.token; + var operation = parseOperationType(lexer); + expect(lexer, TokenKind.COLON); + var type = parseNamedType(lexer); + return { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation: operation, + type: type, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + */ + + +function parseScalarTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: Kind.SCALAR_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + */ + + +function parseObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: Kind.OBJECT_TYPE_DEFINITION, + description: description, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + */ + + +function parseImplementsInterfaces(lexer) { + var types = []; + + if (lexer.token.value === 'implements') { + lexer.advance(); // Optional leading ampersand + + skip(lexer, TokenKind.AMP); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, TokenKind.AMP) || // Legacy support for the SDL? + lexer.options.allowLegacySDLImplementsInterfaces && peek(lexer, TokenKind.NAME)); + } + + return types; +} +/** + * FieldsDefinition : { FieldDefinition+ } + */ + + +function parseFieldsDefinition(lexer) { + // Legacy support for the SDL? + if (lexer.options.allowLegacySDLEmptyFields && peek(lexer, TokenKind.BRACE_L) && lexer.lookahead().kind === TokenKind.BRACE_R) { + lexer.advance(); + lexer.advance(); + return []; + } + + return peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseFieldDefinition, TokenKind.BRACE_R) : []; +} +/** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + */ + + +function parseFieldDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expect(lexer, TokenKind.COLON); + var type = parseTypeReference(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: Kind.FIELD_DEFINITION, + description: description, + name: name, + arguments: args, + type: type, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ArgumentsDefinition : ( InputValueDefinition+ ) + */ + + +function parseArgumentDefs(lexer) { + if (!peek(lexer, TokenKind.PAREN_L)) { + return []; + } + + return many(lexer, TokenKind.PAREN_L, parseInputValueDef, TokenKind.PAREN_R); +} +/** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + */ + + +function parseInputValueDef(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + expect(lexer, TokenKind.COLON); + var type = parseTypeReference(lexer); + var defaultValue; + + if (skip(lexer, TokenKind.EQUALS)) { + defaultValue = parseConstValue(lexer); + } + + var directives = parseDirectives(lexer, true); + return { + kind: Kind.INPUT_VALUE_DEFINITION, + description: description, + name: name, + type: type, + defaultValue: defaultValue, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + */ + + +function parseInterfaceTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + return { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + */ + + +function parseUnionTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + return { + kind: Kind.UNION_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + */ + + +function parseUnionMemberTypes(lexer) { + var types = []; + + if (skip(lexer, TokenKind.EQUALS)) { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + + do { + types.push(parseNamedType(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + } + + return types; +} +/** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + */ + + +function parseEnumTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + return { + kind: Kind.ENUM_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * EnumValuesDefinition : { EnumValueDefinition+ } + */ + + +function parseEnumValuesDefinition(lexer) { + return peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseEnumValueDefinition, TokenKind.BRACE_R) : []; +} +/** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * EnumValue : Name + */ + + +function parseEnumValueDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + return { + kind: Kind.ENUM_VALUE_DEFINITION, + description: description, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + */ + + +function parseInputObjectTypeDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + return { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description: description, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InputFieldsDefinition : { InputValueDefinition+ } + */ + + +function parseInputFieldsDefinition(lexer) { + return peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseInputValueDef, TokenKind.BRACE_R) : []; +} +/** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + */ + + +function parseTypeSystemExtension(lexer) { + var keywordToken = lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return parseSchemaExtension(lexer); + + case 'scalar': + return parseScalarTypeExtension(lexer); + + case 'type': + return parseObjectTypeExtension(lexer); + + case 'interface': + return parseInterfaceTypeExtension(lexer); + + case 'union': + return parseUnionTypeExtension(lexer); + + case 'enum': + return parseEnumTypeExtension(lexer); + + case 'input': + return parseInputObjectTypeExtension(lexer); + } + } + + throw unexpected(lexer, keywordToken); +} +/** + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + */ + + +function parseSchemaExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'schema'); + var directives = parseDirectives(lexer, true); + var operationTypes = peek(lexer, TokenKind.BRACE_L) ? many(lexer, TokenKind.BRACE_L, parseOperationTypeDefinition, TokenKind.BRACE_R) : []; + + if (directives.length === 0 && operationTypes.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.SCHEMA_EXTENSION, + directives: directives, + operationTypes: operationTypes, + loc: loc(lexer, start) + }; +} +/** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + */ + + +function parseScalarTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'scalar'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + + if (directives.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.SCALAR_TYPE_EXTENSION, + name: name, + directives: directives, + loc: loc(lexer, start) + }; +} +/** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + */ + + +function parseObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'type'); + var name = parseName(lexer); + var interfaces = parseImplementsInterfaces(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (interfaces.length === 0 && directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.OBJECT_TYPE_EXTENSION, + name: name, + interfaces: interfaces, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * InterfaceTypeExtension : + * - extend interface Name Directives[Const]? FieldsDefinition + * - extend interface Name Directives[Const] + */ + + +function parseInterfaceTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'interface'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + */ + + +function parseUnionTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'union'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var types = parseUnionMemberTypes(lexer); + + if (directives.length === 0 && types.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.UNION_TYPE_EXTENSION, + name: name, + directives: directives, + types: types, + loc: loc(lexer, start) + }; +} +/** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + */ + + +function parseEnumTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'enum'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var values = parseEnumValuesDefinition(lexer); + + if (directives.length === 0 && values.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.ENUM_TYPE_EXTENSION, + name: name, + directives: directives, + values: values, + loc: loc(lexer, start) + }; +} +/** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + */ + + +function parseInputObjectTypeExtension(lexer) { + var start = lexer.token; + expectKeyword(lexer, 'extend'); + expectKeyword(lexer, 'input'); + var name = parseName(lexer); + var directives = parseDirectives(lexer, true); + var fields = parseInputFieldsDefinition(lexer); + + if (directives.length === 0 && fields.length === 0) { + throw unexpected(lexer); + } + + return { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name: name, + directives: directives, + fields: fields, + loc: loc(lexer, start) + }; +} +/** + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? on DirectiveLocations + */ + + +function parseDirectiveDefinition(lexer) { + var start = lexer.token; + var description = parseDescription(lexer); + expectKeyword(lexer, 'directive'); + expect(lexer, TokenKind.AT); + var name = parseName(lexer); + var args = parseArgumentDefs(lexer); + expectKeyword(lexer, 'on'); + var locations = parseDirectiveLocations(lexer); + return { + kind: Kind.DIRECTIVE_DEFINITION, + description: description, + name: name, + arguments: args, + locations: locations, + loc: loc(lexer, start) + }; +} +/** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + */ + + +function parseDirectiveLocations(lexer) { + // Optional leading pipe + skip(lexer, TokenKind.PIPE); + var locations = []; + + do { + locations.push(parseDirectiveLocation(lexer)); + } while (skip(lexer, TokenKind.PIPE)); + + return locations; +} +/* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + */ + + +function parseDirectiveLocation(lexer) { + var start = lexer.token; + var name = parseName(lexer); + + if (DirectiveLocation.hasOwnProperty(name.value)) { + return name; + } + + throw unexpected(lexer, start); +} // Core parsing utility functions + +/** + * Returns a location object, used to identify the place in + * the source that created a given parsed object. + */ + + +function loc(lexer, startToken) { + if (!lexer.options.noLocation) { + return new Loc(startToken, lexer.lastToken, lexer.source); + } +} + +function Loc(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; +} // Print a simplified form when appearing in JSON/util.inspect. + + +Loc.prototype.toJSON = Loc.prototype.inspect = function toJSON() { + return { + start: this.start, + end: this.end + }; +}; +/** + * Determines if the next token is of a given kind + */ + + +function peek(lexer, kind) { + return lexer.token.kind === kind; +} +/** + * If the next token is of the given kind, return true after advancing + * the lexer. Otherwise, do not change the parser state and return false. + */ + + +function skip(lexer, kind) { + var match = lexer.token.kind === kind; + + if (match) { + lexer.advance(); + } + + return match; +} +/** + * If the next token is of the given kind, return that token after advancing + * the lexer. Otherwise, do not change the parser state and throw an error. + */ + + +function expect(lexer, kind) { + var token = lexer.token; + + if (token.kind === kind) { + lexer.advance(); + return token; + } + + throw syntaxError(lexer.source, token.start, "Expected ".concat(kind, ", found ").concat(getTokenDesc(token))); +} +/** + * If the next token is a keyword with the given value, return that token after + * advancing the lexer. Otherwise, do not change the parser state and return + * false. + */ + + +function expectKeyword(lexer, value) { + var token = lexer.token; + + if (token.kind === TokenKind.NAME && token.value === value) { + lexer.advance(); + return token; + } + + throw syntaxError(lexer.source, token.start, "Expected \"".concat(value, "\", found ").concat(getTokenDesc(token))); +} +/** + * Helper function for creating an error when an unexpected lexed token + * is encountered. + */ + + +function unexpected(lexer, atToken) { + var token = atToken || lexer.token; + return syntaxError(lexer.source, token.start, "Unexpected ".concat(getTokenDesc(token))); +} +/** + * Returns a possibly empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function any(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = []; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} +/** + * Returns a non-empty list of parse nodes, determined by + * the parseFn. This list begins with a lex token of openKind + * and ends with a lex token of closeKind. Advances the parser + * to the next lex token after the closing token. + */ + + +function many(lexer, openKind, parseFn, closeKind) { + expect(lexer, openKind); + var nodes = [parseFn(lexer)]; + + while (!skip(lexer, closeKind)) { + nodes.push(parseFn(lexer)); + } + + return nodes; +} \ No newline at end of file diff --git a/node_modules/graphql/language/predicates.js b/node_modules/graphql/language/predicates.js new file mode 100644 index 00000000..f06ed8d4 --- /dev/null +++ b/node_modules/graphql/language/predicates.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDefinitionNode = isDefinitionNode; +exports.isExecutableDefinitionNode = isExecutableDefinitionNode; +exports.isSelectionNode = isSelectionNode; +exports.isValueNode = isValueNode; +exports.isTypeNode = isTypeNode; +exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; +exports.isTypeDefinitionNode = isTypeDefinitionNode; +exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; +exports.isTypeExtensionNode = isTypeExtensionNode; + +var _kinds = require("./kinds"); + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} + +function isExecutableDefinitionNode(node) { + return node.kind === _kinds.Kind.OPERATION_DEFINITION || node.kind === _kinds.Kind.FRAGMENT_DEFINITION; +} + +function isSelectionNode(node) { + return node.kind === _kinds.Kind.FIELD || node.kind === _kinds.Kind.FRAGMENT_SPREAD || node.kind === _kinds.Kind.INLINE_FRAGMENT; +} + +function isValueNode(node) { + return node.kind === _kinds.Kind.VARIABLE || node.kind === _kinds.Kind.INT || node.kind === _kinds.Kind.FLOAT || node.kind === _kinds.Kind.STRING || node.kind === _kinds.Kind.BOOLEAN || node.kind === _kinds.Kind.NULL || node.kind === _kinds.Kind.ENUM || node.kind === _kinds.Kind.LIST || node.kind === _kinds.Kind.OBJECT; +} + +function isTypeNode(node) { + return node.kind === _kinds.Kind.NAMED_TYPE || node.kind === _kinds.Kind.LIST_TYPE || node.kind === _kinds.Kind.NON_NULL_TYPE; +} + +function isTypeSystemDefinitionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === _kinds.Kind.DIRECTIVE_DEFINITION; +} + +function isTypeDefinitionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION; +} + +function isTypeSystemExtensionNode(node) { + return node.kind === _kinds.Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} + +function isTypeExtensionNode(node) { + return node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; +} \ No newline at end of file diff --git a/node_modules/graphql/language/predicates.js.flow b/node_modules/graphql/language/predicates.js.flow new file mode 100644 index 00000000..bde7b3a6 --- /dev/null +++ b/node_modules/graphql/language/predicates.js.flow @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTNode } from './ast'; +import { Kind } from './kinds'; + +export function isDefinitionNode(node: ASTNode): boolean %checks { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); +} + +export function isExecutableDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.OPERATION_DEFINITION || + node.kind === Kind.FRAGMENT_DEFINITION + ); +} + +export function isSelectionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.FIELD || + node.kind === Kind.FRAGMENT_SPREAD || + node.kind === Kind.INLINE_FRAGMENT + ); +} + +export function isValueNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.VARIABLE || + node.kind === Kind.INT || + node.kind === Kind.FLOAT || + node.kind === Kind.STRING || + node.kind === Kind.BOOLEAN || + node.kind === Kind.NULL || + node.kind === Kind.ENUM || + node.kind === Kind.LIST || + node.kind === Kind.OBJECT + ); +} + +export function isTypeNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.NAMED_TYPE || + node.kind === Kind.LIST_TYPE || + node.kind === Kind.NON_NULL_TYPE + ); +} + +export function isTypeSystemDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === Kind.DIRECTIVE_DEFINITION + ); +} + +export function isTypeDefinitionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCALAR_TYPE_DEFINITION || + node.kind === Kind.OBJECT_TYPE_DEFINITION || + node.kind === Kind.INTERFACE_TYPE_DEFINITION || + node.kind === Kind.UNION_TYPE_DEFINITION || + node.kind === Kind.ENUM_TYPE_DEFINITION || + node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ); +} + +export function isTypeSystemExtensionNode(node: ASTNode): boolean %checks { + return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} + +export function isTypeExtensionNode(node: ASTNode): boolean %checks { + return ( + node.kind === Kind.SCALAR_TYPE_EXTENSION || + node.kind === Kind.OBJECT_TYPE_EXTENSION || + node.kind === Kind.INTERFACE_TYPE_EXTENSION || + node.kind === Kind.UNION_TYPE_EXTENSION || + node.kind === Kind.ENUM_TYPE_EXTENSION || + node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION + ); +} diff --git a/node_modules/graphql/language/predicates.mjs b/node_modules/graphql/language/predicates.mjs new file mode 100644 index 00000000..3d8af902 --- /dev/null +++ b/node_modules/graphql/language/predicates.mjs @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from './kinds'; +export function isDefinitionNode(node) { + return isExecutableDefinitionNode(node) || isTypeSystemDefinitionNode(node) || isTypeSystemExtensionNode(node); +} +export function isExecutableDefinitionNode(node) { + return node.kind === Kind.OPERATION_DEFINITION || node.kind === Kind.FRAGMENT_DEFINITION; +} +export function isSelectionNode(node) { + return node.kind === Kind.FIELD || node.kind === Kind.FRAGMENT_SPREAD || node.kind === Kind.INLINE_FRAGMENT; +} +export function isValueNode(node) { + return node.kind === Kind.VARIABLE || node.kind === Kind.INT || node.kind === Kind.FLOAT || node.kind === Kind.STRING || node.kind === Kind.BOOLEAN || node.kind === Kind.NULL || node.kind === Kind.ENUM || node.kind === Kind.LIST || node.kind === Kind.OBJECT; +} +export function isTypeNode(node) { + return node.kind === Kind.NAMED_TYPE || node.kind === Kind.LIST_TYPE || node.kind === Kind.NON_NULL_TYPE; +} +export function isTypeSystemDefinitionNode(node) { + return node.kind === Kind.SCHEMA_DEFINITION || isTypeDefinitionNode(node) || node.kind === Kind.DIRECTIVE_DEFINITION; +} +export function isTypeDefinitionNode(node) { + return node.kind === Kind.SCALAR_TYPE_DEFINITION || node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INTERFACE_TYPE_DEFINITION || node.kind === Kind.UNION_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION; +} +export function isTypeSystemExtensionNode(node) { + return node.kind === Kind.SCHEMA_EXTENSION || isTypeExtensionNode(node); +} +export function isTypeExtensionNode(node) { + return node.kind === Kind.SCALAR_TYPE_EXTENSION || node.kind === Kind.OBJECT_TYPE_EXTENSION || node.kind === Kind.INTERFACE_TYPE_EXTENSION || node.kind === Kind.UNION_TYPE_EXTENSION || node.kind === Kind.ENUM_TYPE_EXTENSION || node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION; +} \ No newline at end of file diff --git a/node_modules/graphql/language/printer.js b/node_modules/graphql/language/printer.js new file mode 100644 index 00000000..18e3340c --- /dev/null +++ b/node_modules/graphql/language/printer.js @@ -0,0 +1,319 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.print = print; + +var _visitor = require("./visitor"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +function print(ast) { + return (0, _visitor.visit)(ast, { + leave: printDocASTReducer + }); +} + +var printDocASTReducer = { + Name: function Name(node) { + return node.value; + }, + Variable: function Variable(node) { + return '$' + node.name; + }, + // Document + Document: function Document(node) { + return join(node.definitions, '\n\n') + '\n'; + }, + OperationDefinition: function OperationDefinition(node) { + var op = node.operation; + var name = node.name; + var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + var directives = join(node.directives, ' '); + var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + VariableDefinition: function VariableDefinition(_ref) { + var variable = _ref.variable, + type = _ref.type, + defaultValue = _ref.defaultValue, + directives = _ref.directives; + return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); + }, + SelectionSet: function SelectionSet(_ref2) { + var selections = _ref2.selections; + return block(selections); + }, + Field: function Field(_ref3) { + var alias = _ref3.alias, + name = _ref3.name, + args = _ref3.arguments, + directives = _ref3.directives, + selectionSet = _ref3.selectionSet; + return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' '); + }, + Argument: function Argument(_ref4) { + var name = _ref4.name, + value = _ref4.value; + return name + ': ' + value; + }, + // Fragments + FragmentSpread: function FragmentSpread(_ref5) { + var name = _ref5.name, + directives = _ref5.directives; + return '...' + name + wrap(' ', join(directives, ' ')); + }, + InlineFragment: function InlineFragment(_ref6) { + var typeCondition = _ref6.typeCondition, + directives = _ref6.directives, + selectionSet = _ref6.selectionSet; + return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); + }, + FragmentDefinition: function FragmentDefinition(_ref7) { + var name = _ref7.name, + typeCondition = _ref7.typeCondition, + variableDefinitions = _ref7.variableDefinitions, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return (// Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet + ); + }, + // Value + IntValue: function IntValue(_ref8) { + var value = _ref8.value; + return value; + }, + FloatValue: function FloatValue(_ref9) { + var value = _ref9.value; + return value; + }, + StringValue: function StringValue(_ref10, key) { + var value = _ref10.value, + isBlockString = _ref10.block; + return isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return value ? 'true' : 'false'; + }, + NullValue: function NullValue() { + return 'null'; + }, + EnumValue: function EnumValue(_ref12) { + var value = _ref12.value; + return value; + }, + ListValue: function ListValue(_ref13) { + var values = _ref13.values; + return '[' + join(values, ', ') + ']'; + }, + ObjectValue: function ObjectValue(_ref14) { + var fields = _ref14.fields; + return '{' + join(fields, ', ') + '}'; + }, + ObjectField: function ObjectField(_ref15) { + var name = _ref15.name, + value = _ref15.value; + return name + ': ' + value; + }, + // Directive + Directive: function Directive(_ref16) { + var name = _ref16.name, + args = _ref16.arguments; + return '@' + name + wrap('(', join(args, ', '), ')'); + }, + // Type + NamedType: function NamedType(_ref17) { + var name = _ref17.name; + return name; + }, + ListType: function ListType(_ref18) { + var type = _ref18.type; + return '[' + type + ']'; + }, + NonNullType: function NonNullType(_ref19) { + var type = _ref19.type; + return type + '!'; + }, + // Type System Definitions + SchemaDefinition: function SchemaDefinition(_ref20) { + var directives = _ref20.directives, + operationTypes = _ref20.operationTypes; + return join(['schema', join(directives, ' '), block(operationTypes)], ' '); + }, + OperationTypeDefinition: function OperationTypeDefinition(_ref21) { + var operation = _ref21.operation, + type = _ref21.type; + return operation + ': ' + type; + }, + ScalarTypeDefinition: addDescription(function (_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }), + ObjectTypeDefinition: addDescription(function (_ref23) { + var name = _ref23.name, + interfaces = _ref23.interfaces, + directives = _ref23.directives, + fields = _ref23.fields; + return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + FieldDefinition: addDescription(function (_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ': ' + type + wrap(' ', join(directives, ' ')); + }), + InputValueDefinition: addDescription(function (_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }), + InterfaceTypeDefinition: addDescription(function (_ref26) { + var name = _ref26.name, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, join(directives, ' '), block(fields)], ' '); + }), + UnionTypeDefinition: addDescription(function (_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }), + EnumTypeDefinition: addDescription(function (_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }), + EnumValueDefinition: addDescription(function (_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }), + InputObjectTypeDefinition: addDescription(function (_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }), + DirectiveDefinition: addDescription(function (_ref31) { + var name = _ref31.name, + args = _ref31.arguments, + locations = _ref31.locations; + return 'directive @' + name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ' on ' + join(locations, ' | '); + }), + SchemaExtension: function SchemaExtension(_ref32) { + var directives = _ref32.directives, + operationTypes = _ref32.operationTypes; + return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); + }, + ScalarTypeExtension: function ScalarTypeExtension(_ref33) { + var name = _ref33.name, + directives = _ref33.directives; + return join(['extend scalar', name, join(directives, ' ')], ' '); + }, + ObjectTypeExtension: function ObjectTypeExtension(_ref34) { + var name = _ref34.name, + interfaces = _ref34.interfaces, + directives = _ref34.directives, + fields = _ref34.fields; + return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { + var name = _ref35.name, + directives = _ref35.directives, + fields = _ref35.fields; + return join(['extend interface', name, join(directives, ' '), block(fields)], ' '); + }, + UnionTypeExtension: function UnionTypeExtension(_ref36) { + var name = _ref36.name, + directives = _ref36.directives, + types = _ref36.types; + return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }, + EnumTypeExtension: function EnumTypeExtension(_ref37) { + var name = _ref37.name, + directives = _ref37.directives, + values = _ref37.values; + return join(['extend enum', name, join(directives, ' '), block(values)], ' '); + }, + InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { + var name = _ref38.name, + directives = _ref38.directives, + fields = _ref38.fields; + return join(['extend input', name, join(directives, ' '), block(fields)], ' '); + } +}; + +function addDescription(cb) { + return function (node) { + return join([node.description, cb(node)], '\n'); + }; +} +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + +function join(maybeArray, separator) { + return maybeArray ? maybeArray.filter(function (x) { + return x; + }).join(separator || '') : ''; +} +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ + + +function block(array) { + return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : ''; +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise + * print an empty string. + */ + + +function wrap(start, maybeString, end) { + return maybeString ? start + maybeString + (end || '') : ''; +} + +function indent(maybeString) { + return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ + + +function printBlockString(value, isDescription) { + var escaped = value.replace(/"""/g, '\\"""'); + return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 ? "\"\"\"".concat(escaped.replace(/"$/, '"\n'), "\"\"\"") : "\"\"\"\n".concat(isDescription ? escaped : indent(escaped), "\n\"\"\""); +} \ No newline at end of file diff --git a/node_modules/graphql/language/printer.js.flow b/node_modules/graphql/language/printer.js.flow new file mode 100644 index 00000000..5254f46e --- /dev/null +++ b/node_modules/graphql/language/printer.js.flow @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import { visit } from './visitor'; + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ +export function print(ast) { + return visit(ast, { leave: printDocASTReducer }); +} + +const printDocASTReducer = { + Name: node => node.value, + Variable: node => '$' + node.name, + + // Document + + Document: node => join(node.definitions, '\n\n') + '\n', + + OperationDefinition(node) { + const op = node.operation; + const name = node.name; + const varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + const directives = join(node.directives, ' '); + const selectionSet = node.selectionSet; + // Anonymous queries with no directives or variable definitions can use + // the query short form. + return !name && !directives && !varDefs && op === 'query' + ? selectionSet + : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + + VariableDefinition: ({ variable, type, defaultValue, directives }) => + variable + + ': ' + + type + + wrap(' = ', defaultValue) + + wrap(' ', join(directives, ' ')), + SelectionSet: ({ selections }) => block(selections), + + Field: ({ alias, name, arguments: args, directives, selectionSet }) => + join( + [ + wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), + join(directives, ' '), + selectionSet, + ], + ' ', + ), + + Argument: ({ name, value }) => name + ': ' + value, + + // Fragments + + FragmentSpread: ({ name, directives }) => + '...' + name + wrap(' ', join(directives, ' ')), + + InlineFragment: ({ typeCondition, directives, selectionSet }) => + join( + ['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], + ' ', + ), + + FragmentDefinition: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet, + }) => + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + + selectionSet, + + // Value + + IntValue: ({ value }) => value, + FloatValue: ({ value }) => value, + StringValue: ({ value, block: isBlockString }, key) => + isBlockString + ? printBlockString(value, key === 'description') + : JSON.stringify(value), + BooleanValue: ({ value }) => (value ? 'true' : 'false'), + NullValue: () => 'null', + EnumValue: ({ value }) => value, + ListValue: ({ values }) => '[' + join(values, ', ') + ']', + ObjectValue: ({ fields }) => '{' + join(fields, ', ') + '}', + ObjectField: ({ name, value }) => name + ': ' + value, + + // Directive + + Directive: ({ name, arguments: args }) => + '@' + name + wrap('(', join(args, ', '), ')'), + + // Type + + NamedType: ({ name }) => name, + ListType: ({ type }) => '[' + type + ']', + NonNullType: ({ type }) => type + '!', + + // Type System Definitions + + SchemaDefinition: ({ directives, operationTypes }) => + join(['schema', join(directives, ' '), block(operationTypes)], ' '), + + OperationTypeDefinition: ({ operation, type }) => operation + ': ' + type, + + ScalarTypeDefinition: addDescription(({ name, directives }) => + join(['scalar', name, join(directives, ' ')], ' '), + ), + + ObjectTypeDefinition: addDescription( + ({ name, interfaces, directives, fields }) => + join( + [ + 'type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + ), + + FieldDefinition: addDescription( + ({ name, arguments: args, type, directives }) => + name + + (args.every(arg => arg.indexOf('\n') === -1) + ? wrap('(', join(args, ', '), ')') + : wrap('(\n', indent(join(args, '\n')), '\n)')) + + ': ' + + type + + wrap(' ', join(directives, ' ')), + ), + + InputValueDefinition: addDescription( + ({ name, type, defaultValue, directives }) => + join( + [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], + ' ', + ), + ), + + InterfaceTypeDefinition: addDescription(({ name, directives, fields }) => + join(['interface', name, join(directives, ' '), block(fields)], ' '), + ), + + UnionTypeDefinition: addDescription(({ name, directives, types }) => + join( + [ + 'union', + name, + join(directives, ' '), + types && types.length !== 0 ? '= ' + join(types, ' | ') : '', + ], + ' ', + ), + ), + + EnumTypeDefinition: addDescription(({ name, directives, values }) => + join(['enum', name, join(directives, ' '), block(values)], ' '), + ), + + EnumValueDefinition: addDescription(({ name, directives }) => + join([name, join(directives, ' ')], ' '), + ), + + InputObjectTypeDefinition: addDescription(({ name, directives, fields }) => + join(['input', name, join(directives, ' '), block(fields)], ' '), + ), + + DirectiveDefinition: addDescription( + ({ name, arguments: args, locations }) => + 'directive @' + + name + + (args.every(arg => arg.indexOf('\n') === -1) + ? wrap('(', join(args, ', '), ')') + : wrap('(\n', indent(join(args, '\n')), '\n)')) + + ' on ' + + join(locations, ' | '), + ), + + SchemaExtension: ({ directives, operationTypes }) => + join(['extend schema', join(directives, ' '), block(operationTypes)], ' '), + + ScalarTypeExtension: ({ name, directives }) => + join(['extend scalar', name, join(directives, ' ')], ' '), + + ObjectTypeExtension: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + + InterfaceTypeExtension: ({ name, directives, fields }) => + join(['extend interface', name, join(directives, ' '), block(fields)], ' '), + + UnionTypeExtension: ({ name, directives, types }) => + join( + [ + 'extend union', + name, + join(directives, ' '), + types && types.length !== 0 ? '= ' + join(types, ' | ') : '', + ], + ' ', + ), + + EnumTypeExtension: ({ name, directives, values }) => + join(['extend enum', name, join(directives, ' '), block(values)], ' '), + + InputObjectTypeExtension: ({ name, directives, fields }) => + join(['extend input', name, join(directives, ' '), block(fields)], ' '), +}; + +function addDescription(cb) { + return node => join([node.description, cb(node)], '\n'); +} + +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ +function join(maybeArray, separator) { + return maybeArray ? maybeArray.filter(x => x).join(separator || '') : ''; +} + +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ +function block(array) { + return array && array.length !== 0 + ? '{\n' + indent(join(array, '\n')) + '\n}' + : ''; +} + +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise + * print an empty string. + */ +function wrap(start, maybeString, end) { + return maybeString ? start + maybeString + (end || '') : ''; +} + +function indent(maybeString) { + return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); +} + +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ +function printBlockString(value, isDescription) { + const escaped = value.replace(/"""/g, '\\"""'); + return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 + ? `"""${escaped.replace(/"$/, '"\n')}"""` + : `"""\n${isDescription ? escaped : indent(escaped)}\n"""`; +} diff --git a/node_modules/graphql/language/printer.mjs b/node_modules/graphql/language/printer.mjs new file mode 100644 index 00000000..b6d56f17 --- /dev/null +++ b/node_modules/graphql/language/printer.mjs @@ -0,0 +1,310 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +import { visit } from './visitor'; +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + */ + +export function print(ast) { + return visit(ast, { + leave: printDocASTReducer + }); +} +var printDocASTReducer = { + Name: function Name(node) { + return node.value; + }, + Variable: function Variable(node) { + return '$' + node.name; + }, + // Document + Document: function Document(node) { + return join(node.definitions, '\n\n') + '\n'; + }, + OperationDefinition: function OperationDefinition(node) { + var op = node.operation; + var name = node.name; + var varDefs = wrap('(', join(node.variableDefinitions, ', '), ')'); + var directives = join(node.directives, ' '); + var selectionSet = node.selectionSet; // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return !name && !directives && !varDefs && op === 'query' ? selectionSet : join([op, join([name, varDefs]), directives, selectionSet], ' '); + }, + VariableDefinition: function VariableDefinition(_ref) { + var variable = _ref.variable, + type = _ref.type, + defaultValue = _ref.defaultValue, + directives = _ref.directives; + return variable + ': ' + type + wrap(' = ', defaultValue) + wrap(' ', join(directives, ' ')); + }, + SelectionSet: function SelectionSet(_ref2) { + var selections = _ref2.selections; + return block(selections); + }, + Field: function Field(_ref3) { + var alias = _ref3.alias, + name = _ref3.name, + args = _ref3.arguments, + directives = _ref3.directives, + selectionSet = _ref3.selectionSet; + return join([wrap('', alias, ': ') + name + wrap('(', join(args, ', '), ')'), join(directives, ' '), selectionSet], ' '); + }, + Argument: function Argument(_ref4) { + var name = _ref4.name, + value = _ref4.value; + return name + ': ' + value; + }, + // Fragments + FragmentSpread: function FragmentSpread(_ref5) { + var name = _ref5.name, + directives = _ref5.directives; + return '...' + name + wrap(' ', join(directives, ' ')); + }, + InlineFragment: function InlineFragment(_ref6) { + var typeCondition = _ref6.typeCondition, + directives = _ref6.directives, + selectionSet = _ref6.selectionSet; + return join(['...', wrap('on ', typeCondition), join(directives, ' '), selectionSet], ' '); + }, + FragmentDefinition: function FragmentDefinition(_ref7) { + var name = _ref7.name, + typeCondition = _ref7.typeCondition, + variableDefinitions = _ref7.variableDefinitions, + directives = _ref7.directives, + selectionSet = _ref7.selectionSet; + return (// Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + "fragment ".concat(name).concat(wrap('(', join(variableDefinitions, ', '), ')'), " ") + "on ".concat(typeCondition, " ").concat(wrap('', join(directives, ' '), ' ')) + selectionSet + ); + }, + // Value + IntValue: function IntValue(_ref8) { + var value = _ref8.value; + return value; + }, + FloatValue: function FloatValue(_ref9) { + var value = _ref9.value; + return value; + }, + StringValue: function StringValue(_ref10, key) { + var value = _ref10.value, + isBlockString = _ref10.block; + return isBlockString ? printBlockString(value, key === 'description') : JSON.stringify(value); + }, + BooleanValue: function BooleanValue(_ref11) { + var value = _ref11.value; + return value ? 'true' : 'false'; + }, + NullValue: function NullValue() { + return 'null'; + }, + EnumValue: function EnumValue(_ref12) { + var value = _ref12.value; + return value; + }, + ListValue: function ListValue(_ref13) { + var values = _ref13.values; + return '[' + join(values, ', ') + ']'; + }, + ObjectValue: function ObjectValue(_ref14) { + var fields = _ref14.fields; + return '{' + join(fields, ', ') + '}'; + }, + ObjectField: function ObjectField(_ref15) { + var name = _ref15.name, + value = _ref15.value; + return name + ': ' + value; + }, + // Directive + Directive: function Directive(_ref16) { + var name = _ref16.name, + args = _ref16.arguments; + return '@' + name + wrap('(', join(args, ', '), ')'); + }, + // Type + NamedType: function NamedType(_ref17) { + var name = _ref17.name; + return name; + }, + ListType: function ListType(_ref18) { + var type = _ref18.type; + return '[' + type + ']'; + }, + NonNullType: function NonNullType(_ref19) { + var type = _ref19.type; + return type + '!'; + }, + // Type System Definitions + SchemaDefinition: function SchemaDefinition(_ref20) { + var directives = _ref20.directives, + operationTypes = _ref20.operationTypes; + return join(['schema', join(directives, ' '), block(operationTypes)], ' '); + }, + OperationTypeDefinition: function OperationTypeDefinition(_ref21) { + var operation = _ref21.operation, + type = _ref21.type; + return operation + ': ' + type; + }, + ScalarTypeDefinition: addDescription(function (_ref22) { + var name = _ref22.name, + directives = _ref22.directives; + return join(['scalar', name, join(directives, ' ')], ' '); + }), + ObjectTypeDefinition: addDescription(function (_ref23) { + var name = _ref23.name, + interfaces = _ref23.interfaces, + directives = _ref23.directives, + fields = _ref23.fields; + return join(['type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }), + FieldDefinition: addDescription(function (_ref24) { + var name = _ref24.name, + args = _ref24.arguments, + type = _ref24.type, + directives = _ref24.directives; + return name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ': ' + type + wrap(' ', join(directives, ' ')); + }), + InputValueDefinition: addDescription(function (_ref25) { + var name = _ref25.name, + type = _ref25.type, + defaultValue = _ref25.defaultValue, + directives = _ref25.directives; + return join([name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], ' '); + }), + InterfaceTypeDefinition: addDescription(function (_ref26) { + var name = _ref26.name, + directives = _ref26.directives, + fields = _ref26.fields; + return join(['interface', name, join(directives, ' '), block(fields)], ' '); + }), + UnionTypeDefinition: addDescription(function (_ref27) { + var name = _ref27.name, + directives = _ref27.directives, + types = _ref27.types; + return join(['union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }), + EnumTypeDefinition: addDescription(function (_ref28) { + var name = _ref28.name, + directives = _ref28.directives, + values = _ref28.values; + return join(['enum', name, join(directives, ' '), block(values)], ' '); + }), + EnumValueDefinition: addDescription(function (_ref29) { + var name = _ref29.name, + directives = _ref29.directives; + return join([name, join(directives, ' ')], ' '); + }), + InputObjectTypeDefinition: addDescription(function (_ref30) { + var name = _ref30.name, + directives = _ref30.directives, + fields = _ref30.fields; + return join(['input', name, join(directives, ' '), block(fields)], ' '); + }), + DirectiveDefinition: addDescription(function (_ref31) { + var name = _ref31.name, + args = _ref31.arguments, + locations = _ref31.locations; + return 'directive @' + name + (args.every(function (arg) { + return arg.indexOf('\n') === -1; + }) ? wrap('(', join(args, ', '), ')') : wrap('(\n', indent(join(args, '\n')), '\n)')) + ' on ' + join(locations, ' | '); + }), + SchemaExtension: function SchemaExtension(_ref32) { + var directives = _ref32.directives, + operationTypes = _ref32.operationTypes; + return join(['extend schema', join(directives, ' '), block(operationTypes)], ' '); + }, + ScalarTypeExtension: function ScalarTypeExtension(_ref33) { + var name = _ref33.name, + directives = _ref33.directives; + return join(['extend scalar', name, join(directives, ' ')], ' '); + }, + ObjectTypeExtension: function ObjectTypeExtension(_ref34) { + var name = _ref34.name, + interfaces = _ref34.interfaces, + directives = _ref34.directives, + fields = _ref34.fields; + return join(['extend type', name, wrap('implements ', join(interfaces, ' & ')), join(directives, ' '), block(fields)], ' '); + }, + InterfaceTypeExtension: function InterfaceTypeExtension(_ref35) { + var name = _ref35.name, + directives = _ref35.directives, + fields = _ref35.fields; + return join(['extend interface', name, join(directives, ' '), block(fields)], ' '); + }, + UnionTypeExtension: function UnionTypeExtension(_ref36) { + var name = _ref36.name, + directives = _ref36.directives, + types = _ref36.types; + return join(['extend union', name, join(directives, ' '), types && types.length !== 0 ? '= ' + join(types, ' | ') : ''], ' '); + }, + EnumTypeExtension: function EnumTypeExtension(_ref37) { + var name = _ref37.name, + directives = _ref37.directives, + values = _ref37.values; + return join(['extend enum', name, join(directives, ' '), block(values)], ' '); + }, + InputObjectTypeExtension: function InputObjectTypeExtension(_ref38) { + var name = _ref38.name, + directives = _ref38.directives, + fields = _ref38.fields; + return join(['extend input', name, join(directives, ' '), block(fields)], ' '); + } +}; + +function addDescription(cb) { + return function (node) { + return join([node.description, cb(node)], '\n'); + }; +} +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + */ + + +function join(maybeArray, separator) { + return maybeArray ? maybeArray.filter(function (x) { + return x; + }).join(separator || '') : ''; +} +/** + * Given array, print each item on its own line, wrapped in an + * indented "{ }" block. + */ + + +function block(array) { + return array && array.length !== 0 ? '{\n' + indent(join(array, '\n')) + '\n}' : ''; +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise + * print an empty string. + */ + + +function wrap(start, maybeString, end) { + return maybeString ? start + maybeString + (end || '') : ''; +} + +function indent(maybeString) { + return maybeString && ' ' + maybeString.replace(/\n/g, '\n '); +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + */ + + +function printBlockString(value, isDescription) { + var escaped = value.replace(/"""/g, '\\"""'); + return (value[0] === ' ' || value[0] === '\t') && value.indexOf('\n') === -1 ? "\"\"\"".concat(escaped.replace(/"$/, '"\n'), "\"\"\"") : "\"\"\"\n".concat(isDescription ? escaped : indent(escaped), "\n\"\"\""); +} \ No newline at end of file diff --git a/node_modules/graphql/language/source.js b/node_modules/graphql/language/source.js new file mode 100644 index 00000000..388bc90c --- /dev/null +++ b/node_modules/graphql/language/source.js @@ -0,0 +1,43 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Source = void 0; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +var Source = function Source(body, name, locationOffset) { + _defineProperty(this, "body", void 0); + + _defineProperty(this, "name", void 0); + + _defineProperty(this, "locationOffset", void 0); + + this.body = body; + this.name = name || 'GraphQL request'; + this.locationOffset = locationOffset || { + line: 1, + column: 1 + }; + !(this.locationOffset.line > 0) ? (0, _invariant.default)(0, 'line in locationOffset is 1-indexed and must be positive') : void 0; + !(this.locationOffset.column > 0) ? (0, _invariant.default)(0, 'column in locationOffset is 1-indexed and must be positive') : void 0; +}; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.Source = Source; +(0, _defineToStringTag.default)(Source); \ No newline at end of file diff --git a/node_modules/graphql/language/source.js.flow b/node_modules/graphql/language/source.js.flow new file mode 100644 index 00000000..94a875fc --- /dev/null +++ b/node_modules/graphql/language/source.js.flow @@ -0,0 +1,47 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import defineToStringTag from '../jsutils/defineToStringTag'; + +type Location = {| + line: number, + column: number, +|}; + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +export class Source { + body: string; + name: string; + locationOffset: Location; + + constructor(body: string, name?: string, locationOffset?: Location): void { + this.body = body; + this.name = name || 'GraphQL request'; + this.locationOffset = locationOffset || { line: 1, column: 1 }; + invariant( + this.locationOffset.line > 0, + 'line in locationOffset is 1-indexed and must be positive', + ); + invariant( + this.locationOffset.column > 0, + 'column in locationOffset is 1-indexed and must be positive', + ); + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(Source); diff --git a/node_modules/graphql/language/source.mjs b/node_modules/graphql/language/source.mjs new file mode 100644 index 00000000..fd1425e0 --- /dev/null +++ b/node_modules/graphql/language/source.mjs @@ -0,0 +1,39 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import defineToStringTag from '../jsutils/defineToStringTag'; + +/** + * A representation of source input to GraphQL. + * `name` and `locationOffset` are optional. They are useful for clients who + * store GraphQL documents in source files; for example, if the GraphQL input + * starts at line 40 in a file named Foo.graphql, it might be useful for name to + * be "Foo.graphql" and location to be `{ line: 40, column: 0 }`. + * line and column in locationOffset are 1-indexed + */ +export var Source = function Source(body, name, locationOffset) { + _defineProperty(this, "body", void 0); + + _defineProperty(this, "name", void 0); + + _defineProperty(this, "locationOffset", void 0); + + this.body = body; + this.name = name || 'GraphQL request'; + this.locationOffset = locationOffset || { + line: 1, + column: 1 + }; + !(this.locationOffset.line > 0) ? invariant(0, 'line in locationOffset is 1-indexed and must be positive') : void 0; + !(this.locationOffset.column > 0) ? invariant(0, 'column in locationOffset is 1-indexed and must be positive') : void 0; +}; // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(Source); \ No newline at end of file diff --git a/node_modules/graphql/language/visitor.js b/node_modules/graphql/language/visitor.js new file mode 100644 index 00000000..3da1fb63 --- /dev/null +++ b/node_modules/graphql/language/visitor.js @@ -0,0 +1,450 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.visit = visit; +exports.visitInParallel = visitInParallel; +exports.visitWithTypeInfo = visitWithTypeInfo; +exports.getVisitFn = getVisitFn; +exports.BREAK = exports.QueryDocumentKeys = void 0; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +exports.QueryDocumentKeys = QueryDocumentKeys; +var BREAK = {}; +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ + +exports.BREAK = BREAK; + +function visit(root, visitor) { + var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; + + /* eslint-disable no-undef-init */ + var stack = undefined; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var node = undefined; + var key = undefined; + var parent = undefined; + var path = []; + var ancestors = []; + var newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + var isLeaving = index === keys.length; + var isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + + for (var k in node) { + if (node.hasOwnProperty(k)) { + clone[k] = node[k]; + } + } + + node = clone; + } + + var editOffset = 0; + + for (var ii = 0; ii < edits.length; ii++) { + var editKey = edits[ii][0]; + var editValue = edits[ii][1]; + + if (inArray) { + editKey -= editOffset; + } + + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? inArray ? index : keys[index] : undefined; + node = parent ? parent[key] : newRoot; + + if (node === null || node === undefined) { + continue; + } + + if (parent) { + path.push(key); + } + } + + var result = void 0; + + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error('Invalid AST Node: ' + (0, _inspect.default)(node)); + } + + var visitFn = getVisitFn(visitor, node.kind, isLeaving); + + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { + inArray: inArray, + index: index, + keys: keys, + edits: edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] || []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +function isNode(maybeNode) { + return Boolean(maybeNode && typeof maybeNode.kind === 'string'); +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + + +function visitInParallel(visitors) { + var skipping = new Array(visitors.length); + return { + enter: function enter(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave: function leave(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + true); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + + +function visitWithTypeInfo(typeInfo, visitor) { + return { + enter: function enter(node) { + typeInfo.enter(node); + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitor, arguments); + + if (result !== undefined) { + typeInfo.leave(node); + + if (isNode(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + leave: function leave(node) { + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + true); + var result; + + if (fn) { + result = fn.apply(visitor, arguments); + } + + typeInfo.leave(node); + return result; + } + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ + + +function getVisitFn(visitor, kind, isLeaving) { + var kindVisitor = visitor[kind]; + + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + + var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; + + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + var specificVisitor = isLeaving ? visitor.leave : visitor.enter; + + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + + var specificKindVisitor = specificVisitor[kind]; + + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/language/visitor.js.flow b/node_modules/graphql/language/visitor.js.flow new file mode 100644 index 00000000..ab5839ad --- /dev/null +++ b/node_modules/graphql/language/visitor.js.flow @@ -0,0 +1,479 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import type { ASTNode, ASTKindToNode } from './ast'; +import type { TypeInfo } from '../utilities/TypeInfo'; + +/** + * A visitor is provided to visit, it contains the collection of + * relevant functions to be called during the visitor's traversal. + */ +export type ASTVisitor = Visitor; +export type Visitor> = + | EnterLeave< + | VisitFn + | ShapeMap(Node) => VisitFn>, + > + | ShapeMap< + KindToNode, + (Node) => VisitFn | EnterLeave>, + >; +type EnterLeave = {| +enter?: T, +leave?: T |}; +type ShapeMap = $Shape<$ObjMap>; + +/** + * A visitor is comprised of visit functions, which are called on each node + * during the visitor's traversal. + */ +export type VisitFn = ( + // The current node being visiting. + node: TVisitedNode, + // The index or key to this node from the parent node or Array. + key: string | number | void, + // The parent immediately above this node, which may be an Array. + parent: TAnyNode | $ReadOnlyArray | void, + // The key path to get to this node from the root node. + path: $ReadOnlyArray, + // All nodes and Arrays visited before reaching parent of this node. + // These correspond to array indices in `path`. + // Note: ancestors includes arrays which contain the parent of visited node. + ancestors: $ReadOnlyArray>, +) => any; + +/** + * A KeyMap describes each the traversable properties of each kind of node. + */ +export type VisitorKeyMap = $ObjMap< + KindToNode, + (T) => $ReadOnlyArray<$Keys>, +>; + +export const QueryDocumentKeys = { + Name: [], + + Document: ['definitions'], + OperationDefinition: [ + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet', + ], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: [ + 'name', + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet', + ], + + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + + Directive: ['name', 'arguments'], + + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + + SchemaDefinition: ['directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives', + ], + InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + + SchemaExtension: ['directives', 'operationTypes'], + + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'], +}; + +export const BREAK = {}; + +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ +export function visit( + root: ASTNode, + visitor: Visitor, + visitorKeys: VisitorKeyMap = QueryDocumentKeys, +): any { + /* eslint-disable no-undef-init */ + let stack: any = undefined; + let inArray = Array.isArray(root); + let keys: any = [root]; + let index = -1; + let edits = []; + let node: any = undefined; + let key: any = undefined; + let parent: any = undefined; + const path: any = []; + const ancestors = []; + let newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + const clone = {}; + for (const k in node) { + if (node.hasOwnProperty(k)) { + clone[k] = node[k]; + } + } + node = clone; + } + let editOffset = 0; + for (let ii = 0; ii < edits.length; ii++) { + let editKey: any = edits[ii][0]; + const editValue = edits[ii][1]; + if (inArray) { + editKey -= editOffset; + } + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? (inArray ? index : keys[index]) : undefined; + node = parent ? parent[key] : newRoot; + if (node === null || node === undefined) { + continue; + } + if (parent) { + path.push(key); + } + } + + let result; + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error('Invalid AST Node: ' + inspect(node)); + } + const visitFn = getVisitFn(visitor, node.kind, isLeaving); + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { inArray, index, keys, edits, prev: stack }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] || []; + index = -1; + edits = []; + if (parent) { + ancestors.push(parent); + } + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +function isNode(maybeNode): boolean %checks { + return Boolean(maybeNode && typeof maybeNode.kind === 'string'); +} + +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ +export function visitInParallel( + visitors: Array>, +): Visitor { + const skipping = new Array(visitors.length); + + return { + enter(node) { + for (let i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ false); + if (fn) { + const result = fn.apply(visitors[i], arguments); + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave(node) { + for (let i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + const fn = getVisitFn(visitors[i], node.kind, /* isLeaving */ true); + if (fn) { + const result = fn.apply(visitors[i], arguments); + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; +} + +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ +export function visitWithTypeInfo( + typeInfo: TypeInfo, + visitor: Visitor, +): Visitor { + return { + enter(node) { + typeInfo.enter(node); + const fn = getVisitFn(visitor, node.kind, /* isLeaving */ false); + if (fn) { + const result = fn.apply(visitor, arguments); + if (result !== undefined) { + typeInfo.leave(node); + if (isNode(result)) { + typeInfo.enter(result); + } + } + return result; + } + }, + leave(node) { + const fn = getVisitFn(visitor, node.kind, /* isLeaving */ true); + let result; + if (fn) { + result = fn.apply(visitor, arguments); + } + typeInfo.leave(node); + return result; + }, + }; +} + +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ +export function getVisitFn( + visitor: Visitor, + kind: string, + isLeaving: boolean, +): ?VisitFn { + const kindVisitor = visitor[kind]; + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + const kindSpecificVisitor = isLeaving + ? kindVisitor.leave + : kindVisitor.enter; + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + const specificVisitor = isLeaving ? visitor.leave : visitor.enter; + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + const specificKindVisitor = specificVisitor[kind]; + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} diff --git a/node_modules/graphql/language/visitor.mjs b/node_modules/graphql/language/visitor.mjs new file mode 100644 index 00000000..01cc2580 --- /dev/null +++ b/node_modules/graphql/language/visitor.mjs @@ -0,0 +1,431 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +export var QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: ['name', 'variableDefinitions', 'directives', 'selectionSet'], + VariableDefinition: ['variable', 'type', 'defaultValue', 'directives'], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: ['name', // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + 'variableDefinitions', 'typeCondition', 'directives', 'selectionSet'], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: ['description', 'name', 'interfaces', 'directives', 'fields'], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: ['description', 'name', 'type', 'defaultValue', 'directives'], + InterfaceTypeDefinition: ['description', 'name', 'directives', 'fields'], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: ['description', 'name', 'arguments', 'locations'], + SchemaExtension: ['directives', 'operationTypes'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'] +}; +export var BREAK = {}; +/** + * visit() will walk through an AST using a depth first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * + * const editedAST = visit(ast, { + * enter(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: skip visiting this node + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * }, + * leave(node, key, parent, path, ancestors) { + * // @return + * // undefined: no action + * // false: no action + * // visitor.BREAK: stop visiting altogether + * // null: delete this node + * // any value: replace this node with the returned value + * } + * }); + * + * Alternatively to providing enter() and leave() functions, a visitor can + * instead provide functions named the same as the kinds of AST nodes, or + * enter/leave visitors at a named key, leading to four permutations of + * visitor API: + * + * 1) Named visitors triggered when entering a node a specific kind. + * + * visit(ast, { + * Kind(node) { + * // enter the "Kind" node + * } + * }) + * + * 2) Named visitors that trigger upon entering and leaving a node of + * a specific kind. + * + * visit(ast, { + * Kind: { + * enter(node) { + * // enter the "Kind" node + * } + * leave(node) { + * // leave the "Kind" node + * } + * } + * }) + * + * 3) Generic visitors that trigger upon entering and leaving any node. + * + * visit(ast, { + * enter(node) { + * // enter any node + * }, + * leave(node) { + * // leave any node + * } + * }) + * + * 4) Parallel visitors for entering and leaving nodes of a specific kind. + * + * visit(ast, { + * enter: { + * Kind(node) { + * // enter the "Kind" node + * } + * }, + * leave: { + * Kind(node) { + * // leave the "Kind" node + * } + * } + * }) + */ + +export function visit(root, visitor) { + var visitorKeys = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QueryDocumentKeys; + + /* eslint-disable no-undef-init */ + var stack = undefined; + var inArray = Array.isArray(root); + var keys = [root]; + var index = -1; + var edits = []; + var node = undefined; + var key = undefined; + var parent = undefined; + var path = []; + var ancestors = []; + var newRoot = root; + /* eslint-enable no-undef-init */ + + do { + index++; + var isLeaving = index === keys.length; + var isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + } else { + var clone = {}; + + for (var k in node) { + if (node.hasOwnProperty(k)) { + clone[k] = node[k]; + } + } + + node = clone; + } + + var editOffset = 0; + + for (var ii = 0; ii < edits.length; ii++) { + var editKey = edits[ii][0]; + var editValue = edits[ii][1]; + + if (inArray) { + editKey -= editOffset; + } + + if (inArray && editValue === null) { + node.splice(editKey, 1); + editOffset++; + } else { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else { + key = parent ? inArray ? index : keys[index] : undefined; + node = parent ? parent[key] : newRoot; + + if (node === null || node === undefined) { + continue; + } + + if (parent) { + path.push(key); + } + } + + var result = void 0; + + if (!Array.isArray(node)) { + if (!isNode(node)) { + throw new Error('Invalid AST Node: ' + inspect(node)); + } + + var visitFn = getVisitFn(visitor, node.kind, isLeaving); + + if (visitFn) { + result = visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + stack = { + inArray: inArray, + index: index, + keys: keys, + edits: edits, + prev: stack + }; + inArray = Array.isArray(node); + keys = inArray ? node : visitorKeys[node.kind] || []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + newRoot = edits[edits.length - 1][1]; + } + + return newRoot; +} + +function isNode(maybeNode) { + return Boolean(maybeNode && typeof maybeNode.kind === 'string'); +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + */ + + +export function visitInParallel(visitors) { + var skipping = new Array(visitors.length); + return { + enter: function enter(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + } + }, + leave: function leave(node) { + for (var i = 0; i < visitors.length; i++) { + if (!skipping[i]) { + var fn = getVisitFn(visitors[i], node.kind, + /* isLeaving */ + true); + + if (fn) { + var result = fn.apply(visitors[i], arguments); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + } + }; +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + */ + +export function visitWithTypeInfo(typeInfo, visitor) { + return { + enter: function enter(node) { + typeInfo.enter(node); + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + false); + + if (fn) { + var result = fn.apply(visitor, arguments); + + if (result !== undefined) { + typeInfo.leave(node); + + if (isNode(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + leave: function leave(node) { + var fn = getVisitFn(visitor, node.kind, + /* isLeaving */ + true); + var result; + + if (fn) { + result = fn.apply(visitor, arguments); + } + + typeInfo.leave(node); + return result; + } + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. + */ + +export function getVisitFn(visitor, kind, isLeaving) { + var kindVisitor = visitor[kind]; + + if (kindVisitor) { + if (!isLeaving && typeof kindVisitor === 'function') { + // { Kind() {} } + return kindVisitor; + } + + var kindSpecificVisitor = isLeaving ? kindVisitor.leave : kindVisitor.enter; + + if (typeof kindSpecificVisitor === 'function') { + // { Kind: { enter() {}, leave() {} } } + return kindSpecificVisitor; + } + } else { + var specificVisitor = isLeaving ? visitor.leave : visitor.enter; + + if (specificVisitor) { + if (typeof specificVisitor === 'function') { + // { enter() {}, leave() {} } + return specificVisitor; + } + + var specificKindVisitor = specificVisitor[kind]; + + if (typeof specificKindVisitor === 'function') { + // { enter: { Kind() {} }, leave: { Kind() {} } } + return specificKindVisitor; + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/package.json b/node_modules/graphql/package.json new file mode 100644 index 00000000..45f99d5e --- /dev/null +++ b/node_modules/graphql/package.json @@ -0,0 +1,55 @@ +{ + "_args": [ + [ + "graphql@14.0.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "graphql@14.0.2", + "_id": "graphql@14.0.2", + "_inBundle": false, + "_integrity": "sha512-gUC4YYsaiSJT1h40krG3J+USGlwhzNTXSb4IOZljn9ag5Tj+RkoXrWp+Kh7WyE3t1NCfab5kzCuxBIvOMERMXw==", + "_location": "/graphql", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "graphql@14.0.2", + "name": "graphql", + "escapedName": "graphql", + "rawSpec": "14.0.2", + "saveSpec": null, + "fetchSpec": "14.0.2" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/graphql/-/graphql-14.0.2.tgz", + "_spec": "14.0.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/graphql/graphql-js/issues" + }, + "dependencies": { + "iterall": "^1.2.2" + }, + "description": "A Query Language and Runtime which can target any service.", + "engines": { + "node": ">= 6.x" + }, + "homepage": "https://github.com/graphql/graphql-js", + "keywords": [ + "graphql", + "graphql-js" + ], + "license": "MIT", + "main": "index", + "module": "index.mjs", + "name": "graphql", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/graphql/graphql-js.git" + }, + "sideEffects": false, + "version": "14.0.2" +} diff --git a/node_modules/graphql/subscription/asyncIteratorReject.js b/node_modules/graphql/subscription/asyncIteratorReject.js new file mode 100644 index 00000000..8e06da39 --- /dev/null +++ b/node_modules/graphql/subscription/asyncIteratorReject.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = asyncIteratorReject; + +var _iterall = require("iterall"); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Given an error, returns an AsyncIterable which will fail with that error. + * + * Similar to Promise.reject(error) + */ +function asyncIteratorReject(error) { + var isComplete = false; + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + return _defineProperty({ + next: function next() { + var result = isComplete ? Promise.resolve({ + value: undefined, + done: true + }) : Promise.reject(error); + isComplete = true; + return result; + }, + return: function _return() { + isComplete = true; + return Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw() { + isComplete = true; + return Promise.reject(error); + } + }, _iterall.$$asyncIterator, function () { + return this; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/asyncIteratorReject.js.flow b/node_modules/graphql/subscription/asyncIteratorReject.js.flow new file mode 100644 index 00000000..7992dc6e --- /dev/null +++ b/node_modules/graphql/subscription/asyncIteratorReject.js.flow @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { $$asyncIterator } from 'iterall'; + +/** + * Given an error, returns an AsyncIterable which will fail with that error. + * + * Similar to Promise.reject(error) + */ +export default function asyncIteratorReject(error: Error): AsyncIterator { + let isComplete = false; + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + return ({ + next() { + const result = isComplete + ? Promise.resolve({ value: undefined, done: true }) + : Promise.reject(error); + isComplete = true; + return result; + }, + return() { + isComplete = true; + return Promise.resolve({ value: undefined, done: true }); + }, + throw() { + isComplete = true; + return Promise.reject(error); + }, + [$$asyncIterator]() { + return this; + }, + }: any); +} diff --git a/node_modules/graphql/subscription/asyncIteratorReject.mjs b/node_modules/graphql/subscription/asyncIteratorReject.mjs new file mode 100644 index 00000000..e2612cf7 --- /dev/null +++ b/node_modules/graphql/subscription/asyncIteratorReject.mjs @@ -0,0 +1,46 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { $$asyncIterator } from 'iterall'; +/** + * Given an error, returns an AsyncIterable which will fail with that error. + * + * Similar to Promise.reject(error) + */ + +export default function asyncIteratorReject(error) { + var isComplete = false; + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + return _defineProperty({ + next: function next() { + var result = isComplete ? Promise.resolve({ + value: undefined, + done: true + }) : Promise.reject(error); + isComplete = true; + return result; + }, + return: function _return() { + isComplete = true; + return Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw() { + isComplete = true; + return Promise.reject(error); + } + }, $$asyncIterator, function () { + return this; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/index.js b/node_modules/graphql/subscription/index.js new file mode 100644 index 00000000..0b45f008 --- /dev/null +++ b/node_modules/graphql/subscription/index.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "subscribe", { + enumerable: true, + get: function get() { + return _subscribe.subscribe; + } +}); +Object.defineProperty(exports, "createSourceEventStream", { + enumerable: true, + get: function get() { + return _subscribe.createSourceEventStream; + } +}); + +var _subscribe = require("./subscribe"); \ No newline at end of file diff --git a/node_modules/graphql/subscription/index.js.flow b/node_modules/graphql/subscription/index.js.flow new file mode 100644 index 00000000..18831657 --- /dev/null +++ b/node_modules/graphql/subscription/index.js.flow @@ -0,0 +1,10 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { subscribe, createSourceEventStream } from './subscribe'; diff --git a/node_modules/graphql/subscription/index.mjs b/node_modules/graphql/subscription/index.mjs new file mode 100644 index 00000000..a0e36467 --- /dev/null +++ b/node_modules/graphql/subscription/index.mjs @@ -0,0 +1,9 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { subscribe, createSourceEventStream } from './subscribe'; \ No newline at end of file diff --git a/node_modules/graphql/subscription/mapAsyncIterator.js b/node_modules/graphql/subscription/mapAsyncIterator.js new file mode 100644 index 00000000..eec4f902 --- /dev/null +++ b/node_modules/graphql/subscription/mapAsyncIterator.js @@ -0,0 +1,85 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = mapAsyncIterator; + +var _iterall = require("iterall"); + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +function mapAsyncIterator(iterable, callback, rejectCallback) { + var iterator = (0, _iterall.getAsyncIterator)(iterable); + var $return; + var abruptClose; // $FlowFixMe(>=0.68.0) + + if (typeof iterator.return === 'function') { + $return = iterator.return; + + abruptClose = function abruptClose(error) { + var rethrow = function rethrow() { + return Promise.reject(error); + }; + + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + var mapReject; + + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + var reject = rejectCallback; + + mapReject = function mapReject(error) { + return asyncMapValue(error, reject).then(iteratorResult, abruptClose); + }; + } + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult, mapReject); + }, + return: function _return() { + return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw(error) { + // $FlowFixMe(>=0.68.0) + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + + return Promise.reject(error).catch(abruptClose); + } + }, _iterall.$$asyncIterator, function () { + return this; + }); +} + +function asyncMapValue(value, callback) { + return new Promise(function (resolve) { + return resolve(callback(value)); + }); +} + +function iteratorResult(value) { + return { + value: value, + done: false + }; +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/mapAsyncIterator.js.flow b/node_modules/graphql/subscription/mapAsyncIterator.js.flow new file mode 100644 index 00000000..c7a7e23c --- /dev/null +++ b/node_modules/graphql/subscription/mapAsyncIterator.js.flow @@ -0,0 +1,81 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { $$asyncIterator, getAsyncIterator } from 'iterall'; +import type { MaybePromise } from '../jsutils/MaybePromise'; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator( + iterable: AsyncIterable, + callback: T => MaybePromise, + rejectCallback?: any => MaybePromise, +): AsyncGenerator { + const iterator = getAsyncIterator(iterable); + let $return; + let abruptClose; + // $FlowFixMe(>=0.68.0) + if (typeof iterator.return === 'function') { + $return = iterator.return; + abruptClose = error => { + const rethrow = () => Promise.reject(error); + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done + ? result + : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + let mapReject; + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + const reject = rejectCallback; + mapReject = error => + asyncMapValue(error, reject).then(iteratorResult, abruptClose); + } + + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + return ({ + next() { + return iterator.next().then(mapResult, mapReject); + }, + return() { + return $return + ? $return.call(iterator).then(mapResult, mapReject) + : Promise.resolve({ value: undefined, done: true }); + }, + throw(error) { + // $FlowFixMe(>=0.68.0) + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + return Promise.reject(error).catch(abruptClose); + }, + [$$asyncIterator]() { + return this; + }, + }: any); +} + +function asyncMapValue( + value: T, + callback: T => MaybePromise, +): Promise { + return new Promise(resolve => resolve(callback(value))); +} + +function iteratorResult(value: T): IteratorResult { + return { value, done: false }; +} diff --git a/node_modules/graphql/subscription/mapAsyncIterator.mjs b/node_modules/graphql/subscription/mapAsyncIterator.mjs new file mode 100644 index 00000000..fe20bb1d --- /dev/null +++ b/node_modules/graphql/subscription/mapAsyncIterator.mjs @@ -0,0 +1,86 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { $$asyncIterator, getAsyncIterator } from 'iterall'; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + */ +export default function mapAsyncIterator(iterable, callback, rejectCallback) { + var iterator = getAsyncIterator(iterable); + var $return; + var abruptClose; // $FlowFixMe(>=0.68.0) + + if (typeof iterator.return === 'function') { + $return = iterator.return; + + abruptClose = function abruptClose(error) { + var rethrow = function rethrow() { + return Promise.reject(error); + }; + + return $return.call(iterator).then(rethrow, rethrow); + }; + } + + function mapResult(result) { + return result.done ? result : asyncMapValue(result.value, callback).then(iteratorResult, abruptClose); + } + + var mapReject; + + if (rejectCallback) { + // Capture rejectCallback to ensure it cannot be null. + var reject = rejectCallback; + + mapReject = function mapReject(error) { + return asyncMapValue(error, reject).then(iteratorResult, abruptClose); + }; + } + /* TODO: Flow doesn't support symbols as keys: + https://github.com/facebook/flow/issues/3258 */ + + + return _defineProperty({ + next: function next() { + return iterator.next().then(mapResult, mapReject); + }, + return: function _return() { + return $return ? $return.call(iterator).then(mapResult, mapReject) : Promise.resolve({ + value: undefined, + done: true + }); + }, + throw: function _throw(error) { + // $FlowFixMe(>=0.68.0) + if (typeof iterator.throw === 'function') { + return iterator.throw(error).then(mapResult, mapReject); + } + + return Promise.reject(error).catch(abruptClose); + } + }, $$asyncIterator, function () { + return this; + }); +} + +function asyncMapValue(value, callback) { + return new Promise(function (resolve) { + return resolve(callback(value)); + }); +} + +function iteratorResult(value) { + return { + value: value, + done: false + }; +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/subscribe.js b/node_modules/graphql/subscription/subscribe.js new file mode 100644 index 00000000..c0134cdb --- /dev/null +++ b/node_modules/graphql/subscription/subscribe.js @@ -0,0 +1,151 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.subscribe = subscribe; +exports.createSourceEventStream = createSourceEventStream; + +var _iterall = require("iterall"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _GraphQLError = require("../error/GraphQLError"); + +var _locatedError = require("../error/locatedError"); + +var _execute = require("../execution/execute"); + +var _mapAsyncIterator = _interopRequireDefault(require("./mapAsyncIterator")); + +var _getOperationRootType = require("../utilities/getOperationRootType"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? subscribeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.subscribeFieldResolver) : subscribeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver); +} +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ + + +function reportGraphQLError(error) { + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error] + }; + } + + throw error; +} + +function subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + var mapSourceToResponse = function mapSourceToResponse(payload) { + return (0, _execute.execute)(schema, document, payload, contextValue, variableValues, operationName, fieldResolver); + }; // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + + + return sourcePromise.then(function (resultOrStream) { + return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used. + (0, _iterall.isAsyncIterable)(resultOrStream) ? (0, _mapAsyncIterator.default)(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream + ); + }, reportGraphQLError); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + +function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); + + try { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + var exeContext = (0, _execute.buildExecutionContext)(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return Promise.resolve({ + errors: exeContext + }); + } + + var type = (0, _getOperationRootType.getOperationRootType)(schema, exeContext.operation); + var fields = (0, _execute.collectFields)(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null)); + var responseNames = Object.keys(fields); + var responseName = responseNames[0]; + var fieldNodes = fields[responseName]; + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = (0, _execute.getFieldDef)(schema, type, fieldName); + + if (!fieldDef) { + throw new _GraphQLError.GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes); + } // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + + var resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + var path = (0, _execute.addPath)(undefined, responseName); + var info = (0, _execute.buildResolveInfo)(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + + var result = (0, _execute.resolveFieldValueOrError)(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type. + + return Promise.resolve(result).then(function (eventStream) { + // If eventStream is an Error, rethrow a located error. + if (eventStream instanceof Error) { + throw (0, _locatedError.locatedError)(eventStream, fieldNodes, (0, _execute.responsePathAsArray)(path)); + } // Assert field returned an event stream, otherwise yield an error. + + + if ((0, _iterall.isAsyncIterable)(eventStream)) { + // Note: isAsyncIterable above ensures this will be correct. + return eventStream; + } + + throw new Error('Subscription field must return Async Iterable. Received: ' + (0, _inspect.default)(eventStream)); + }); + } catch (error) { + return Promise.reject(error); + } +} \ No newline at end of file diff --git a/node_modules/graphql/subscription/subscribe.js.flow b/node_modules/graphql/subscription/subscribe.js.flow new file mode 100644 index 00000000..4b2e74ac --- /dev/null +++ b/node_modules/graphql/subscription/subscribe.js.flow @@ -0,0 +1,289 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { isAsyncIterable } from 'iterall'; +import inspect from '../jsutils/inspect'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import { + addPath, + assertValidExecutionArguments, + buildExecutionContext, + buildResolveInfo, + collectFields, + execute, + getFieldDef, + resolveFieldValueOrError, + responsePathAsArray, +} from '../execution/execute'; +import type { GraphQLSchema } from '../type/schema'; +import mapAsyncIterator from './mapAsyncIterator'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import type { ExecutionResult } from '../execution/execute'; +import type { DocumentNode } from '../language/ast'; +import type { GraphQLFieldResolver } from '../type/definition'; +import { getOperationRootType } from '../utilities/getOperationRootType'; + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (client error). The promise will be rejected if a + * server error occurs. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ +declare function subscribe( + {| + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, + subscribeFieldResolver?: ?GraphQLFieldResolver, + |}, + ..._: [] +): Promise | ExecutionResult>; +/* eslint-disable no-redeclare */ +declare function subscribe( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ?ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, + subscribeFieldResolver?: ?GraphQLFieldResolver, +): Promise | ExecutionResult>; +export function subscribe( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, +) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 + ? subscribeImpl( + argsOrSchema.schema, + argsOrSchema.document, + argsOrSchema.rootValue, + argsOrSchema.contextValue, + argsOrSchema.variableValues, + argsOrSchema.operationName, + argsOrSchema.fieldResolver, + argsOrSchema.subscribeFieldResolver, + ) + : subscribeImpl( + argsOrSchema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, + ); +} + +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ +function reportGraphQLError(error) { + if (error instanceof GraphQLError) { + return { errors: [error] }; + } + throw error; +} + +function subscribeImpl( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + subscribeFieldResolver, +) { + const sourcePromise = createSourceEventStream( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + subscribeFieldResolver, + ); + + // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + const mapSourceToResponse = payload => + execute( + schema, + document, + payload, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + return sourcePromise.then( + resultOrStream => + // Note: Flow can't refine isAsyncIterable, so explicit casts are used. + isAsyncIterable(resultOrStream) + ? mapAsyncIterator( + ((resultOrStream: any): AsyncIterable), + mapSourceToResponse, + reportGraphQLError, + ) + : ((resultOrStream: any): ExecutionResult), + reportGraphQLError, + ); +} + +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ +export function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: mixed, + contextValue?: mixed, + variableValues?: ObjMap, + operationName?: ?string, + fieldResolver?: ?GraphQLFieldResolver, +): Promise | ExecutionResult> { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + assertValidExecutionArguments(schema, document, variableValues); + + try { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + const exeContext = buildExecutionContext( + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + ); + + // Return early errors if execution context failed. + if (Array.isArray(exeContext)) { + return Promise.resolve({ errors: exeContext }); + } + + const type = getOperationRootType(schema, exeContext.operation); + const fields = collectFields( + exeContext, + type, + exeContext.operation.selectionSet, + Object.create(null), + Object.create(null), + ); + const responseNames = Object.keys(fields); + const responseName = responseNames[0]; + const fieldNodes = fields[responseName]; + const fieldNode = fieldNodes[0]; + const fieldName = fieldNode.name.value; + const fieldDef = getFieldDef(schema, type, fieldName); + + if (!fieldDef) { + throw new GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + fieldNodes, + ); + } + + // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + const resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + + const path = addPath(undefined, responseName); + + const info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); + + // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + const result = resolveFieldValueOrError( + exeContext, + fieldDef, + fieldNodes, + resolveFn, + rootValue, + info, + ); + + // Coerce to Promise for easier error handling and consistent return type. + return Promise.resolve(result).then(eventStream => { + // If eventStream is an Error, rethrow a located error. + if (eventStream instanceof Error) { + throw locatedError(eventStream, fieldNodes, responsePathAsArray(path)); + } + + // Assert field returned an event stream, otherwise yield an error. + if (isAsyncIterable(eventStream)) { + // Note: isAsyncIterable above ensures this will be correct. + return ((eventStream: any): AsyncIterable); + } + throw new Error( + 'Subscription field must return Async Iterable. Received: ' + + inspect(eventStream), + ); + }); + } catch (error) { + return Promise.reject(error); + } +} diff --git a/node_modules/graphql/subscription/subscribe.mjs b/node_modules/graphql/subscription/subscribe.mjs new file mode 100644 index 00000000..e2e65caf --- /dev/null +++ b/node_modules/graphql/subscription/subscribe.mjs @@ -0,0 +1,154 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isAsyncIterable } from 'iterall'; +import inspect from '../jsutils/inspect'; +import { GraphQLError } from '../error/GraphQLError'; +import { locatedError } from '../error/locatedError'; +import { addPath, assertValidExecutionArguments, buildExecutionContext, buildResolveInfo, collectFields, execute, getFieldDef, resolveFieldValueOrError, responsePathAsArray } from '../execution/execute'; +import mapAsyncIterator from './mapAsyncIterator'; +import { getOperationRootType } from '../utilities/getOperationRootType'; +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise which resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (client error). The promise will be rejected if a + * server error occurs. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Accepts either an object with named arguments, or individual arguments. + */ + +export function subscribe(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + /* eslint-enable no-redeclare */ + // Extract arguments from object args if provided. + return arguments.length === 1 ? subscribeImpl(argsOrSchema.schema, argsOrSchema.document, argsOrSchema.rootValue, argsOrSchema.contextValue, argsOrSchema.variableValues, argsOrSchema.operationName, argsOrSchema.fieldResolver, argsOrSchema.subscribeFieldResolver) : subscribeImpl(argsOrSchema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver); +} +/** + * This function checks if the error is a GraphQLError. If it is, report it as + * an ExecutionResult, containing only errors and no data. Otherwise treat the + * error as a system-class error and re-throw it. + */ + +function reportGraphQLError(error) { + if (error instanceof GraphQLError) { + return { + errors: [error] + }; + } + + throw error; +} + +function subscribeImpl(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver, subscribeFieldResolver) { + var sourcePromise = createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, subscribeFieldResolver); // For each payload yielded from a subscription, map it over the normal + // GraphQL `execute` function, with `payload` as the rootValue. + // This implements the "MapSourceToResponseEvent" algorithm described in + // the GraphQL specification. The `execute` function provides the + // "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the + // "ExecuteQuery" algorithm, for which `execute` is also used. + + var mapSourceToResponse = function mapSourceToResponse(payload) { + return execute(schema, document, payload, contextValue, variableValues, operationName, fieldResolver); + }; // Resolve the Source Stream, then map every source value to a + // ExecutionResult value as described above. + + + return sourcePromise.then(function (resultOrStream) { + return (// Note: Flow can't refine isAsyncIterable, so explicit casts are used. + isAsyncIterable(resultOrStream) ? mapAsyncIterator(resultOrStream, mapSourceToResponse, reportGraphQLError) : resultOrStream + ); + }, reportGraphQLError); +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise. + * + * If the client-provided invalid arguments, the source stream could not be + * created, or the resolver did not return an AsyncIterable, this function will + * will throw an error, which should be caught and handled by the caller. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + */ + + +export function createSourceEventStream(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver) { + // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + assertValidExecutionArguments(schema, document, variableValues); + + try { + // If a valid context cannot be created due to incorrect arguments, + // this will throw an error. + var exeContext = buildExecutionContext(schema, document, rootValue, contextValue, variableValues, operationName, fieldResolver); // Return early errors if execution context failed. + + if (Array.isArray(exeContext)) { + return Promise.resolve({ + errors: exeContext + }); + } + + var type = getOperationRootType(schema, exeContext.operation); + var fields = collectFields(exeContext, type, exeContext.operation.selectionSet, Object.create(null), Object.create(null)); + var responseNames = Object.keys(fields); + var responseName = responseNames[0]; + var fieldNodes = fields[responseName]; + var fieldNode = fieldNodes[0]; + var fieldName = fieldNode.name.value; + var fieldDef = getFieldDef(schema, type, fieldName); + + if (!fieldDef) { + throw new GraphQLError("The subscription field \"".concat(fieldName, "\" is not defined."), fieldNodes); + } // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + + var resolveFn = fieldDef.subscribe || exeContext.fieldResolver; + var path = addPath(undefined, responseName); + var info = buildResolveInfo(exeContext, fieldDef, fieldNodes, type, path); // resolveFieldValueOrError implements the "ResolveFieldEventStream" + // algorithm from GraphQL specification. It differs from + // "ResolveFieldValue" due to providing a different `resolveFn`. + + var result = resolveFieldValueOrError(exeContext, fieldDef, fieldNodes, resolveFn, rootValue, info); // Coerce to Promise for easier error handling and consistent return type. + + return Promise.resolve(result).then(function (eventStream) { + // If eventStream is an Error, rethrow a located error. + if (eventStream instanceof Error) { + throw locatedError(eventStream, fieldNodes, responsePathAsArray(path)); + } // Assert field returned an event stream, otherwise yield an error. + + + if (isAsyncIterable(eventStream)) { + // Note: isAsyncIterable above ensures this will be correct. + return eventStream; + } + + throw new Error('Subscription field must return Async Iterable. Received: ' + inspect(eventStream)); + }); + } catch (error) { + return Promise.reject(error); + } +} \ No newline at end of file diff --git a/node_modules/graphql/type/definition.js b/node_modules/graphql/type/definition.js new file mode 100644 index 00000000..99ff4a57 --- /dev/null +++ b/node_modules/graphql/type/definition.js @@ -0,0 +1,968 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isType = isType; +exports.assertType = assertType; +exports.isScalarType = isScalarType; +exports.assertScalarType = assertScalarType; +exports.isObjectType = isObjectType; +exports.assertObjectType = assertObjectType; +exports.isInterfaceType = isInterfaceType; +exports.assertInterfaceType = assertInterfaceType; +exports.isUnionType = isUnionType; +exports.assertUnionType = assertUnionType; +exports.isEnumType = isEnumType; +exports.assertEnumType = assertEnumType; +exports.isInputObjectType = isInputObjectType; +exports.assertInputObjectType = assertInputObjectType; +exports.isListType = isListType; +exports.assertListType = assertListType; +exports.isNonNullType = isNonNullType; +exports.assertNonNullType = assertNonNullType; +exports.isInputType = isInputType; +exports.assertInputType = assertInputType; +exports.isOutputType = isOutputType; +exports.assertOutputType = assertOutputType; +exports.isLeafType = isLeafType; +exports.assertLeafType = assertLeafType; +exports.isCompositeType = isCompositeType; +exports.assertCompositeType = assertCompositeType; +exports.isAbstractType = isAbstractType; +exports.assertAbstractType = assertAbstractType; +exports.GraphQLList = GraphQLList; +exports.GraphQLNonNull = GraphQLNonNull; +exports.isWrappingType = isWrappingType; +exports.assertWrappingType = assertWrappingType; +exports.isNullableType = isNullableType; +exports.assertNullableType = assertNullableType; +exports.getNullableType = getNullableType; +exports.isNamedType = isNamedType; +exports.assertNamedType = assertNamedType; +exports.getNamedType = getNamedType; +exports.isRequiredArgument = isRequiredArgument; +exports.isRequiredInputField = isRequiredInputField; +exports.GraphQLInputObjectType = exports.GraphQLEnumType = exports.GraphQLUnionType = exports.GraphQLInterfaceType = exports.GraphQLObjectType = exports.GraphQLScalarType = void 0; + +var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON")); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf")); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _kinds = require("../language/kinds"); + +var _valueFromASTUntyped = require("../utilities/valueFromASTUntyped"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} + +function assertType(type) { + !isType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL type.")) : void 0; + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + + +// eslint-disable-next-line no-redeclare +function isScalarType(type) { + return (0, _instanceOf.default)(type, GraphQLScalarType); +} + +function assertScalarType(type) { + !isScalarType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Scalar type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isObjectType(type) { + return (0, _instanceOf.default)(type, GraphQLObjectType); +} + +function assertObjectType(type) { + !isObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Object type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isInterfaceType(type) { + return (0, _instanceOf.default)(type, GraphQLInterfaceType); +} + +function assertInterfaceType(type) { + !isInterfaceType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Interface type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isUnionType(type) { + return (0, _instanceOf.default)(type, GraphQLUnionType); +} + +function assertUnionType(type) { + !isUnionType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Union type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isEnumType(type) { + return (0, _instanceOf.default)(type, GraphQLEnumType); +} + +function assertEnumType(type) { + !isEnumType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Enum type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isInputObjectType(type) { + return (0, _instanceOf.default)(type, GraphQLInputObjectType); +} + +function assertInputObjectType(type) { + !isInputObjectType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Input Object type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isListType(type) { + return (0, _instanceOf.default)(type, GraphQLList); +} + +function assertListType(type) { + !isListType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL List type.")) : void 0; + return type; +} + +// eslint-disable-next-line no-redeclare +function isNonNullType(type) { + return (0, _instanceOf.default)(type, GraphQLNonNull); +} + +function assertNonNullType(type) { + !isNonNullType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL Non-Null type.")) : void 0; + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + + +function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} + +function assertInputType(type) { + !isInputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL input type.")) : void 0; + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + + +function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} + +function assertOutputType(type) { + !isOutputType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL output type.")) : void 0; + return type; +} +/** + * These types may describe types which may be leaf values. + */ + + +function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} + +function assertLeafType(type) { + !isLeafType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL leaf type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + + +function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} + +function assertCompositeType(type) { + !isCompositeType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL composite type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + + +function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} + +function assertAbstractType(type) { + !isAbstractType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL abstract type.")) : void 0; + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: GraphQLList(PersonType) }, + * children: { type: GraphQLList(PersonType) }, + * }) + * }) + * + */ + + +// eslint-disable-next-line no-redeclare +function GraphQLList(ofType) { + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} // Need to cast through any to alter the prototype. + + +GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +(0, _defineToJSON.default)(GraphQLList); +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +// eslint-disable-next-line no-redeclare +function GraphQLNonNull(ofType) { + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} // Need to cast through any to alter the prototype. + + +GraphQLNonNull.prototype.toString = function toString() { + return String(this.ofType) + '!'; +}; + +(0, _defineToJSON.default)(GraphQLNonNull); +/** + * These types wrap and modify other types + */ + +function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} + +function assertWrappingType(type) { + !isWrappingType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL wrapping type.")) : void 0; + return type; +} +/** + * These types can all accept null as a value. + */ + + +function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} + +function assertNullableType(type) { + !isNullableType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL nullable type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + + +function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + + +function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} + +function assertNamedType(type) { + !isNamedType(type) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(type), " to be a GraphQL named type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + + +function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + + +function resolveThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ + + +var GraphQLScalarType = +/*#__PURE__*/ +function () { + function GraphQLScalarType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "serialize", void 0); + + _defineProperty(this, "parseValue", void 0); + + _defineProperty(this, "parseLiteral", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + this.name = config.name; + this.description = config.description; + this.serialize = config.serialize; + + this.parseValue = config.parseValue || function (value) { + return value; + }; + + this.parseLiteral = config.parseLiteral || _valueFromASTUntyped.valueFromASTUntyped; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(typeof config.serialize === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar ") + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.') : void 0; + + if (config.parseValue || config.parseLiteral) { + !(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" ") + 'functions.') : void 0; + } + } + + var _proto = GraphQLScalarType.prototype; + + _proto.toString = function toString() { + return this.name; + }; + + return GraphQLScalarType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLScalarType = GraphQLScalarType; +(0, _defineToStringTag.default)(GraphQLScalarType); +(0, _defineToJSON.default)(GraphQLScalarType); + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +var GraphQLObjectType = +/*#__PURE__*/ +function () { + function GraphQLObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "isTypeOf", void 0); + + _defineProperty(this, "_fields", void 0); + + _defineProperty(this, "_interfaces", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.isTypeOf = config.isTypeOf; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(config.isTypeOf == null || typeof config.isTypeOf === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.isTypeOf), ".")) : void 0; + } + + var _proto2 = GraphQLObjectType.prototype; + + _proto2.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto2.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto2.toString = function toString() { + return this.name; + }; + + return GraphQLObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLObjectType = GraphQLObjectType; +(0, _defineToStringTag.default)(GraphQLObjectType); +(0, _defineToJSON.default)(GraphQLObjectType); + +function defineInterfaces(config) { + var interfaces = resolveThunk(config.interfaces) || []; + !Array.isArray(interfaces) ? (0, _invariant.default)(0, "".concat(config.name, " interfaces must be an Array or a function which returns ") + 'an Array.') : void 0; + return interfaces; +} + +function defineFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr = Object.keys(fieldMap); + + var _loop = function _loop() { + var fieldName = _arr[_i]; + var fieldConfig = fieldMap[fieldName]; + !isPlainObj(fieldConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object")) : void 0; + !!fieldConfig.hasOwnProperty('isDeprecated') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" ") + 'instead of "isDeprecated".') : void 0; + + var field = _objectSpread({}, fieldConfig, { + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName + }); + + !(field.resolve == null || typeof field.resolve === 'function') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat((0, _inspect.default)(field.resolve), ".")) : void 0; + var argsConfig = fieldConfig.args; + + if (!argsConfig) { + field.args = []; + } else { + !isPlainObj(argsConfig) ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument ") + 'names as keys.') : void 0; + field.args = Object.keys(argsConfig).map(function (argName) { + var arg = argsConfig[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + + resultFieldMap[fieldName] = field; + }; + + for (var _i = 0; _i < _arr.length; _i++) { + _loop(); + } + + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && _typeof(obj) === 'object' && !Array.isArray(obj); +} + +function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +var GraphQLInterfaceType = +/*#__PURE__*/ +function () { + function GraphQLInterfaceType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._fields = defineFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0; + } + + var _proto3 = GraphQLInterfaceType.prototype; + + _proto3.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto3.toString = function toString() { + return this.name; + }; + + return GraphQLInterfaceType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLInterfaceType = GraphQLInterfaceType; +(0, _defineToStringTag.default)(GraphQLInterfaceType); +(0, _defineToJSON.default)(GraphQLInterfaceType); + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +var GraphQLUnionType = +/*#__PURE__*/ +function () { + function GraphQLUnionType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_types", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._types = defineTypes.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? (0, _invariant.default)(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat((0, _inspect.default)(config.resolveType), ".")) : void 0; + } + + var _proto4 = GraphQLUnionType.prototype; + + _proto4.getTypes = function getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + }; + + _proto4.toString = function toString() { + return this.name; + }; + + return GraphQLUnionType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLUnionType = GraphQLUnionType; +(0, _defineToStringTag.default)(GraphQLUnionType); +(0, _defineToJSON.default)(GraphQLUnionType); + +function defineTypes(config) { + var types = resolveThunk(config.types) || []; + !Array.isArray(types) ? (0, _invariant.default)(0, 'Must provide Array of types or a function which returns ' + "such an array for Union ".concat(config.name, ".")) : void 0; + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +var GraphQLEnumType +/* */ += +/*#__PURE__*/ +function () { + function GraphQLEnumType(config + /* */ + ) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_values", void 0); + + _defineProperty(this, "_valueLookup", void 0); + + _defineProperty(this, "_nameLookup", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._values = defineEnumValues(this, config.values); + this._valueLookup = new Map(this._values.map(function (enumValue) { + return [enumValue.value, enumValue]; + })); + this._nameLookup = (0, _keyMap.default)(this._values, function (value) { + return value.name; + }); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + } + + var _proto5 = GraphQLEnumType.prototype; + + _proto5.getValues = function getValues() { + return this._values; + }; + + _proto5.getValue = function getValue(name) { + return this._nameLookup[name]; + }; + + _proto5.serialize = function serialize(value + /* T */ + ) { + var enumValue = this._valueLookup.get(value); + + if (enumValue) { + return enumValue.name; + } + }; + + _proto5.parseValue = function parseValue(value) + /* T */ + { + if (typeof value === 'string') { + var enumValue = this.getValue(value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.parseLiteral = function parseLiteral(valueNode, _variables) + /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind === _kinds.Kind.ENUM) { + var enumValue = this.getValue(valueNode.value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.toString = function toString() { + return this.name; + }; + + return GraphQLEnumType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLEnumType = GraphQLEnumType; +(0, _defineToStringTag.default)(GraphQLEnumType); +(0, _defineToJSON.default)(GraphQLEnumType); + +function defineEnumValues(type, valueMap +/* */ +) { + !isPlainObj(valueMap) ? (0, _invariant.default)(0, "".concat(type.name, " values must be an object with value names as keys.")) : void 0; + return Object.keys(valueMap).map(function (valueName) { + var value = valueMap[valueName]; + !isPlainObj(value) ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat((0, _inspect.default)(value), ".")) : void 0; + !!value.hasOwnProperty('isDeprecated') ? (0, _invariant.default)(0, "".concat(type.name, ".").concat(valueName, " should provide \"deprecationReason\" instead ") + 'of "isDeprecated".') : void 0; + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + astNode: value.astNode, + value: value.hasOwnProperty('value') ? value.value : valueName + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: GraphQLNonNull(GraphQLFloat) }, + * lon: { type: GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +var GraphQLInputObjectType = +/*#__PURE__*/ +function () { + function GraphQLInputObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._fields = defineInputFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? (0, _invariant.default)(0, 'Must provide name.') : void 0; + } + + var _proto6 = GraphQLInputObjectType.prototype; + + _proto6.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto6.toString = function toString() { + return this.name; + }; + + return GraphQLInputObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLInputObjectType = GraphQLInputObjectType; +(0, _defineToStringTag.default)(GraphQLInputObjectType); +(0, _defineToJSON.default)(GraphQLInputObjectType); + +function defineInputFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? (0, _invariant.default)(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr2 = Object.keys(fieldMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var fieldName = _arr2[_i2]; + + var field = _objectSpread({}, fieldMap[fieldName], { + name: fieldName + }); + + !!field.hasOwnProperty('resolve') ? (0, _invariant.default)(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but ") + 'Input Types cannot define resolvers.') : void 0; + resultFieldMap[fieldName] = field; + } + + return resultFieldMap; +} + +function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} \ No newline at end of file diff --git a/node_modules/graphql/type/definition.js.flow b/node_modules/graphql/type/definition.js.flow new file mode 100644 index 00000000..675092d0 --- /dev/null +++ b/node_modules/graphql/type/definition.js.flow @@ -0,0 +1,1286 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import defineToJSON from '../jsutils/defineToJSON'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import instanceOf from '../jsutils/instanceOf'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { Kind } from '../language/kinds'; +import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped'; +import type { + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + OperationDefinitionNode, + FieldNode, + FragmentDefinitionNode, + ValueNode, +} from '../language/ast'; +import type { GraphQLSchema } from './schema'; +import type { MaybePromise } from '../jsutils/MaybePromise'; + +// Predicates & Assertions + +/** + * These are all of the possible kinds of types. + */ +export type GraphQLType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; + +export function isType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); +} + +export function assertType(type: mixed): GraphQLType { + invariant(isType(type), `Expected ${inspect(type)} to be a GraphQL type.`); + return type; +} + +/** + * There are predicates for each kind of GraphQL type. + */ + +declare function isScalarType(type: mixed): boolean %checks(type instanceof + GraphQLScalarType); +// eslint-disable-next-line no-redeclare +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} + +export function assertScalarType(type: mixed): GraphQLScalarType { + invariant( + isScalarType(type), + `Expected ${inspect(type)} to be a GraphQL Scalar type.`, + ); + return type; +} + +declare function isObjectType(type: mixed): boolean %checks(type instanceof + GraphQLObjectType); +// eslint-disable-next-line no-redeclare +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} + +export function assertObjectType(type: mixed): GraphQLObjectType { + invariant( + isObjectType(type), + `Expected ${inspect(type)} to be a GraphQL Object type.`, + ); + return type; +} + +declare function isInterfaceType(type: mixed): boolean %checks(type instanceof + GraphQLInterfaceType); +// eslint-disable-next-line no-redeclare +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} + +export function assertInterfaceType(type: mixed): GraphQLInterfaceType { + invariant( + isInterfaceType(type), + `Expected ${inspect(type)} to be a GraphQL Interface type.`, + ); + return type; +} + +declare function isUnionType(type: mixed): boolean %checks(type instanceof + GraphQLUnionType); +// eslint-disable-next-line no-redeclare +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} + +export function assertUnionType(type: mixed): GraphQLUnionType { + invariant( + isUnionType(type), + `Expected ${inspect(type)} to be a GraphQL Union type.`, + ); + return type; +} + +declare function isEnumType(type: mixed): boolean %checks(type instanceof + GraphQLEnumType); +// eslint-disable-next-line no-redeclare +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} + +export function assertEnumType(type: mixed): GraphQLEnumType { + invariant( + isEnumType(type), + `Expected ${inspect(type)} to be a GraphQL Enum type.`, + ); + return type; +} + +declare function isInputObjectType(type: mixed): boolean %checks(type instanceof + GraphQLInputObjectType); +// eslint-disable-next-line no-redeclare +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} + +export function assertInputObjectType(type: mixed): GraphQLInputObjectType { + invariant( + isInputObjectType(type), + `Expected ${inspect(type)} to be a GraphQL Input Object type.`, + ); + return type; +} + +declare function isListType(type: mixed): boolean %checks(type instanceof + GraphQLList); +// eslint-disable-next-line no-redeclare +export function isListType(type) { + return instanceOf(type, GraphQLList); +} + +export function assertListType(type: mixed): GraphQLList { + invariant( + isListType(type), + `Expected ${inspect(type)} to be a GraphQL List type.`, + ); + return type; +} + +declare function isNonNullType(type: mixed): boolean %checks(type instanceof + GraphQLNonNull); +// eslint-disable-next-line no-redeclare +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} + +export function assertNonNullType(type: mixed): GraphQLNonNull { + invariant( + isNonNullType(type), + `Expected ${inspect(type)} to be a GraphQL Non-Null type.`, + ); + return type; +} + +/** + * These types may be used as input types for arguments and directives. + */ +export type GraphQLInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList, + >; + +export function isInputType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); +} + +export function assertInputType(type: mixed): GraphQLInputType { + invariant( + isInputType(type), + `Expected ${inspect(type)} to be a GraphQL input type.`, + ); + return type; +} + +/** + * These types may be used as output types as the result of fields. + */ +export type GraphQLOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList, + >; + +export function isOutputType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); +} + +export function assertOutputType(type: mixed): GraphQLOutputType { + invariant( + isOutputType(type), + `Expected ${inspect(type)} to be a GraphQL output type.`, + ); + return type; +} + +/** + * These types may describe types which may be leaf values. + */ +export type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; + +export function isLeafType(type: mixed): boolean %checks { + return isScalarType(type) || isEnumType(type); +} + +export function assertLeafType(type: mixed): GraphQLLeafType { + invariant( + isLeafType(type), + `Expected ${inspect(type)} to be a GraphQL leaf type.`, + ); + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLCompositeType = + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; + +export function isCompositeType(type: mixed): boolean %checks { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} + +export function assertCompositeType(type: mixed): GraphQLCompositeType { + invariant( + isCompositeType(type), + `Expected ${inspect(type)} to be a GraphQL composite type.`, + ); + return type; +} + +/** + * These types may describe the parent context of a selection set. + */ +export type GraphQLAbstractType = GraphQLInterfaceType | GraphQLUnionType; + +export function isAbstractType(type: mixed): boolean %checks { + return isInterfaceType(type) || isUnionType(type); +} + +export function assertAbstractType(type: mixed): GraphQLAbstractType { + invariant( + isAbstractType(type), + `Expected ${inspect(type)} to be a GraphQL abstract type.`, + ); + return type; +} + +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: GraphQLList(PersonType) }, + * children: { type: GraphQLList(PersonType) }, + * }) + * }) + * + */ +declare class GraphQLList<+T: GraphQLType> { + +ofType: T; + static (ofType: T): GraphQLList; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +// eslint-disable-next-line no-redeclare +export function GraphQLList(ofType) { + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} + +// Need to cast through any to alter the prototype. +(GraphQLList.prototype: any).toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; +defineToJSON(GraphQLList); + +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +declare class GraphQLNonNull<+T: GraphQLNullableType> { + +ofType: T; + static (ofType: T): GraphQLNonNull; + // Note: constructors cannot be used for covariant types. Drop the "new". + constructor(ofType: GraphQLType): void; +} +// eslint-disable-next-line no-redeclare +export function GraphQLNonNull(ofType) { + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} + +// Need to cast through any to alter the prototype. +(GraphQLNonNull.prototype: any).toString = function toString() { + return String(this.ofType) + '!'; +}; +defineToJSON(GraphQLNonNull); + +/** + * These types wrap and modify other types + */ + +export type GraphQLWrappingType = GraphQLList | GraphQLNonNull; + +export function isWrappingType(type: mixed): boolean %checks { + return isListType(type) || isNonNullType(type); +} + +export function assertWrappingType(type: mixed): GraphQLWrappingType { + invariant( + isWrappingType(type), + `Expected ${inspect(type)} to be a GraphQL wrapping type.`, + ); + return type; +} + +/** + * These types can all accept null as a value. + */ +export type GraphQLNullableType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; + +export function isNullableType(type: mixed): boolean %checks { + return isType(type) && !isNonNullType(type); +} + +export function assertNullableType(type: mixed): GraphQLNullableType { + invariant( + isNullableType(type), + `Expected ${inspect(type)} to be a GraphQL nullable type.`, + ); + return type; +} + +/* eslint-disable no-redeclare */ +declare function getNullableType(type: void | null): void; +declare function getNullableType(type: T): T; +declare function getNullableType(type: GraphQLNonNull): T; +export function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} + +/** + * These named types do not include modifiers like List or NonNull. + */ +export type GraphQLNamedType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; + +export function isNamedType(type: mixed): boolean %checks { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); +} + +export function assertNamedType(type: mixed): GraphQLNamedType { + invariant( + isNamedType(type), + `Expected ${inspect(type)} to be a GraphQL named type.`, + ); + return type; +} + +/* eslint-disable no-redeclare */ +declare function getNamedType(type: void | null): void; +declare function getNamedType(type: GraphQLType): GraphQLNamedType; +export function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + let unwrappedType = type; + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + return unwrappedType; + } +} + +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ +export type Thunk<+T> = (() => T) | T; + +function resolveThunk<+T>(thunk: Thunk): T { + return typeof thunk === 'function' ? thunk() : thunk; +} + +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ +export class GraphQLScalarType { + name: string; + description: ?string; + serialize: GraphQLScalarSerializer<*>; + parseValue: GraphQLScalarValueParser<*>; + parseLiteral: GraphQLScalarLiteralParser<*>; + astNode: ?ScalarTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + + constructor(config: GraphQLScalarTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.serialize = config.serialize; + this.parseValue = config.parseValue || (value => value); + this.parseLiteral = config.parseLiteral || valueFromASTUntyped; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + typeof config.serialize === 'function', + `${this.name} must provide "serialize" function. If this custom Scalar ` + + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + + 'functions are also provided.', + ); + if (config.parseValue || config.parseLiteral) { + invariant( + typeof config.parseValue === 'function' && + typeof config.parseLiteral === 'function', + `${this.name} must provide both "parseValue" and "parseLiteral" ` + + 'functions.', + ); + } + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLScalarType); +defineToJSON(GraphQLScalarType); + +export type GraphQLScalarSerializer = (value: mixed) => ?TExternal; +export type GraphQLScalarValueParser = (value: mixed) => ?TInternal; +export type GraphQLScalarLiteralParser = ( + valueNode: ValueNode, + variables: ?ObjMap, +) => ?TInternal; + +export type GraphQLScalarTypeConfig = {| + name: string, + description?: ?string, + // Serializes an internal value to include in a response. + serialize: GraphQLScalarSerializer, + // Parses an externally provided value to use as an input. + parseValue?: GraphQLScalarValueParser, + // Parses an externally provided literal value to use as an input. + parseLiteral?: GraphQLScalarLiteralParser, + astNode?: ?ScalarTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export class GraphQLObjectType { + name: string; + description: ?string; + astNode: ?ObjectTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + isTypeOf: ?GraphQLIsTypeOfFn<*, *>; + + _fields: Thunk>; + _interfaces: Thunk>; + + constructor(config: GraphQLObjectTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.isTypeOf = config.isTypeOf; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + config.isTypeOf == null || typeof config.isTypeOf === 'function', + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${inspect(config.isTypeOf)}.`, + ); + } + + getFields(): GraphQLFieldMap<*, *> { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + getInterfaces(): Array { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + return this._interfaces; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLObjectType); +defineToJSON(GraphQLObjectType); + +function defineInterfaces( + config: GraphQLObjectTypeConfig<*, *>, +): Array { + const interfaces = resolveThunk(config.interfaces) || []; + invariant( + Array.isArray(interfaces), + `${config.name} interfaces must be an Array or a function which returns ` + + 'an Array.', + ); + return interfaces; +} + +function defineFieldMap( + config: + | GraphQLObjectTypeConfig + | GraphQLInterfaceTypeConfig, +): GraphQLFieldMap { + const fieldMap = resolveThunk(config.fields) || {}; + invariant( + isPlainObj(fieldMap), + `${config.name} fields must be an object with field names as keys or a ` + + 'function which returns such an object.', + ); + + const resultFieldMap = Object.create(null); + for (const fieldName of Object.keys(fieldMap)) { + const fieldConfig = fieldMap[fieldName]; + invariant( + isPlainObj(fieldConfig), + `${config.name}.${fieldName} field config must be an object`, + ); + invariant( + !fieldConfig.hasOwnProperty('isDeprecated'), + `${config.name}.${fieldName} should provide "deprecationReason" ` + + 'instead of "isDeprecated".', + ); + const field = { + ...fieldConfig, + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName, + }; + invariant( + field.resolve == null || typeof field.resolve === 'function', + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${inspect(field.resolve)}.`, + ); + const argsConfig = fieldConfig.args; + if (!argsConfig) { + field.args = []; + } else { + invariant( + isPlainObj(argsConfig), + `${config.name}.${fieldName} args must be an object with argument ` + + 'names as keys.', + ); + field.args = Object.keys(argsConfig).map(argName => { + const arg = argsConfig[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode, + }; + }); + } + resultFieldMap[fieldName] = field; + } + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); +} + +export type GraphQLObjectTypeConfig = {| + name: string, + interfaces?: Thunk>, + fields: Thunk>, + isTypeOf?: ?GraphQLIsTypeOfFn, + description?: ?string, + astNode?: ?ObjectTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +export type GraphQLTypeResolver = ( + value: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => MaybePromise; + +export type GraphQLIsTypeOfFn = ( + source: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => MaybePromise; + +export type GraphQLFieldResolver< + TSource, + TContext, + TArgs = { [argument: string]: any }, +> = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo, +) => mixed; + +export type GraphQLResolveInfo = {| + +fieldName: string, + +fieldNodes: $ReadOnlyArray, + +returnType: GraphQLOutputType, + +parentType: GraphQLObjectType, + +path: ResponsePath, + +schema: GraphQLSchema, + +fragments: ObjMap, + +rootValue: mixed, + +operation: OperationDefinitionNode, + +variableValues: { [variable: string]: mixed }, +|}; + +export type ResponsePath = {| + +prev: ResponsePath | void, + +key: string | number, +|}; + +export type GraphQLFieldConfig< + TSource, + TContext, + TArgs = { [argument: string]: any }, +> = {| + type: GraphQLOutputType, + args?: GraphQLFieldConfigArgumentMap, + resolve?: GraphQLFieldResolver, + subscribe?: GraphQLFieldResolver, + deprecationReason?: ?string, + description?: ?string, + astNode?: ?FieldDefinitionNode, +|}; + +export type GraphQLFieldConfigArgumentMap = ObjMap; + +export type GraphQLArgumentConfig = {| + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +|}; + +export type GraphQLFieldConfigMap = ObjMap< + GraphQLFieldConfig, +>; + +export type GraphQLField< + TSource, + TContext, + TArgs = { [argument: string]: any }, +> = { + name: string, + description: ?string, + type: GraphQLOutputType, + args: Array, + resolve?: GraphQLFieldResolver, + subscribe?: GraphQLFieldResolver, + isDeprecated?: boolean, + deprecationReason?: ?string, + astNode?: ?FieldDefinitionNode, +}; + +export type GraphQLArgument = { + name: string, + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +}; + +export function isRequiredArgument(arg: GraphQLArgument): boolean %checks { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +export type GraphQLFieldMap = ObjMap< + GraphQLField, +>; + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export class GraphQLInterfaceType { + name: string; + description: ?string; + astNode: ?InterfaceTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + resolveType: ?GraphQLTypeResolver<*, *>; + + _fields: Thunk>; + + constructor(config: GraphQLInterfaceTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._fields = defineFieldMap.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + config.resolveType == null || typeof config.resolveType === 'function', + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + + getFields(): GraphQLFieldMap<*, *> { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLInterfaceType); +defineToJSON(GraphQLInterfaceType); + +export type GraphQLInterfaceTypeConfig = {| + name: string, + fields: Thunk>, + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: ?GraphQLTypeResolver, + description?: ?string, + astNode?: ?InterfaceTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export class GraphQLUnionType { + name: string; + description: ?string; + astNode: ?UnionTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + resolveType: ?GraphQLTypeResolver<*, *>; + + _types: Thunk>; + + constructor(config: GraphQLUnionTypeConfig<*, *>): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._types = defineTypes.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + invariant( + config.resolveType == null || typeof config.resolveType === 'function', + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + + getTypes(): Array { + if (typeof this._types === 'function') { + this._types = this._types(); + } + return this._types; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLUnionType); +defineToJSON(GraphQLUnionType); + +function defineTypes( + config: GraphQLUnionTypeConfig<*, *>, +): Array { + const types = resolveThunk(config.types) || []; + invariant( + Array.isArray(types), + 'Must provide Array of types or a function which returns ' + + `such an array for Union ${config.name}.`, + ); + return types; +} + +export type GraphQLUnionTypeConfig = {| + name: string, + types: Thunk>, + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: ?GraphQLTypeResolver, + description?: ?string, + astNode?: ?UnionTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export class GraphQLEnumType /* */ { + name: string; + description: ?string; + astNode: ?EnumTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + + _values: Array */>; + _valueLookup: Map; + _nameLookup: ObjMap; + + constructor(config: GraphQLEnumTypeConfig /* */): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._values = defineEnumValues(this, config.values); + this._valueLookup = new Map( + this._values.map(enumValue => [enumValue.value, enumValue]), + ); + this._nameLookup = keyMap(this._values, value => value.name); + + invariant(typeof config.name === 'string', 'Must provide name.'); + } + + getValues(): Array */> { + return this._values; + } + + getValue(name: string): ?GraphQLEnumValue { + return this._nameLookup[name]; + } + + serialize(value: mixed /* T */): ?string { + const enumValue = this._valueLookup.get(value); + if (enumValue) { + return enumValue.name; + } + } + + parseValue(value: mixed): ?any /* T */ { + if (typeof value === 'string') { + const enumValue = this.getValue(value); + if (enumValue) { + return enumValue.value; + } + } + } + + parseLiteral(valueNode: ValueNode, _variables: ?ObjMap): ?any /* T */ { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind === Kind.ENUM) { + const enumValue = this.getValue(valueNode.value); + if (enumValue) { + return enumValue.value; + } + } + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLEnumType); +defineToJSON(GraphQLEnumType); + +function defineEnumValues( + type: GraphQLEnumType, + valueMap: GraphQLEnumValueConfigMap /* */, +): Array */> { + invariant( + isPlainObj(valueMap), + `${type.name} values must be an object with value names as keys.`, + ); + return Object.keys(valueMap).map(valueName => { + const value = valueMap[valueName]; + invariant( + isPlainObj(value), + `${type.name}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${inspect(value)}.`, + ); + invariant( + !value.hasOwnProperty('isDeprecated'), + `${type.name}.${valueName} should provide "deprecationReason" instead ` + + 'of "isDeprecated".', + ); + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + astNode: value.astNode, + value: value.hasOwnProperty('value') ? value.value : valueName, + }; + }); +} + +export type GraphQLEnumTypeConfig /* */ = {| + name: string, + values: GraphQLEnumValueConfigMap /* */, + description?: ?string, + astNode?: ?EnumTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +export type GraphQLEnumValueConfigMap /* */ = ObjMap< + GraphQLEnumValueConfig /* */, +>; + +export type GraphQLEnumValueConfig /* */ = {| + value?: any /* T */, + deprecationReason?: ?string, + description?: ?string, + astNode?: ?EnumValueDefinitionNode, +|}; + +export type GraphQLEnumValue /* */ = { + name: string, + description: ?string, + isDeprecated?: boolean, + deprecationReason: ?string, + astNode?: ?EnumValueDefinitionNode, + value: any /* T */, +}; + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: GraphQLNonNull(GraphQLFloat) }, + * lon: { type: GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export class GraphQLInputObjectType { + name: string; + description: ?string; + astNode: ?InputObjectTypeDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + + _fields: Thunk; + + constructor(config: GraphQLInputObjectTypeConfig): void { + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._fields = defineInputFieldMap.bind(undefined, config); + invariant(typeof config.name === 'string', 'Must provide name.'); + } + + getFields(): GraphQLInputFieldMap { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + return this._fields; + } + + toString(): string { + return this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLInputObjectType); +defineToJSON(GraphQLInputObjectType); + +function defineInputFieldMap( + config: GraphQLInputObjectTypeConfig, +): GraphQLInputFieldMap { + const fieldMap = resolveThunk(config.fields) || {}; + invariant( + isPlainObj(fieldMap), + `${config.name} fields must be an object with field names as keys or a ` + + 'function which returns such an object.', + ); + const resultFieldMap = Object.create(null); + for (const fieldName of Object.keys(fieldMap)) { + const field = { + ...fieldMap[fieldName], + name: fieldName, + }; + invariant( + !field.hasOwnProperty('resolve'), + `${config.name}.${fieldName} field has a resolve property, but ` + + 'Input Types cannot define resolvers.', + ); + resultFieldMap[fieldName] = field; + } + return resultFieldMap; +} + +export type GraphQLInputObjectTypeConfig = {| + name: string, + fields: Thunk, + description?: ?string, + astNode?: ?InputObjectTypeDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, +|}; + +export type GraphQLInputFieldConfig = {| + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +|}; + +export type GraphQLInputFieldConfigMap = ObjMap; + +export type GraphQLInputField = { + name: string, + type: GraphQLInputType, + defaultValue?: mixed, + description?: ?string, + astNode?: ?InputValueDefinitionNode, +}; + +export function isRequiredInputField( + field: GraphQLInputField, +): boolean %checks { + return isNonNullType(field.type) && field.defaultValue === undefined; +} + +export type GraphQLInputFieldMap = ObjMap; diff --git a/node_modules/graphql/type/definition.mjs b/node_modules/graphql/type/definition.mjs new file mode 100644 index 00000000..b37bf3e6 --- /dev/null +++ b/node_modules/graphql/type/definition.mjs @@ -0,0 +1,869 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import defineToJSON from '../jsutils/defineToJSON'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import instanceOf from '../jsutils/instanceOf'; +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import { Kind } from '../language/kinds'; +import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped'; +export function isType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type); +} +export function assertType(type) { + !isType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL type.")) : void 0; + return type; +} +/** + * There are predicates for each kind of GraphQL type. + */ + +// eslint-disable-next-line no-redeclare +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} +export function assertScalarType(type) { + !isScalarType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Scalar type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} +export function assertObjectType(type) { + !isObjectType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Object type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} +export function assertInterfaceType(type) { + !isInterfaceType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Interface type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} +export function assertUnionType(type) { + !isUnionType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Union type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} +export function assertEnumType(type) { + !isEnumType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Enum type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} +export function assertInputObjectType(type) { + !isInputObjectType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Input Object type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isListType(type) { + return instanceOf(type, GraphQLList); +} +export function assertListType(type) { + !isListType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL List type.")) : void 0; + return type; +} +// eslint-disable-next-line no-redeclare +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} +export function assertNonNullType(type) { + !isNonNullType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL Non-Null type.")) : void 0; + return type; +} +/** + * These types may be used as input types for arguments and directives. + */ + +export function isInputType(type) { + return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType); +} +export function assertInputType(type) { + !isInputType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL input type.")) : void 0; + return type; +} +/** + * These types may be used as output types as the result of fields. + */ + +export function isOutputType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType); +} +export function assertOutputType(type) { + !isOutputType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL output type.")) : void 0; + return type; +} +/** + * These types may describe types which may be leaf values. + */ + +export function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} +export function assertLeafType(type) { + !isLeafType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL leaf type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +export function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} +export function assertCompositeType(type) { + !isCompositeType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL composite type.")) : void 0; + return type; +} +/** + * These types may describe the parent context of a selection set. + */ + +export function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} +export function assertAbstractType(type) { + !isAbstractType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL abstract type.")) : void 0; + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: GraphQLList(PersonType) }, + * children: { type: GraphQLList(PersonType) }, + * }) + * }) + * + */ + +// eslint-disable-next-line no-redeclare +export function GraphQLList(ofType) { + if (this instanceof GraphQLList) { + this.ofType = assertType(ofType); + } else { + return new GraphQLList(ofType); + } +} // Need to cast through any to alter the prototype. + +GraphQLList.prototype.toString = function toString() { + return '[' + String(this.ofType) + ']'; +}; + +defineToJSON(GraphQLList); +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * + * Example: + * + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: GraphQLNonNull(GraphQLString) }, + * }) + * }) + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +// eslint-disable-next-line no-redeclare +export function GraphQLNonNull(ofType) { + if (this instanceof GraphQLNonNull) { + this.ofType = assertNullableType(ofType); + } else { + return new GraphQLNonNull(ofType); + } +} // Need to cast through any to alter the prototype. + +GraphQLNonNull.prototype.toString = function toString() { + return String(this.ofType) + '!'; +}; + +defineToJSON(GraphQLNonNull); +/** + * These types wrap and modify other types + */ + +export function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} +export function assertWrappingType(type) { + !isWrappingType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL wrapping type.")) : void 0; + return type; +} +/** + * These types can all accept null as a value. + */ + +export function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} +export function assertNullableType(type) { + !isNullableType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL nullable type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + +export function getNullableType(type) { + /* eslint-enable no-redeclare */ + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** + * These named types do not include modifiers like List or NonNull. + */ + +export function isNamedType(type) { + return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type); +} +export function assertNamedType(type) { + !isNamedType(type) ? invariant(0, "Expected ".concat(inspect(type), " to be a GraphQL named type.")) : void 0; + return type; +} +/* eslint-disable no-redeclare */ + +export function getNamedType(type) { + /* eslint-enable no-redeclare */ + if (type) { + var unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + */ + +function resolveThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Scalar Type Definition + * + * The leaf values of any request and input values to arguments are + * Scalars (or Enums) and are defined with a name and a series of functions + * used to parse input from ast or variables and to ensure validity. + * + * If a type's serialize function does not return a value (i.e. it returns + * `undefined`) then an error will be raised and a `null` value will be returned + * in the response. If the serialize function returns `null`, then no error will + * be included in the response. + * + * Example: + * + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize(value) { + * if (value % 2 === 1) { + * return value; + * } + * } + * }); + * + */ + + +export var GraphQLScalarType = +/*#__PURE__*/ +function () { + function GraphQLScalarType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "serialize", void 0); + + _defineProperty(this, "parseValue", void 0); + + _defineProperty(this, "parseLiteral", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + this.name = config.name; + this.description = config.description; + this.serialize = config.serialize; + + this.parseValue = config.parseValue || function (value) { + return value; + }; + + this.parseLiteral = config.parseLiteral || valueFromASTUntyped; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(typeof config.serialize === 'function') ? invariant(0, "".concat(this.name, " must provide \"serialize\" function. If this custom Scalar ") + 'is also used as an input type, ensure "parseValue" and "parseLiteral" ' + 'functions are also provided.') : void 0; + + if (config.parseValue || config.parseLiteral) { + !(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function') ? invariant(0, "".concat(this.name, " must provide both \"parseValue\" and \"parseLiteral\" ") + 'functions.') : void 0; + } + } + + var _proto = GraphQLScalarType.prototype; + + _proto.toString = function toString() { + return this.name; + }; + + return GraphQLScalarType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLScalarType); +defineToJSON(GraphQLScalarType); + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * + * Example: + * + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve(obj) { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * Example: + * + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * + */ +export var GraphQLObjectType = +/*#__PURE__*/ +function () { + function GraphQLObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "isTypeOf", void 0); + + _defineProperty(this, "_fields", void 0); + + _defineProperty(this, "_interfaces", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.isTypeOf = config.isTypeOf; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(config.isTypeOf == null || typeof config.isTypeOf === 'function') ? invariant(0, "".concat(this.name, " must provide \"isTypeOf\" as a function, ") + "but got: ".concat(inspect(config.isTypeOf), ".")) : void 0; + } + + var _proto2 = GraphQLObjectType.prototype; + + _proto2.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto2.getInterfaces = function getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + }; + + _proto2.toString = function toString() { + return this.name; + }; + + return GraphQLObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLObjectType); +defineToJSON(GraphQLObjectType); + +function defineInterfaces(config) { + var interfaces = resolveThunk(config.interfaces) || []; + !Array.isArray(interfaces) ? invariant(0, "".concat(config.name, " interfaces must be an Array or a function which returns ") + 'an Array.') : void 0; + return interfaces; +} + +function defineFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? invariant(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr = Object.keys(fieldMap); + + var _loop = function _loop() { + var fieldName = _arr[_i]; + var fieldConfig = fieldMap[fieldName]; + !isPlainObj(fieldConfig) ? invariant(0, "".concat(config.name, ".").concat(fieldName, " field config must be an object")) : void 0; + !!fieldConfig.hasOwnProperty('isDeprecated') ? invariant(0, "".concat(config.name, ".").concat(fieldName, " should provide \"deprecationReason\" ") + 'instead of "isDeprecated".') : void 0; + + var field = _objectSpread({}, fieldConfig, { + isDeprecated: Boolean(fieldConfig.deprecationReason), + name: fieldName + }); + + !(field.resolve == null || typeof field.resolve === 'function') ? invariant(0, "".concat(config.name, ".").concat(fieldName, " field resolver must be a function if ") + "provided, but got: ".concat(inspect(field.resolve), ".")) : void 0; + var argsConfig = fieldConfig.args; + + if (!argsConfig) { + field.args = []; + } else { + !isPlainObj(argsConfig) ? invariant(0, "".concat(config.name, ".").concat(fieldName, " args must be an object with argument ") + 'names as keys.') : void 0; + field.args = Object.keys(argsConfig).map(function (argName) { + var arg = argsConfig[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + + resultFieldMap[fieldName] = field; + }; + + for (var _i = 0; _i < _arr.length; _i++) { + _loop(); + } + + return resultFieldMap; +} + +function isPlainObj(obj) { + return obj && _typeof(obj) === 'object' && !Array.isArray(obj); +} + +export function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * + * Example: + * + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * + */ +export var GraphQLInterfaceType = +/*#__PURE__*/ +function () { + function GraphQLInterfaceType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._fields = defineFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? invariant(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), ".")) : void 0; + } + + var _proto3 = GraphQLInterfaceType.prototype; + + _proto3.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto3.toString = function toString() { + return this.name; + }; + + return GraphQLInterfaceType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLInterfaceType); +defineToJSON(GraphQLInterfaceType); + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * + * Example: + * + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [ DogType, CatType ], + * resolveType(value) { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * + */ +export var GraphQLUnionType = +/*#__PURE__*/ +function () { + function GraphQLUnionType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "resolveType", void 0); + + _defineProperty(this, "_types", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this.resolveType = config.resolveType; + this._types = defineTypes.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + !(config.resolveType == null || typeof config.resolveType === 'function') ? invariant(0, "".concat(this.name, " must provide \"resolveType\" as a function, ") + "but got: ".concat(inspect(config.resolveType), ".")) : void 0; + } + + var _proto4 = GraphQLUnionType.prototype; + + _proto4.getTypes = function getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + }; + + _proto4.toString = function toString() { + return this.name; + }; + + return GraphQLUnionType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLUnionType); +defineToJSON(GraphQLUnionType); + +function defineTypes(config) { + var types = resolveThunk(config.types) || []; + !Array.isArray(types) ? invariant(0, 'Must provide Array of types or a function which returns ' + "such an array for Union ".concat(config.name, ".")) : void 0; + return types; +} + +/** + * Enum Type Definition + * + * Some leaf values of requests and input values are Enums. GraphQL serializes + * Enum values as strings, however internally Enums can be represented by any + * kind of type, often integers. + * + * Example: + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 } + * } + * }); + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export var GraphQLEnumType +/* */ += +/*#__PURE__*/ +function () { + function GraphQLEnumType(config + /* */ + ) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_values", void 0); + + _defineProperty(this, "_valueLookup", void 0); + + _defineProperty(this, "_nameLookup", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._values = defineEnumValues(this, config.values); + this._valueLookup = new Map(this._values.map(function (enumValue) { + return [enumValue.value, enumValue]; + })); + this._nameLookup = keyMap(this._values, function (value) { + return value.name; + }); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + } + + var _proto5 = GraphQLEnumType.prototype; + + _proto5.getValues = function getValues() { + return this._values; + }; + + _proto5.getValue = function getValue(name) { + return this._nameLookup[name]; + }; + + _proto5.serialize = function serialize(value + /* T */ + ) { + var enumValue = this._valueLookup.get(value); + + if (enumValue) { + return enumValue.name; + } + }; + + _proto5.parseValue = function parseValue(value) + /* T */ + { + if (typeof value === 'string') { + var enumValue = this.getValue(value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.parseLiteral = function parseLiteral(valueNode, _variables) + /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind === Kind.ENUM) { + var enumValue = this.getValue(valueNode.value); + + if (enumValue) { + return enumValue.value; + } + } + }; + + _proto5.toString = function toString() { + return this.name; + }; + + return GraphQLEnumType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLEnumType); +defineToJSON(GraphQLEnumType); + +function defineEnumValues(type, valueMap +/* */ +) { + !isPlainObj(valueMap) ? invariant(0, "".concat(type.name, " values must be an object with value names as keys.")) : void 0; + return Object.keys(valueMap).map(function (valueName) { + var value = valueMap[valueName]; + !isPlainObj(value) ? invariant(0, "".concat(type.name, ".").concat(valueName, " must refer to an object with a \"value\" key ") + "representing an internal value but got: ".concat(inspect(value), ".")) : void 0; + !!value.hasOwnProperty('isDeprecated') ? invariant(0, "".concat(type.name, ".").concat(valueName, " should provide \"deprecationReason\" instead ") + 'of "isDeprecated".') : void 0; + return { + name: valueName, + description: value.description, + isDeprecated: Boolean(value.deprecationReason), + deprecationReason: value.deprecationReason, + astNode: value.astNode, + value: value.hasOwnProperty('value') ? value.value : valueName + }; + }); +} + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * + * Example: + * + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: GraphQLNonNull(GraphQLFloat) }, + * lon: { type: GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * + */ +export var GraphQLInputObjectType = +/*#__PURE__*/ +function () { + function GraphQLInputObjectType(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_fields", void 0); + + this.name = config.name; + this.description = config.description; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + this._fields = defineInputFieldMap.bind(undefined, config); + !(typeof config.name === 'string') ? invariant(0, 'Must provide name.') : void 0; + } + + var _proto6 = GraphQLInputObjectType.prototype; + + _proto6.getFields = function getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + }; + + _proto6.toString = function toString() { + return this.name; + }; + + return GraphQLInputObjectType; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLInputObjectType); +defineToJSON(GraphQLInputObjectType); + +function defineInputFieldMap(config) { + var fieldMap = resolveThunk(config.fields) || {}; + !isPlainObj(fieldMap) ? invariant(0, "".concat(config.name, " fields must be an object with field names as keys or a ") + 'function which returns such an object.') : void 0; + var resultFieldMap = Object.create(null); + + var _arr2 = Object.keys(fieldMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var fieldName = _arr2[_i2]; + + var field = _objectSpread({}, fieldMap[fieldName], { + name: fieldName + }); + + !!field.hasOwnProperty('resolve') ? invariant(0, "".concat(config.name, ".").concat(fieldName, " field has a resolve property, but ") + 'Input Types cannot define resolvers.') : void 0; + resultFieldMap[fieldName] = field; + } + + return resultFieldMap; +} + +export function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} \ No newline at end of file diff --git a/node_modules/graphql/type/directives.js b/node_modules/graphql/type/directives.js new file mode 100644 index 00000000..eecadc9e --- /dev/null +++ b/node_modules/graphql/type/directives.js @@ -0,0 +1,156 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDirective = isDirective; +exports.isSpecifiedDirective = isSpecifiedDirective; +exports.specifiedDirectives = exports.GraphQLDeprecatedDirective = exports.DEFAULT_DEPRECATION_REASON = exports.GraphQLSkipDirective = exports.GraphQLIncludeDirective = exports.GraphQLDirective = void 0; + +var _definition = require("./definition"); + +var _scalars = require("./scalars"); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +var _defineToJSON = _interopRequireDefault(require("../jsutils/defineToJSON")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _directiveLocation = require("../language/directiveLocation"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// eslint-disable-next-line no-redeclare +function isDirective(directive) { + return (0, _instanceOf.default)(directive, GraphQLDirective); +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + + +var GraphQLDirective = +/*#__PURE__*/ +function () { + function GraphQLDirective(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "locations", void 0); + + _defineProperty(this, "args", void 0); + + _defineProperty(this, "astNode", void 0); + + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.astNode = config.astNode; + !config.name ? (0, _invariant.default)(0, 'Directive must be named.') : void 0; + !Array.isArray(config.locations) ? (0, _invariant.default)(0, 'Must provide locations for directive.') : void 0; + var args = config.args; + + if (!args) { + this.args = []; + } else { + !!Array.isArray(args) ? (0, _invariant.default)(0, "@".concat(config.name, " args must be an object with argument names as keys.")) : void 0; + this.args = Object.keys(args).map(function (argName) { + var arg = args[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + } + + var _proto = GraphQLDirective.prototype; + + _proto.toString = function toString() { + return '@' + this.name; + }; + + return GraphQLDirective; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLDirective = GraphQLDirective; +(0, _defineToStringTag.default)(GraphQLDirective); +(0, _defineToJSON.default)(GraphQLDirective); + +/** + * Used to conditionally include fields or fragments. + */ +var GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +exports.GraphQLIncludeDirective = GraphQLIncludeDirective; +var GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.', + locations: [_directiveLocation.DirectiveLocation.FIELD, _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, _directiveLocation.DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +exports.GraphQLSkipDirective = GraphQLSkipDirective; +var DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON; +var GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [_directiveLocation.DirectiveLocation.FIELD_DEFINITION, _directiveLocation.DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: _scalars.GraphQLString, + description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted using ' + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * The full list of specified directives. + */ + +exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective; +var specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective]; +exports.specifiedDirectives = specifiedDirectives; + +function isSpecifiedDirective(directive) { + return specifiedDirectives.some(function (specifiedDirective) { + return specifiedDirective.name === directive.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/type/directives.js.flow b/node_modules/graphql/type/directives.js.flow new file mode 100644 index 00000000..e8a7b74f --- /dev/null +++ b/node_modules/graphql/type/directives.js.flow @@ -0,0 +1,178 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + GraphQLFieldConfigArgumentMap, + GraphQLArgument, +} from './definition'; +import { GraphQLNonNull } from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import defineToJSON from '../jsutils/defineToJSON'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import type { DirectiveDefinitionNode } from '../language/ast'; +import { + DirectiveLocation, + type DirectiveLocationEnum, +} from '../language/directiveLocation'; + +/** + * Test if the given value is a GraphQL directive. + */ +declare function isDirective( + directive: mixed, +): boolean %checks(directive instanceof GraphQLDirective); +// eslint-disable-next-line no-redeclare +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export class GraphQLDirective { + name: string; + description: ?string; + locations: Array; + args: Array; + astNode: ?DirectiveDefinitionNode; + + constructor(config: GraphQLDirectiveConfig): void { + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.astNode = config.astNode; + invariant(config.name, 'Directive must be named.'); + invariant( + Array.isArray(config.locations), + 'Must provide locations for directive.', + ); + + const args = config.args; + if (!args) { + this.args = []; + } else { + invariant( + !Array.isArray(args), + `@${config.name} args must be an object with argument names as keys.`, + ); + this.args = Object.keys(args).map(argName => { + const arg = args[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode, + }; + }); + } + } + + toString(): string { + return '@' + this.name; + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLDirective); +defineToJSON(GraphQLDirective); + +export type GraphQLDirectiveConfig = {| + name: string, + description?: ?string, + locations: Array, + args?: ?GraphQLFieldConfigArgumentMap, + astNode?: ?DirectiveDefinitionNode, +|}; + +/** + * Used to conditionally include fields or fragments. + */ +export const GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: + 'Directs the executor to include this field or fragment only when ' + + 'the `if` argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.', + }, + }, +}); + +/** + * Used to conditionally skip (exclude) fields or fragments. + */ +export const GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: + 'Directs the executor to skip this field or fragment when the `if` ' + + 'argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.', + }, + }, +}); + +/** + * Constant string used for default reason for a deprecation. + */ +export const DEFAULT_DEPRECATION_REASON = 'No longer supported'; + +/** + * Used to declare element of a GraphQL schema as deprecated. + */ +export const GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: GraphQLString, + description: + 'Explains why this element was deprecated, usually also including a ' + + 'suggestion for how to access supported similar data. Formatted using ' + + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON, + }, + }, +}); + +/** + * The full list of specified directives. + */ +export const specifiedDirectives: $ReadOnlyArray<*> = [ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, +]; + +export function isSpecifiedDirective( + directive: GraphQLDirective, +): boolean %checks { + return specifiedDirectives.some( + specifiedDirective => specifiedDirective.name === directive.name, + ); +} diff --git a/node_modules/graphql/type/directives.mjs b/node_modules/graphql/type/directives.mjs new file mode 100644 index 00000000..b0629e5d --- /dev/null +++ b/node_modules/graphql/type/directives.mjs @@ -0,0 +1,141 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLNonNull } from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import defineToJSON from '../jsutils/defineToJSON'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import { DirectiveLocation } from '../language/directiveLocation'; +/** + * Test if the given value is a GraphQL directive. + */ + +// eslint-disable-next-line no-redeclare +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ + +export var GraphQLDirective = +/*#__PURE__*/ +function () { + function GraphQLDirective(config) { + _defineProperty(this, "name", void 0); + + _defineProperty(this, "description", void 0); + + _defineProperty(this, "locations", void 0); + + _defineProperty(this, "args", void 0); + + _defineProperty(this, "astNode", void 0); + + this.name = config.name; + this.description = config.description; + this.locations = config.locations; + this.astNode = config.astNode; + !config.name ? invariant(0, 'Directive must be named.') : void 0; + !Array.isArray(config.locations) ? invariant(0, 'Must provide locations for directive.') : void 0; + var args = config.args; + + if (!args) { + this.args = []; + } else { + !!Array.isArray(args) ? invariant(0, "@".concat(config.name, " args must be an object with argument names as keys.")) : void 0; + this.args = Object.keys(args).map(function (argName) { + var arg = args[argName]; + return { + name: argName, + description: arg.description === undefined ? null : arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + astNode: arg.astNode + }; + }); + } + } + + var _proto = GraphQLDirective.prototype; + + _proto.toString = function toString() { + return '@' + this.name; + }; + + return GraphQLDirective; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLDirective); +defineToJSON(GraphQLDirective); + +/** + * Used to conditionally include fields or fragments. + */ +export var GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: 'Directs the executor to include this field or fragment only when ' + 'the `if` argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.' + } + } +}); +/** + * Used to conditionally skip (exclude) fields or fragments. + */ + +export var GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: 'Directs the executor to skip this field or fragment when the `if` ' + 'argument is true.', + locations: [DirectiveLocation.FIELD, DirectiveLocation.FRAGMENT_SPREAD, DirectiveLocation.INLINE_FRAGMENT], + args: { + if: { + type: GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.' + } + } +}); +/** + * Constant string used for default reason for a deprecation. + */ + +export var DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + */ + +export var GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [DirectiveLocation.FIELD_DEFINITION, DirectiveLocation.ENUM_VALUE], + args: { + reason: { + type: GraphQLString, + description: 'Explains why this element was deprecated, usually also including a ' + 'suggestion for how to access supported similar data. Formatted using ' + 'the Markdown syntax (as specified by [CommonMark](https://commonmark.org/).', + defaultValue: DEFAULT_DEPRECATION_REASON + } + } +}); +/** + * The full list of specified directives. + */ + +export var specifiedDirectives = [GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective]; +export function isSpecifiedDirective(directive) { + return specifiedDirectives.some(function (specifiedDirective) { + return specifiedDirective.name === directive.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/type/index.js b/node_modules/graphql/type/index.js new file mode 100644 index 00000000..d758984a --- /dev/null +++ b/node_modules/graphql/type/index.js @@ -0,0 +1,491 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "isSchema", { + enumerable: true, + get: function get() { + return _schema.isSchema; + } +}); +Object.defineProperty(exports, "GraphQLSchema", { + enumerable: true, + get: function get() { + return _schema.GraphQLSchema; + } +}); +Object.defineProperty(exports, "isType", { + enumerable: true, + get: function get() { + return _definition.isType; + } +}); +Object.defineProperty(exports, "isScalarType", { + enumerable: true, + get: function get() { + return _definition.isScalarType; + } +}); +Object.defineProperty(exports, "isObjectType", { + enumerable: true, + get: function get() { + return _definition.isObjectType; + } +}); +Object.defineProperty(exports, "isInterfaceType", { + enumerable: true, + get: function get() { + return _definition.isInterfaceType; + } +}); +Object.defineProperty(exports, "isUnionType", { + enumerable: true, + get: function get() { + return _definition.isUnionType; + } +}); +Object.defineProperty(exports, "isEnumType", { + enumerable: true, + get: function get() { + return _definition.isEnumType; + } +}); +Object.defineProperty(exports, "isInputObjectType", { + enumerable: true, + get: function get() { + return _definition.isInputObjectType; + } +}); +Object.defineProperty(exports, "isListType", { + enumerable: true, + get: function get() { + return _definition.isListType; + } +}); +Object.defineProperty(exports, "isNonNullType", { + enumerable: true, + get: function get() { + return _definition.isNonNullType; + } +}); +Object.defineProperty(exports, "isInputType", { + enumerable: true, + get: function get() { + return _definition.isInputType; + } +}); +Object.defineProperty(exports, "isOutputType", { + enumerable: true, + get: function get() { + return _definition.isOutputType; + } +}); +Object.defineProperty(exports, "isLeafType", { + enumerable: true, + get: function get() { + return _definition.isLeafType; + } +}); +Object.defineProperty(exports, "isCompositeType", { + enumerable: true, + get: function get() { + return _definition.isCompositeType; + } +}); +Object.defineProperty(exports, "isAbstractType", { + enumerable: true, + get: function get() { + return _definition.isAbstractType; + } +}); +Object.defineProperty(exports, "isWrappingType", { + enumerable: true, + get: function get() { + return _definition.isWrappingType; + } +}); +Object.defineProperty(exports, "isNullableType", { + enumerable: true, + get: function get() { + return _definition.isNullableType; + } +}); +Object.defineProperty(exports, "isNamedType", { + enumerable: true, + get: function get() { + return _definition.isNamedType; + } +}); +Object.defineProperty(exports, "isRequiredArgument", { + enumerable: true, + get: function get() { + return _definition.isRequiredArgument; + } +}); +Object.defineProperty(exports, "isRequiredInputField", { + enumerable: true, + get: function get() { + return _definition.isRequiredInputField; + } +}); +Object.defineProperty(exports, "assertType", { + enumerable: true, + get: function get() { + return _definition.assertType; + } +}); +Object.defineProperty(exports, "assertScalarType", { + enumerable: true, + get: function get() { + return _definition.assertScalarType; + } +}); +Object.defineProperty(exports, "assertObjectType", { + enumerable: true, + get: function get() { + return _definition.assertObjectType; + } +}); +Object.defineProperty(exports, "assertInterfaceType", { + enumerable: true, + get: function get() { + return _definition.assertInterfaceType; + } +}); +Object.defineProperty(exports, "assertUnionType", { + enumerable: true, + get: function get() { + return _definition.assertUnionType; + } +}); +Object.defineProperty(exports, "assertEnumType", { + enumerable: true, + get: function get() { + return _definition.assertEnumType; + } +}); +Object.defineProperty(exports, "assertInputObjectType", { + enumerable: true, + get: function get() { + return _definition.assertInputObjectType; + } +}); +Object.defineProperty(exports, "assertListType", { + enumerable: true, + get: function get() { + return _definition.assertListType; + } +}); +Object.defineProperty(exports, "assertNonNullType", { + enumerable: true, + get: function get() { + return _definition.assertNonNullType; + } +}); +Object.defineProperty(exports, "assertInputType", { + enumerable: true, + get: function get() { + return _definition.assertInputType; + } +}); +Object.defineProperty(exports, "assertOutputType", { + enumerable: true, + get: function get() { + return _definition.assertOutputType; + } +}); +Object.defineProperty(exports, "assertLeafType", { + enumerable: true, + get: function get() { + return _definition.assertLeafType; + } +}); +Object.defineProperty(exports, "assertCompositeType", { + enumerable: true, + get: function get() { + return _definition.assertCompositeType; + } +}); +Object.defineProperty(exports, "assertAbstractType", { + enumerable: true, + get: function get() { + return _definition.assertAbstractType; + } +}); +Object.defineProperty(exports, "assertWrappingType", { + enumerable: true, + get: function get() { + return _definition.assertWrappingType; + } +}); +Object.defineProperty(exports, "assertNullableType", { + enumerable: true, + get: function get() { + return _definition.assertNullableType; + } +}); +Object.defineProperty(exports, "assertNamedType", { + enumerable: true, + get: function get() { + return _definition.assertNamedType; + } +}); +Object.defineProperty(exports, "getNullableType", { + enumerable: true, + get: function get() { + return _definition.getNullableType; + } +}); +Object.defineProperty(exports, "getNamedType", { + enumerable: true, + get: function get() { + return _definition.getNamedType; + } +}); +Object.defineProperty(exports, "GraphQLScalarType", { + enumerable: true, + get: function get() { + return _definition.GraphQLScalarType; + } +}); +Object.defineProperty(exports, "GraphQLObjectType", { + enumerable: true, + get: function get() { + return _definition.GraphQLObjectType; + } +}); +Object.defineProperty(exports, "GraphQLInterfaceType", { + enumerable: true, + get: function get() { + return _definition.GraphQLInterfaceType; + } +}); +Object.defineProperty(exports, "GraphQLUnionType", { + enumerable: true, + get: function get() { + return _definition.GraphQLUnionType; + } +}); +Object.defineProperty(exports, "GraphQLEnumType", { + enumerable: true, + get: function get() { + return _definition.GraphQLEnumType; + } +}); +Object.defineProperty(exports, "GraphQLInputObjectType", { + enumerable: true, + get: function get() { + return _definition.GraphQLInputObjectType; + } +}); +Object.defineProperty(exports, "GraphQLList", { + enumerable: true, + get: function get() { + return _definition.GraphQLList; + } +}); +Object.defineProperty(exports, "GraphQLNonNull", { + enumerable: true, + get: function get() { + return _definition.GraphQLNonNull; + } +}); +Object.defineProperty(exports, "isDirective", { + enumerable: true, + get: function get() { + return _directives.isDirective; + } +}); +Object.defineProperty(exports, "GraphQLDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLDirective; + } +}); +Object.defineProperty(exports, "isSpecifiedDirective", { + enumerable: true, + get: function get() { + return _directives.isSpecifiedDirective; + } +}); +Object.defineProperty(exports, "specifiedDirectives", { + enumerable: true, + get: function get() { + return _directives.specifiedDirectives; + } +}); +Object.defineProperty(exports, "GraphQLIncludeDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLIncludeDirective; + } +}); +Object.defineProperty(exports, "GraphQLSkipDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLSkipDirective; + } +}); +Object.defineProperty(exports, "GraphQLDeprecatedDirective", { + enumerable: true, + get: function get() { + return _directives.GraphQLDeprecatedDirective; + } +}); +Object.defineProperty(exports, "DEFAULT_DEPRECATION_REASON", { + enumerable: true, + get: function get() { + return _directives.DEFAULT_DEPRECATION_REASON; + } +}); +Object.defineProperty(exports, "isSpecifiedScalarType", { + enumerable: true, + get: function get() { + return _scalars.isSpecifiedScalarType; + } +}); +Object.defineProperty(exports, "specifiedScalarTypes", { + enumerable: true, + get: function get() { + return _scalars.specifiedScalarTypes; + } +}); +Object.defineProperty(exports, "GraphQLInt", { + enumerable: true, + get: function get() { + return _scalars.GraphQLInt; + } +}); +Object.defineProperty(exports, "GraphQLFloat", { + enumerable: true, + get: function get() { + return _scalars.GraphQLFloat; + } +}); +Object.defineProperty(exports, "GraphQLString", { + enumerable: true, + get: function get() { + return _scalars.GraphQLString; + } +}); +Object.defineProperty(exports, "GraphQLBoolean", { + enumerable: true, + get: function get() { + return _scalars.GraphQLBoolean; + } +}); +Object.defineProperty(exports, "GraphQLID", { + enumerable: true, + get: function get() { + return _scalars.GraphQLID; + } +}); +Object.defineProperty(exports, "TypeKind", { + enumerable: true, + get: function get() { + return _introspection.TypeKind; + } +}); +Object.defineProperty(exports, "isIntrospectionType", { + enumerable: true, + get: function get() { + return _introspection.isIntrospectionType; + } +}); +Object.defineProperty(exports, "introspectionTypes", { + enumerable: true, + get: function get() { + return _introspection.introspectionTypes; + } +}); +Object.defineProperty(exports, "__Schema", { + enumerable: true, + get: function get() { + return _introspection.__Schema; + } +}); +Object.defineProperty(exports, "__Directive", { + enumerable: true, + get: function get() { + return _introspection.__Directive; + } +}); +Object.defineProperty(exports, "__DirectiveLocation", { + enumerable: true, + get: function get() { + return _introspection.__DirectiveLocation; + } +}); +Object.defineProperty(exports, "__Type", { + enumerable: true, + get: function get() { + return _introspection.__Type; + } +}); +Object.defineProperty(exports, "__Field", { + enumerable: true, + get: function get() { + return _introspection.__Field; + } +}); +Object.defineProperty(exports, "__InputValue", { + enumerable: true, + get: function get() { + return _introspection.__InputValue; + } +}); +Object.defineProperty(exports, "__EnumValue", { + enumerable: true, + get: function get() { + return _introspection.__EnumValue; + } +}); +Object.defineProperty(exports, "__TypeKind", { + enumerable: true, + get: function get() { + return _introspection.__TypeKind; + } +}); +Object.defineProperty(exports, "SchemaMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.SchemaMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.TypeMetaFieldDef; + } +}); +Object.defineProperty(exports, "TypeNameMetaFieldDef", { + enumerable: true, + get: function get() { + return _introspection.TypeNameMetaFieldDef; + } +}); +Object.defineProperty(exports, "validateSchema", { + enumerable: true, + get: function get() { + return _validate.validateSchema; + } +}); +Object.defineProperty(exports, "assertValidSchema", { + enumerable: true, + get: function get() { + return _validate.assertValidSchema; + } +}); + +var _schema = require("./schema"); + +var _definition = require("./definition"); + +var _directives = require("./directives"); + +var _scalars = require("./scalars"); + +var _introspection = require("./introspection"); + +var _validate = require("./validate"); \ No newline at end of file diff --git a/node_modules/graphql/type/index.js.flow b/node_modules/graphql/type/index.js.flow new file mode 100644 index 00000000..4868543a --- /dev/null +++ b/node_modules/graphql/type/index.js.flow @@ -0,0 +1,162 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { + // Predicate + isSchema, + // GraphQL Schema definition + GraphQLSchema, +} from './schema'; + +export type { GraphQLSchemaConfig } from './schema'; + +export { + // Predicates + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + // Un-modifiers + getNullableType, + getNamedType, + // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + // Type Wrappers + GraphQLList, + GraphQLNonNull, +} from './definition'; + +export { + // Predicate + isDirective, + // Directives Definition + GraphQLDirective, + // Built-in Directives defined by the Spec + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, +} from './directives'; + +export type { GraphQLDirectiveConfig } from './directives'; + +// Common built-in scalar instances. +export { + isSpecifiedScalarType, + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, +} from './scalars'; + +export { + // "Enum" of Type Kinds + TypeKind, + // GraphQL Types for introspection. + isIntrospectionType, + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from './introspection'; + +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + Thunk, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLEnumTypeConfig, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInterfaceTypeConfig, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './definition'; + +export { validateSchema, assertValidSchema } from './validate'; diff --git a/node_modules/graphql/type/index.mjs b/node_modules/graphql/type/index.mjs new file mode 100644 index 00000000..47d065ad --- /dev/null +++ b/node_modules/graphql/type/index.mjs @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { // Predicate +isSchema, // GraphQL Schema definition +GraphQLSchema } from './schema'; +export { // Predicates +isType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isInputType, isOutputType, isLeafType, isCompositeType, isAbstractType, isWrappingType, isNullableType, isNamedType, isRequiredArgument, isRequiredInputField, // Assertions +assertType, assertScalarType, assertObjectType, assertInterfaceType, assertUnionType, assertEnumType, assertInputObjectType, assertListType, assertNonNullType, assertInputType, assertOutputType, assertLeafType, assertCompositeType, assertAbstractType, assertWrappingType, assertNullableType, assertNamedType, // Un-modifiers +getNullableType, getNamedType, // Definitions +GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, // Type Wrappers +GraphQLList, GraphQLNonNull } from './definition'; +export { // Predicate +isDirective, // Directives Definition +GraphQLDirective, // Built-in Directives defined by the Spec +isSpecifiedDirective, specifiedDirectives, GraphQLIncludeDirective, GraphQLSkipDirective, GraphQLDeprecatedDirective, // Constant Deprecation Reason +DEFAULT_DEPRECATION_REASON } from './directives'; +// Common built-in scalar instances. +export { isSpecifiedScalarType, specifiedScalarTypes, GraphQLInt, GraphQLFloat, GraphQLString, GraphQLBoolean, GraphQLID } from './scalars'; +export { // "Enum" of Type Kinds +TypeKind, // GraphQL Types for introspection. +isIntrospectionType, introspectionTypes, __Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind, // Meta-field definitions. +SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from './introspection'; +export { validateSchema, assertValidSchema } from './validate'; \ No newline at end of file diff --git a/node_modules/graphql/type/introspection.js b/node_modules/graphql/type/introspection.js new file mode 100644 index 00000000..a3a1a255 --- /dev/null +++ b/node_modules/graphql/type/introspection.js @@ -0,0 +1,546 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isIntrospectionType = isIntrospectionType; +exports.introspectionTypes = exports.TypeNameMetaFieldDef = exports.TypeMetaFieldDef = exports.SchemaMetaFieldDef = exports.__TypeKind = exports.TypeKind = exports.__EnumValue = exports.__InputValue = exports.__Field = exports.__Type = exports.__DirectiveLocation = exports.__Directive = exports.__Schema = void 0; + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _astFromValue = require("../utilities/astFromValue"); + +var _printer = require("../language/printer"); + +var _definition = require("./definition"); + +var _scalars = require("./scalars"); + +var _directiveLocation = require("../language/directiveLocation"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var __Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.', + fields: function fields() { + return { + types: { + description: 'A list of all types supported by this server.', + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type))), + resolve: function resolve(schema) { + return (0, _objectValues.default)(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: (0, _definition.GraphQLNonNull)(__Type), + resolve: function resolve(schema) { + return schema.getQueryType(); + } + }, + mutationType: { + description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getMutationType(); + } + }, + subscriptionType: { + description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getSubscriptionType(); + } + }, + directives: { + description: 'A list of all directives supported by this server.', + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); + +exports.__Schema = __Schema; + +var __Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + "\n\nIn some cases, you need to provide options to alter GraphQL's " + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + locations: { + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__DirectiveLocation))), + resolve: function resolve(obj) { + return obj.locations; + } + }, + args: { + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))), + resolve: function resolve(directive) { + return directive.args || []; + } + } + }; + } +}); + +exports.__Directive = __Directive; + +var __DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); + +exports.__DirectiveLocation = __DirectiveLocation; + +var __Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.', + fields: function fields() { + return { + kind: { + type: (0, _definition.GraphQLNonNull)(__TypeKind), + resolve: function resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } else if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } else if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } else if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } else if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } else if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } else if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } else if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + + throw new Error('Unknown kind of type: ' + type); + } + }, + name: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + fields: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Field)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref) { + var includeDeprecated = _ref.includeDeprecated; + + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var fields = (0, _objectValues.default)(type.getFields()); + + if (!includeDeprecated) { + fields = fields.filter(function (field) { + return !field.deprecationReason; + }); + } + + return fields; + } + + return null; + } + }, + interfaces: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)), + resolve: function resolve(type) { + if ((0, _definition.isObjectType)(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__Type)), + resolve: function resolve(type, args, context, _ref2) { + var schema = _ref2.schema; + + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__EnumValue)), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref3) { + var includeDeprecated = _ref3.includeDeprecated; + + if ((0, _definition.isEnumType)(type)) { + var values = type.getValues(); + + if (!includeDeprecated) { + values = values.filter(function (value) { + return !value.deprecationReason; + }); + } + + return values; + } + } + }, + inputFields: { + type: (0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue)), + resolve: function resolve(type) { + if ((0, _definition.isInputObjectType)(type)) { + return (0, _objectValues.default)(type.getFields()); + } + } + }, + ofType: { + type: __Type, + resolve: function resolve(obj) { + return obj.ofType; + } + } + }; + } +}); + +exports.__Type = __Type; + +var __Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + args: { + type: (0, _definition.GraphQLNonNull)((0, _definition.GraphQLList)((0, _definition.GraphQLNonNull)(__InputValue))), + resolve: function resolve(field) { + return field.args || []; + } + }, + type: { + type: (0, _definition.GraphQLNonNull)(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + isDeprecated: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); + +exports.__Field = __Field; + +var __InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + type: { + type: (0, _definition.GraphQLNonNull)(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + defaultValue: { + type: _scalars.GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.', + resolve: function resolve(inputVal) { + return (0, _isInvalid.default)(inputVal.defaultValue) ? null : (0, _printer.print)((0, _astFromValue.astFromValue)(inputVal.defaultValue, inputVal.type)); + } + } + }; + } +}); + +exports.__InputValue = __InputValue; + +var __EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.', + fields: function fields() { + return { + name: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + isDeprecated: { + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); + +exports.__EnumValue = __EnumValue; +var TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}; +exports.TypeKind = TypeKind; + +var __TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + + +exports.__TypeKind = __TypeKind; +var SchemaMetaFieldDef = { + name: '__schema', + type: (0, _definition.GraphQLNonNull)(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: function resolve(source, args, context, _ref4) { + var schema = _ref4.schema; + return schema; + } +}; +exports.SchemaMetaFieldDef = SchemaMetaFieldDef; +var TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString) + }], + resolve: function resolve(source, _ref5, context, _ref6) { + var name = _ref5.name; + var schema = _ref6.schema; + return schema.getType(name); + } +}; +exports.TypeMetaFieldDef = TypeMetaFieldDef; +var TypeNameMetaFieldDef = { + name: '__typename', + type: (0, _definition.GraphQLNonNull)(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: function resolve(source, args, context, _ref7) { + var parentType = _ref7.parentType; + return parentType.name; + } +}; +exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef; +var introspectionTypes = [__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]; +exports.introspectionTypes = introspectionTypes; + +function isIntrospectionType(type) { + return (0, _definition.isNamedType)(type) && ( // Would prefer to use introspectionTypes.some(), however %checks needs + // a simple expression. + type.name === __Schema.name || type.name === __Directive.name || type.name === __DirectiveLocation.name || type.name === __Type.name || type.name === __Field.name || type.name === __InputValue.name || type.name === __EnumValue.name || type.name === __TypeKind.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/introspection.js.flow b/node_modules/graphql/type/introspection.js.flow new file mode 100644 index 00000000..63630d95 --- /dev/null +++ b/node_modules/graphql/type/introspection.js.flow @@ -0,0 +1,498 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import { + GraphQLObjectType, + GraphQLEnumType, + GraphQLList, + GraphQLNonNull, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isAbstractType, + isNamedType, +} from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import { DirectiveLocation } from '../language/directiveLocation'; +import type { GraphQLField } from './definition'; + +export const __Schema = new GraphQLObjectType({ + name: '__Schema', + description: + 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + + 'exposes all available types and directives on the server, as well as ' + + 'the entry points for query, mutation, and subscription operations.', + fields: () => ({ + types: { + description: 'A list of all types supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))), + resolve(schema) { + return objectValues(schema.getTypeMap()); + }, + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: GraphQLNonNull(__Type), + resolve: schema => schema.getQueryType(), + }, + mutationType: { + description: + 'If this server supports mutation, the type that ' + + 'mutation operations will be rooted at.', + type: __Type, + resolve: schema => schema.getMutationType(), + }, + subscriptionType: { + description: + 'If this server support subscription, the type that ' + + 'subscription operations will be rooted at.', + type: __Type, + resolve: schema => schema.getSubscriptionType(), + }, + directives: { + description: 'A list of all directives supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))), + resolve: schema => schema.getDirectives(), + }, + }), +}); + +export const __Directive = new GraphQLObjectType({ + name: '__Directive', + description: + 'A Directive provides a way to describe alternate runtime execution and ' + + 'type validation behavior in a GraphQL document.' + + "\n\nIn some cases, you need to provide options to alter GraphQL's " + + 'execution behavior in ways field arguments will not suffice, such as ' + + 'conditionally including or skipping a field. Directives provide this by ' + + 'describing additional information to the executor.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + locations: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))), + resolve: obj => obj.locations, + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: directive => directive.args || [], + }, + }), +}); + +export const __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: + 'A Directive can be adjacent to many parts of the GraphQL language, a ' + + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.', + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.', + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.', + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.', + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.', + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.', + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.', + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.', + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.', + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.', + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.', + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.', + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.', + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.', + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.', + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.', + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.', + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.', + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.', + }, + }, +}); + +export const __Type = new GraphQLObjectType({ + name: '__Type', + description: + 'The fundamental unit of any GraphQL Schema is the type. There are ' + + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + + '\n\nDepending on the kind of a type, certain fields describe ' + + 'information about that type. Scalar types provide no information ' + + 'beyond a name and description, while Enum types provide their values. ' + + 'Object and Interface types provide the fields they describe. Abstract ' + + 'types, Union and Interface, provide the Object types possible ' + + 'at runtime. List and NonNull types compose other types.', + fields: () => ({ + kind: { + type: GraphQLNonNull(__TypeKind), + resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } else if (isObjectType(type)) { + return TypeKind.OBJECT; + } else if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } else if (isUnionType(type)) { + return TypeKind.UNION; + } else if (isEnumType(type)) { + return TypeKind.ENUM; + } else if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } else if (isListType(type)) { + return TypeKind.LIST; + } else if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } + throw new Error('Unknown kind of type: ' + type); + }, + }, + name: { + type: GraphQLString, + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + fields: { + type: GraphQLList(GraphQLNonNull(__Field)), + args: { + includeDeprecated: { type: GraphQLBoolean, defaultValue: false }, + }, + resolve(type, { includeDeprecated }) { + if (isObjectType(type) || isInterfaceType(type)) { + let fields = objectValues(type.getFields()); + if (!includeDeprecated) { + fields = fields.filter(field => !field.deprecationReason); + } + return fields; + } + return null; + }, + }, + interfaces: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve(type) { + if (isObjectType(type)) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve(type, args, context, { schema }) { + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: GraphQLList(GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { type: GraphQLBoolean, defaultValue: false }, + }, + resolve(type, { includeDeprecated }) { + if (isEnumType(type)) { + let values = type.getValues(); + if (!includeDeprecated) { + values = values.filter(value => !value.deprecationReason); + } + return values; + } + }, + }, + inputFields: { + type: GraphQLList(GraphQLNonNull(__InputValue)), + resolve(type) { + if (isInputObjectType(type)) { + return objectValues(type.getFields()); + } + }, + }, + ofType: { + type: __Type, + resolve: obj => obj.ofType, + }, + }), +}); + +export const __Field = new GraphQLObjectType({ + name: '__Field', + description: + 'Object and Interface types are described by a list of Fields, each of ' + + 'which has a name, potentially a list of arguments, and a return type.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: field => field.args || [], + }, + type: { + type: GraphQLNonNull(__Type), + resolve: obj => obj.type, + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: obj => obj.isDeprecated, + }, + deprecationReason: { + type: GraphQLString, + resolve: obj => obj.deprecationReason, + }, + }), +}); + +export const __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: + 'Arguments provided to Fields or Directives and the input fields of an ' + + 'InputObject are represented as Input Values which describe their type ' + + 'and optionally a default value.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + type: { + type: GraphQLNonNull(__Type), + resolve: obj => obj.type, + }, + defaultValue: { + type: GraphQLString, + description: + 'A GraphQL-formatted string representing the default value for this ' + + 'input value.', + resolve: inputVal => + isInvalid(inputVal.defaultValue) + ? null + : print(astFromValue(inputVal.defaultValue, inputVal.type)), + }, + }), +}); + +export const __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: + 'One possible value for a given Enum. Enum values are unique values, not ' + + 'a placeholder for a string or numeric value. However an Enum value is ' + + 'returned in a JSON response as a string.', + fields: () => ({ + name: { + type: GraphQLNonNull(GraphQLString), + resolve: obj => obj.name, + }, + description: { + type: GraphQLString, + resolve: obj => obj.description, + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: obj => obj.isDeprecated, + }, + deprecationReason: { + type: GraphQLString, + resolve: obj => obj.deprecationReason, + }, + }), +}); + +export const TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL', +}; + +export const __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.', + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + 'Indicates this type is an object. ' + + '`fields` and `interfaces` are valid fields.', + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + 'Indicates this type is an interface. ' + + '`fields` and `possibleTypes` are valid fields.', + }, + UNION: { + value: TypeKind.UNION, + description: + 'Indicates this type is a union. `possibleTypes` is a valid field.', + }, + ENUM: { + value: TypeKind.ENUM, + description: + 'Indicates this type is an enum. `enumValues` is a valid field.', + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + 'Indicates this type is an input object. ' + + '`inputFields` is a valid field.', + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.', + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + 'Indicates this type is a non-null. `ofType` is a valid field.', + }, + }, +}); + +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export const SchemaMetaFieldDef: GraphQLField<*, *> = { + name: '__schema', + type: GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (source, args, context, { schema }) => schema, +}; + +export const TypeMetaFieldDef: GraphQLField<*, *> = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ name: 'name', type: GraphQLNonNull(GraphQLString) }], + resolve: (source, { name }, context, { schema }) => schema.getType(name), +}; + +export const TypeNameMetaFieldDef: GraphQLField<*, *> = { + name: '__typename', + type: GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (source, args, context, { parentType }) => parentType.name, +}; + +export const introspectionTypes: $ReadOnlyArray<*> = [ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, +]; + +export function isIntrospectionType(type: mixed): boolean %checks { + return ( + isNamedType(type) && + // Would prefer to use introspectionTypes.some(), however %checks needs + // a simple expression. + (type.name === __Schema.name || + type.name === __Directive.name || + type.name === __DirectiveLocation.name || + type.name === __Type.name || + type.name === __Field.name || + type.name === __InputValue.name || + type.name === __EnumValue.name || + type.name === __TypeKind.name) + ); +} diff --git a/node_modules/graphql/type/introspection.mjs b/node_modules/graphql/type/introspection.mjs new file mode 100644 index 00000000..6f1bf6ea --- /dev/null +++ b/node_modules/graphql/type/introspection.mjs @@ -0,0 +1,500 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import { GraphQLObjectType, GraphQLEnumType, GraphQLList, GraphQLNonNull, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isListType, isNonNullType, isAbstractType, isNamedType } from './definition'; +import { GraphQLString, GraphQLBoolean } from './scalars'; +import { DirectiveLocation } from '../language/directiveLocation'; +export var __Schema = new GraphQLObjectType({ + name: '__Schema', + description: 'A GraphQL Schema defines the capabilities of a GraphQL server. It ' + 'exposes all available types and directives on the server, as well as ' + 'the entry points for query, mutation, and subscription operations.', + fields: function fields() { + return { + types: { + description: 'A list of all types supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))), + resolve: function resolve(schema) { + return objectValues(schema.getTypeMap()); + } + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: GraphQLNonNull(__Type), + resolve: function resolve(schema) { + return schema.getQueryType(); + } + }, + mutationType: { + description: 'If this server supports mutation, the type that ' + 'mutation operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getMutationType(); + } + }, + subscriptionType: { + description: 'If this server support subscription, the type that ' + 'subscription operations will be rooted at.', + type: __Type, + resolve: function resolve(schema) { + return schema.getSubscriptionType(); + } + }, + directives: { + description: 'A list of all directives supported by this server.', + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))), + resolve: function resolve(schema) { + return schema.getDirectives(); + } + } + }; + } +}); +export var __Directive = new GraphQLObjectType({ + name: '__Directive', + description: 'A Directive provides a way to describe alternate runtime execution and ' + 'type validation behavior in a GraphQL document.' + "\n\nIn some cases, you need to provide options to alter GraphQL's " + 'execution behavior in ways field arguments will not suffice, such as ' + 'conditionally including or skipping a field. Directives provide this by ' + 'describing additional information to the executor.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + locations: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))), + resolve: function resolve(obj) { + return obj.locations; + } + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: function resolve(directive) { + return directive.args || []; + } + } + }; + } +}); +export var __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: 'A Directive can be adjacent to many parts of the GraphQL language, a ' + '__DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.' + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.' + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.' + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.' + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.' + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.' + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.' + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.' + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.' + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.' + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.' + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.' + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.' + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.' + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.' + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.' + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.' + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.' + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.' + } + } +}); +export var __Type = new GraphQLObjectType({ + name: '__Type', + description: 'The fundamental unit of any GraphQL Schema is the type. There are ' + 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' + '\n\nDepending on the kind of a type, certain fields describe ' + 'information about that type. Scalar types provide no information ' + 'beyond a name and description, while Enum types provide their values. ' + 'Object and Interface types provide the fields they describe. Abstract ' + 'types, Union and Interface, provide the Object types possible ' + 'at runtime. List and NonNull types compose other types.', + fields: function fields() { + return { + kind: { + type: GraphQLNonNull(__TypeKind), + resolve: function resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } else if (isObjectType(type)) { + return TypeKind.OBJECT; + } else if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } else if (isUnionType(type)) { + return TypeKind.UNION; + } else if (isEnumType(type)) { + return TypeKind.ENUM; + } else if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } else if (isListType(type)) { + return TypeKind.LIST; + } else if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } + + throw new Error('Unknown kind of type: ' + type); + } + }, + name: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + fields: { + type: GraphQLList(GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref) { + var includeDeprecated = _ref.includeDeprecated; + + if (isObjectType(type) || isInterfaceType(type)) { + var fields = objectValues(type.getFields()); + + if (!includeDeprecated) { + fields = fields.filter(function (field) { + return !field.deprecationReason; + }); + } + + return fields; + } + + return null; + } + }, + interfaces: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve: function resolve(type) { + if (isObjectType(type)) { + return type.getInterfaces(); + } + } + }, + possibleTypes: { + type: GraphQLList(GraphQLNonNull(__Type)), + resolve: function resolve(type, args, context, _ref2) { + var schema = _ref2.schema; + + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + } + }, + enumValues: { + type: GraphQLList(GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false + } + }, + resolve: function resolve(type, _ref3) { + var includeDeprecated = _ref3.includeDeprecated; + + if (isEnumType(type)) { + var values = type.getValues(); + + if (!includeDeprecated) { + values = values.filter(function (value) { + return !value.deprecationReason; + }); + } + + return values; + } + } + }, + inputFields: { + type: GraphQLList(GraphQLNonNull(__InputValue)), + resolve: function resolve(type) { + if (isInputObjectType(type)) { + return objectValues(type.getFields()); + } + } + }, + ofType: { + type: __Type, + resolve: function resolve(obj) { + return obj.ofType; + } + } + }; + } +}); +export var __Field = new GraphQLObjectType({ + name: '__Field', + description: 'Object and Interface types are described by a list of Fields, each of ' + 'which has a name, potentially a list of arguments, and a return type.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + args: { + type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))), + resolve: function resolve(field) { + return field.args || []; + } + }, + type: { + type: GraphQLNonNull(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); +export var __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: 'Arguments provided to Fields or Directives and the input fields of an ' + 'InputObject are represented as Input Values which describe their type ' + 'and optionally a default value.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + type: { + type: GraphQLNonNull(__Type), + resolve: function resolve(obj) { + return obj.type; + } + }, + defaultValue: { + type: GraphQLString, + description: 'A GraphQL-formatted string representing the default value for this ' + 'input value.', + resolve: function resolve(inputVal) { + return isInvalid(inputVal.defaultValue) ? null : print(astFromValue(inputVal.defaultValue, inputVal.type)); + } + } + }; + } +}); +export var __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: 'One possible value for a given Enum. Enum values are unique values, not ' + 'a placeholder for a string or numeric value. However an Enum value is ' + 'returned in a JSON response as a string.', + fields: function fields() { + return { + name: { + type: GraphQLNonNull(GraphQLString), + resolve: function resolve(obj) { + return obj.name; + } + }, + description: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.description; + } + }, + isDeprecated: { + type: GraphQLNonNull(GraphQLBoolean), + resolve: function resolve(obj) { + return obj.isDeprecated; + } + }, + deprecationReason: { + type: GraphQLString, + resolve: function resolve(obj) { + return obj.deprecationReason; + } + } + }; + } +}); +export var TypeKind = { + SCALAR: 'SCALAR', + OBJECT: 'OBJECT', + INTERFACE: 'INTERFACE', + UNION: 'UNION', + ENUM: 'ENUM', + INPUT_OBJECT: 'INPUT_OBJECT', + LIST: 'LIST', + NON_NULL: 'NON_NULL' +}; +export var __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.' + }, + OBJECT: { + value: TypeKind.OBJECT, + description: 'Indicates this type is an object. ' + '`fields` and `interfaces` are valid fields.' + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: 'Indicates this type is an interface. ' + '`fields` and `possibleTypes` are valid fields.' + }, + UNION: { + value: TypeKind.UNION, + description: 'Indicates this type is a union. `possibleTypes` is a valid field.' + }, + ENUM: { + value: TypeKind.ENUM, + description: 'Indicates this type is an enum. `enumValues` is a valid field.' + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: 'Indicates this type is an input object. ' + '`inputFields` is a valid field.' + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.' + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: 'Indicates this type is a non-null. `ofType` is a valid field.' + } + } +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export var SchemaMetaFieldDef = { + name: '__schema', + type: GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: function resolve(source, args, context, _ref4) { + var schema = _ref4.schema; + return schema; + } +}; +export var TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [{ + name: 'name', + type: GraphQLNonNull(GraphQLString) + }], + resolve: function resolve(source, _ref5, context, _ref6) { + var name = _ref5.name; + var schema = _ref6.schema; + return schema.getType(name); + } +}; +export var TypeNameMetaFieldDef = { + name: '__typename', + type: GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: function resolve(source, args, context, _ref7) { + var parentType = _ref7.parentType; + return parentType.name; + } +}; +export var introspectionTypes = [__Schema, __Directive, __DirectiveLocation, __Type, __Field, __InputValue, __EnumValue, __TypeKind]; +export function isIntrospectionType(type) { + return isNamedType(type) && ( // Would prefer to use introspectionTypes.some(), however %checks needs + // a simple expression. + type.name === __Schema.name || type.name === __Directive.name || type.name === __DirectiveLocation.name || type.name === __Type.name || type.name === __Field.name || type.name === __InputValue.name || type.name === __EnumValue.name || type.name === __TypeKind.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/scalars.js b/node_modules/graphql/type/scalars.js new file mode 100644 index 00000000..ea797bb6 --- /dev/null +++ b/node_modules/graphql/type/scalars.js @@ -0,0 +1,244 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSpecifiedScalarType = isSpecifiedScalarType; +exports.specifiedScalarTypes = exports.GraphQLID = exports.GraphQLBoolean = exports.GraphQLString = exports.GraphQLFloat = exports.GraphQLInt = void 0; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _isFinite = _interopRequireDefault(require("../jsutils/isFinite")); + +var _isInteger = _interopRequireDefault(require("../jsutils/isInteger")); + +var _definition = require("./definition"); + +var _kinds = require("../language/kinds"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. +var MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function serializeInt(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!(0, _isInteger.default)(num)) { + throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value))); + } + + if (num > MAX_INT || num < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value))); + } + + return num; +} + +function coerceInt(value) { + if (!(0, _isInteger.default)(value)) { + throw new TypeError("Int cannot represent non-integer value: ".concat((0, _inspect.default)(value))); + } + + if (value > MAX_INT || value < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(ast) { + if (ast.kind === _kinds.Kind.INT) { + var num = parseInt(ast.value, 10); + + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + + return undefined; + } +}); +exports.GraphQLInt = GraphQLInt; + +function serializeFloat(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!(0, _isFinite.default)(num)) { + throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value))); + } + + return num; +} + +function coerceFloat(value) { + if (!(0, _isFinite.default)(value)) { + throw new TypeError("Float cannot represent non numeric value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.FLOAT || ast.kind === _kinds.Kind.INT ? parseFloat(ast.value) : undefined; + } +}); +exports.GraphQLFloat = GraphQLFloat; + +function serializeString(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an complex value which can be represented as a string + // (ex: MongoDB id objects). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof result === 'string') { + return result; + } + + if (typeof result === 'boolean') { + return result ? 'true' : 'false'; + } + + if ((0, _isFinite.default)(result)) { + return result.toString(); + } + + throw new TypeError("String cannot represent value: ".concat((0, _inspect.default)(value))); +} + +function coerceString(value) { + if (typeof value !== 'string') { + throw new TypeError("String cannot represent a non string value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.STRING ? ast.value : undefined; + } +}); +exports.GraphQLString = GraphQLString; + +function serializeBoolean(value) { + if (typeof value === 'boolean') { + return value; + } + + if ((0, _isFinite.default)(value)) { + return value !== 0; + } + + throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value))); +} + +function coerceBoolean(value) { + if (typeof value !== 'boolean') { + throw new TypeError("Boolean cannot represent a non boolean value: ".concat((0, _inspect.default)(value))); + } + + return value; +} + +var GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.BOOLEAN ? ast.value : undefined; + } +}); +exports.GraphQLBoolean = GraphQLBoolean; + +function serializeID(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an object identifier (ex. MongoDB). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; + + if (typeof result === 'string') { + return result; + } + + if ((0, _isInteger.default)(result)) { + return String(result); + } + + throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(value))); +} + +function coerceID(value) { + if (typeof value === 'string') { + return value; + } + + if ((0, _isInteger.default)(value)) { + return value.toString(); + } + + throw new TypeError("ID cannot represent value: ".concat((0, _inspect.default)(value))); +} + +var GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral: function parseLiteral(ast) { + return ast.kind === _kinds.Kind.STRING || ast.kind === _kinds.Kind.INT ? ast.value : undefined; + } +}); +exports.GraphQLID = GraphQLID; +var specifiedScalarTypes = [GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]; +exports.specifiedScalarTypes = specifiedScalarTypes; + +function isSpecifiedScalarType(type) { + return (0, _definition.isNamedType)(type) && ( // Would prefer to use specifiedScalarTypes.some(), however %checks needs + // a simple expression. + type.name === GraphQLString.name || type.name === GraphQLInt.name || type.name === GraphQLFloat.name || type.name === GraphQLBoolean.name || type.name === GraphQLID.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/scalars.js.flow b/node_modules/graphql/type/scalars.js.flow new file mode 100644 index 00000000..89f6ed25 --- /dev/null +++ b/node_modules/graphql/type/scalars.js.flow @@ -0,0 +1,253 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import isFinite from '../jsutils/isFinite'; +import isInteger from '../jsutils/isInteger'; +import { GraphQLScalarType, isNamedType } from './definition'; +import { Kind } from '../language/kinds'; + +// As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. +const MAX_INT = 2147483647; +const MIN_INT = -2147483648; + +function serializeInt(value: mixed): number { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + let num = value; + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!isInteger(num)) { + throw new TypeError( + `Int cannot represent non-integer value: ${inspect(value)}`, + ); + } + if (num > MAX_INT || num < MIN_INT) { + throw new TypeError( + `Int cannot represent non 32-bit signed integer value: ${inspect(value)}`, + ); + } + return num; +} + +function coerceInt(value: mixed): number { + if (!isInteger(value)) { + throw new TypeError( + `Int cannot represent non-integer value: ${inspect(value)}`, + ); + } + if (value > MAX_INT || value < MIN_INT) { + throw new TypeError( + `Int cannot represent non 32-bit signed integer value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: + 'The `Int` scalar type represents non-fractional signed whole numeric ' + + 'values. Int can represent values between -(2^31) and 2^31 - 1. ', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral(ast) { + if (ast.kind === Kind.INT) { + const num = parseInt(ast.value, 10); + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + return undefined; + }, +}); + +function serializeFloat(value: mixed): number { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + let num = value; + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + if (!isFinite(num)) { + throw new TypeError( + `Float cannot represent non numeric value: ${inspect(value)}`, + ); + } + return num; +} + +function coerceFloat(value: mixed): number { + if (!isFinite(value)) { + throw new TypeError( + `Float cannot represent non numeric value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: + 'The `Float` scalar type represents signed double-precision fractional ' + + 'values as specified by ' + + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral(ast) { + return ast.kind === Kind.FLOAT || ast.kind === Kind.INT + ? parseFloat(ast.value) + : undefined; + }, +}); + +function serializeString(value: mixed): string { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an complex value which can be represented as a string + // (ex: MongoDB id objects). + const result = + value && typeof value.valueOf === 'function' ? value.valueOf() : value; + // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + if (typeof result === 'string') { + return result; + } + if (typeof result === 'boolean') { + return result ? 'true' : 'false'; + } + if (isFinite(result)) { + return result.toString(); + } + throw new TypeError(`String cannot represent value: ${inspect(value)}`); +} + +function coerceString(value: mixed): string { + if (typeof value !== 'string') { + throw new TypeError( + `String cannot represent a non string value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLString = new GraphQLScalarType({ + name: 'String', + description: + 'The `String` scalar type represents textual data, represented as UTF-8 ' + + 'character sequences. The String type is most often used by GraphQL to ' + + 'represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral(ast) { + return ast.kind === Kind.STRING ? ast.value : undefined; + }, +}); + +function serializeBoolean(value: mixed): boolean { + if (typeof value === 'boolean') { + return value; + } + if (isFinite(value)) { + return value !== 0; + } + throw new TypeError( + `Boolean cannot represent a non boolean value: ${inspect(value)}`, + ); +} + +function coerceBoolean(value: mixed): boolean { + if (typeof value !== 'boolean') { + throw new TypeError( + `Boolean cannot represent a non boolean value: ${inspect(value)}`, + ); + } + return value; +} + +export const GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral(ast) { + return ast.kind === Kind.BOOLEAN ? ast.value : undefined; + }, +}); + +function serializeID(value: mixed): string { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an object identifier (ex. MongoDB). + const result = + value && typeof value.valueOf === 'function' ? value.valueOf() : value; + if (typeof result === 'string') { + return result; + } + if (isInteger(result)) { + return String(result); + } + throw new TypeError(`ID cannot represent value: ${inspect(value)}`); +} + +function coerceID(value: mixed): string { + if (typeof value === 'string') { + return value; + } + if (isInteger(value)) { + return value.toString(); + } + throw new TypeError(`ID cannot represent value: ${inspect(value)}`); +} + +export const GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: + 'The `ID` scalar type represents a unique identifier, often used to ' + + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + + 'response as a String; however, it is not intended to be human-readable. ' + + 'When expected as an input type, any string (such as `"4"`) or integer ' + + '(such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral(ast) { + return ast.kind === Kind.STRING || ast.kind === Kind.INT + ? ast.value + : undefined; + }, +}); + +export const specifiedScalarTypes: $ReadOnlyArray<*> = [ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, +]; + +export function isSpecifiedScalarType(type: mixed): boolean %checks { + return ( + isNamedType(type) && + // Would prefer to use specifiedScalarTypes.some(), however %checks needs + // a simple expression. + (type.name === GraphQLString.name || + type.name === GraphQLInt.name || + type.name === GraphQLFloat.name || + type.name === GraphQLBoolean.name || + type.name === GraphQLID.name) + ); +} diff --git a/node_modules/graphql/type/scalars.mjs b/node_modules/graphql/type/scalars.mjs new file mode 100644 index 00000000..3eec3120 --- /dev/null +++ b/node_modules/graphql/type/scalars.mjs @@ -0,0 +1,222 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +import isFinite from '../jsutils/isFinite'; +import isInteger from '../jsutils/isInteger'; +import { GraphQLScalarType, isNamedType } from './definition'; +import { Kind } from '../language/kinds'; // As per the GraphQL Spec, Integers are only treated as valid when a valid +// 32-bit signed integer, providing the broadest support across platforms. +// +// n.b. JavaScript's integers are safe between -(2^53 - 1) and 2^53 - 1 because +// they are internally represented as IEEE 754 doubles. + +var MAX_INT = 2147483647; +var MIN_INT = -2147483648; + +function serializeInt(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!isInteger(num)) { + throw new TypeError("Int cannot represent non-integer value: ".concat(inspect(value))); + } + + if (num > MAX_INT || num < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat(inspect(value))); + } + + return num; +} + +function coerceInt(value) { + if (!isInteger(value)) { + throw new TypeError("Int cannot represent non-integer value: ".concat(inspect(value))); + } + + if (value > MAX_INT || value < MIN_INT) { + throw new TypeError("Int cannot represent non 32-bit signed integer value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: 'The `Int` scalar type represents non-fractional signed whole numeric ' + 'values. Int can represent values between -(2^31) and 2^31 - 1. ', + serialize: serializeInt, + parseValue: coerceInt, + parseLiteral: function parseLiteral(ast) { + if (ast.kind === Kind.INT) { + var num = parseInt(ast.value, 10); + + if (num <= MAX_INT && num >= MIN_INT) { + return num; + } + } + + return undefined; + } +}); + +function serializeFloat(value) { + if (typeof value === 'boolean') { + return value ? 1 : 0; + } + + var num = value; + + if (typeof value === 'string' && value !== '') { + num = Number(value); + } + + if (!isFinite(num)) { + throw new TypeError("Float cannot represent non numeric value: ".concat(inspect(value))); + } + + return num; +} + +function coerceFloat(value) { + if (!isFinite(value)) { + throw new TypeError("Float cannot represent non numeric value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: 'The `Float` scalar type represents signed double-precision fractional ' + 'values as specified by ' + '[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ', + serialize: serializeFloat, + parseValue: coerceFloat, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.FLOAT || ast.kind === Kind.INT ? parseFloat(ast.value) : undefined; + } +}); + +function serializeString(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an complex value which can be represented as a string + // (ex: MongoDB id objects). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof result === 'string') { + return result; + } + + if (typeof result === 'boolean') { + return result ? 'true' : 'false'; + } + + if (isFinite(result)) { + return result.toString(); + } + + throw new TypeError("String cannot represent value: ".concat(inspect(value))); +} + +function coerceString(value) { + if (typeof value !== 'string') { + throw new TypeError("String cannot represent a non string value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLString = new GraphQLScalarType({ + name: 'String', + description: 'The `String` scalar type represents textual data, represented as UTF-8 ' + 'character sequences. The String type is most often used by GraphQL to ' + 'represent free-form human-readable text.', + serialize: serializeString, + parseValue: coerceString, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.STRING ? ast.value : undefined; + } +}); + +function serializeBoolean(value) { + if (typeof value === 'boolean') { + return value; + } + + if (isFinite(value)) { + return value !== 0; + } + + throw new TypeError("Boolean cannot represent a non boolean value: ".concat(inspect(value))); +} + +function coerceBoolean(value) { + if (typeof value !== 'boolean') { + throw new TypeError("Boolean cannot represent a non boolean value: ".concat(inspect(value))); + } + + return value; +} + +export var GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + serialize: serializeBoolean, + parseValue: coerceBoolean, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.BOOLEAN ? ast.value : undefined; + } +}); + +function serializeID(value) { + // Support serializing objects with custom valueOf() functions - a common way + // to represent an object identifier (ex. MongoDB). + var result = value && typeof value.valueOf === 'function' ? value.valueOf() : value; + + if (typeof result === 'string') { + return result; + } + + if (isInteger(result)) { + return String(result); + } + + throw new TypeError("ID cannot represent value: ".concat(inspect(value))); +} + +function coerceID(value) { + if (typeof value === 'string') { + return value; + } + + if (isInteger(value)) { + return value.toString(); + } + + throw new TypeError("ID cannot represent value: ".concat(inspect(value))); +} + +export var GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: 'The `ID` scalar type represents a unique identifier, often used to ' + 'refetch an object or as key for a cache. The ID type appears in a JSON ' + 'response as a String; however, it is not intended to be human-readable. ' + 'When expected as an input type, any string (such as `"4"`) or integer ' + '(such as `4`) input value will be accepted as an ID.', + serialize: serializeID, + parseValue: coerceID, + parseLiteral: function parseLiteral(ast) { + return ast.kind === Kind.STRING || ast.kind === Kind.INT ? ast.value : undefined; + } +}); +export var specifiedScalarTypes = [GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID]; +export function isSpecifiedScalarType(type) { + return isNamedType(type) && ( // Would prefer to use specifiedScalarTypes.some(), however %checks needs + // a simple expression. + type.name === GraphQLString.name || type.name === GraphQLInt.name || type.name === GraphQLFloat.name || type.name === GraphQLBoolean.name || type.name === GraphQLID.name); +} \ No newline at end of file diff --git a/node_modules/graphql/type/schema.js b/node_modules/graphql/type/schema.js new file mode 100644 index 00000000..3b7d32ff --- /dev/null +++ b/node_modules/graphql/type/schema.js @@ -0,0 +1,339 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isSchema = isSchema; +exports.GraphQLSchema = void 0; + +var _definition = require("./definition"); + +var _directives = require("./directives"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _introspection = require("./introspection"); + +var _defineToStringTag = _interopRequireDefault(require("../jsutils/defineToStringTag")); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +var _instanceOf = _interopRequireDefault(require("../jsutils/instanceOf")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +// eslint-disable-next-line no-redeclare +function isSchema(schema) { + return (0, _instanceOf.default)(schema, GraphQLSchema); +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ + + +var GraphQLSchema = +/*#__PURE__*/ +function () { + // Used as a cache for validateSchema(). + // Referenced by validateSchema(). + function GraphQLSchema(config) { + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_queryType", void 0); + + _defineProperty(this, "_mutationType", void 0); + + _defineProperty(this, "_subscriptionType", void 0); + + _defineProperty(this, "_directives", void 0); + + _defineProperty(this, "_typeMap", void 0); + + _defineProperty(this, "_implementations", void 0); + + _defineProperty(this, "_possibleTypeMap", void 0); + + _defineProperty(this, "__validationErrors", void 0); + + _defineProperty(this, "__allowedLegacyNames", void 0); + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + if (config && config.assumeValid) { + this.__validationErrors = []; + } else { + // Otherwise check for common mistakes during construction to produce + // clear and early error messages. + !(_typeof(config) === 'object') ? (0, _invariant.default)(0, 'Must provide configuration object.') : void 0; + !(!config.types || Array.isArray(config.types)) ? (0, _invariant.default)(0, "\"types\" must be Array if provided but got: ".concat((0, _inspect.default)(config.types), ".")) : void 0; + !(!config.directives || Array.isArray(config.directives)) ? (0, _invariant.default)(0, '"directives" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.directives), ".")) : void 0; + !(!config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames)) ? (0, _invariant.default)(0, '"allowedLegacyNames" must be Array if provided but got: ' + "".concat((0, _inspect.default)(config.allowedLegacyNames), ".")) : void 0; + } + + this.__allowedLegacyNames = config.allowedLegacyNames || []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = config.directives || _directives.specifiedDirectives; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; // Build type map now to detect any errors within this schema. + + var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), _introspection.__Schema]; + var types = config.types; + + if (types) { + initialTypes = initialTypes.concat(types); + } // Keep track of all types referenced within the schema. + + + var typeMap = Object.create(null); // First by deeply visiting all initial types. + + typeMap = initialTypes.reduce(typeMapReducer, typeMap); // Then by deeply visiting all directive types. + + typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); // Storing the resulting map for reference by the schema. + + this._typeMap = typeMap; // Keep track of all implementations by interface name. + + this._implementations = Object.create(null); + + var _arr = Object.keys(this._typeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + var type = this._typeMap[typeName]; + + if ((0, _definition.isObjectType)(type)) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = type.getInterfaces()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var iface = _step.value; + + if ((0, _definition.isInterfaceType)(iface)) { + var impls = this._implementations[iface.name]; + + if (impls) { + impls.push(type); + } else { + this._implementations[iface.name] = [type]; + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if ((0, _definition.isAbstractType)(type) && !this._implementations[type.name]) { + this._implementations[type.name] = []; + } + } + } + + var _proto = GraphQLSchema.prototype; + + _proto.getQueryType = function getQueryType() { + return this._queryType; + }; + + _proto.getMutationType = function getMutationType() { + return this._mutationType; + }; + + _proto.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + _proto.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + _proto.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + _proto.getPossibleTypes = function getPossibleTypes(abstractType) { + if ((0, _definition.isUnionType)(abstractType)) { + return abstractType.getTypes(); + } + + return this._implementations[abstractType.name]; + }; + + _proto.isPossibleType = function isPossibleType(abstractType, possibleType) { + var possibleTypeMap = this._possibleTypeMap; + + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + var possibleTypes = this.getPossibleTypes(abstractType); + possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) { + return map[type.name] = true, map; + }, Object.create(null)); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + }; + + _proto.getDirectives = function getDirectives() { + return this._directives; + }; + + _proto.getDirective = function getDirective(name) { + return (0, _find.default)(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + return GraphQLSchema; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + + +exports.GraphQLSchema = GraphQLSchema; +(0, _defineToStringTag.default)(GraphQLSchema); + +function typeMapReducer(map, type) { + if (!type) { + return map; + } + + if ((0, _definition.isWrappingType)(type)) { + return typeMapReducer(map, type.ofType); + } + + if (map[type.name]) { + !(map[type.name] === type) ? (0, _invariant.default)(0, 'Schema must contain unique named types but contains multiple ' + "types named \"".concat(type.name, "\".")) : void 0; + return map; + } + + map[type.name] = type; + var reducedMap = map; + + if ((0, _definition.isUnionType)(type)) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if ((0, _definition.isObjectType)(type)) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var field = _step2.value; + + if (field.args) { + var fieldArgTypes = field.args.map(function (arg) { + return arg.type; + }); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + + reducedMap = typeMapReducer(reducedMap, field.type); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + if ((0, _definition.isInputObjectType)(type)) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = (0, _objectValues.default)(type.getFields())[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _field = _step3.value; + reducedMap = typeMapReducer(reducedMap, _field.type); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return reducedMap; +} + +function typeMapDirectiveReducer(map, directive) { + // Directives are not validated until validateSchema() is called. + if (!(0, _directives.isDirective)(directive)) { + return map; + } + + return directive.args.reduce(function (_map, arg) { + return typeMapReducer(_map, arg.type); + }, map); +} \ No newline at end of file diff --git a/node_modules/graphql/type/schema.js.flow b/node_modules/graphql/type/schema.js.flow new file mode 100644 index 00000000..ad95d34a --- /dev/null +++ b/node_modules/graphql/type/schema.js.flow @@ -0,0 +1,329 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isAbstractType, + isObjectType, + isInterfaceType, + isUnionType, + isInputObjectType, + isWrappingType, +} from './definition'; +import type { + GraphQLType, + GraphQLNamedType, + GraphQLAbstractType, + GraphQLObjectType, +} from './definition'; +import type { + SchemaDefinitionNode, + SchemaExtensionNode, +} from '../language/ast'; +import { + GraphQLDirective, + isDirective, + specifiedDirectives, +} from './directives'; +import type { GraphQLError } from '../error/GraphQLError'; +import inspect from '../jsutils/inspect'; +import { __Schema } from './introspection'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import find from '../jsutils/find'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +import type { ObjMap } from '../jsutils/ObjMap'; + +/** + * Test if the given value is a GraphQL schema. + */ +declare function isSchema(schema: mixed): boolean %checks(schema instanceof + GraphQLSchema); +// eslint-disable-next-line no-redeclare +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ +export class GraphQLSchema { + astNode: ?SchemaDefinitionNode; + extensionASTNodes: ?$ReadOnlyArray; + _queryType: ?GraphQLObjectType; + _mutationType: ?GraphQLObjectType; + _subscriptionType: ?GraphQLObjectType; + _directives: $ReadOnlyArray; + _typeMap: TypeMap; + _implementations: ObjMap>; + _possibleTypeMap: ?ObjMap>; + // Used as a cache for validateSchema(). + __validationErrors: ?$ReadOnlyArray; + // Referenced by validateSchema(). + __allowedLegacyNames: $ReadOnlyArray; + + constructor(config: GraphQLSchemaConfig): void { + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + if (config && config.assumeValid) { + this.__validationErrors = []; + } else { + // Otherwise check for common mistakes during construction to produce + // clear and early error messages. + invariant( + typeof config === 'object', + 'Must provide configuration object.', + ); + invariant( + !config.types || Array.isArray(config.types), + `"types" must be Array if provided but got: ${inspect(config.types)}.`, + ); + invariant( + !config.directives || Array.isArray(config.directives), + '"directives" must be Array if provided but got: ' + + `${inspect(config.directives)}.`, + ); + invariant( + !config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames), + '"allowedLegacyNames" must be Array if provided but got: ' + + `${inspect(config.allowedLegacyNames)}.`, + ); + } + + this.__allowedLegacyNames = config.allowedLegacyNames || []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; + // Provide specified directives (e.g. @include and @skip) by default. + this._directives = config.directives || specifiedDirectives; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; + + // Build type map now to detect any errors within this schema. + let initialTypes: Array = [ + this.getQueryType(), + this.getMutationType(), + this.getSubscriptionType(), + __Schema, + ]; + + const types = config.types; + if (types) { + initialTypes = initialTypes.concat(types); + } + + // Keep track of all types referenced within the schema. + let typeMap: TypeMap = Object.create(null); + + // First by deeply visiting all initial types. + typeMap = initialTypes.reduce(typeMapReducer, typeMap); + + // Then by deeply visiting all directive types. + typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); + + // Storing the resulting map for reference by the schema. + this._typeMap = typeMap; + + // Keep track of all implementations by interface name. + this._implementations = Object.create(null); + for (const typeName of Object.keys(this._typeMap)) { + const type = this._typeMap[typeName]; + if (isObjectType(type)) { + for (const iface of type.getInterfaces()) { + if (isInterfaceType(iface)) { + const impls = this._implementations[iface.name]; + if (impls) { + impls.push(type); + } else { + this._implementations[iface.name] = [type]; + } + } + } + } else if (isAbstractType(type) && !this._implementations[type.name]) { + this._implementations[type.name] = []; + } + } + } + + getQueryType(): ?GraphQLObjectType { + return this._queryType; + } + + getMutationType(): ?GraphQLObjectType { + return this._mutationType; + } + + getSubscriptionType(): ?GraphQLObjectType { + return this._subscriptionType; + } + + getTypeMap(): TypeMap { + return this._typeMap; + } + + getType(name: string): ?GraphQLNamedType { + return this.getTypeMap()[name]; + } + + getPossibleTypes( + abstractType: GraphQLAbstractType, + ): $ReadOnlyArray { + if (isUnionType(abstractType)) { + return abstractType.getTypes(); + } + return this._implementations[abstractType.name]; + } + + isPossibleType( + abstractType: GraphQLAbstractType, + possibleType: GraphQLObjectType, + ): boolean { + let possibleTypeMap = this._possibleTypeMap; + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + const possibleTypes = this.getPossibleTypes(abstractType); + possibleTypeMap[abstractType.name] = possibleTypes.reduce( + (map, type) => ((map[type.name] = true), map), + Object.create(null), + ); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + } + + getDirectives(): $ReadOnlyArray { + return this._directives; + } + + getDirective(name: string): ?GraphQLDirective { + return find(this.getDirectives(), directive => directive.name === name); + } +} + +// Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported +defineToStringTag(GraphQLSchema); + +type TypeMap = ObjMap; + +export type GraphQLSchemaValidationOptions = {| + /** + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + */ + assumeValid?: boolean, + + /** + * If provided, the schema will consider fields or types with names included + * in this list valid, even if they do not adhere to the specification's + * schema validation rules. + * + * This option is provided to ease adoption and will be removed in v15. + */ + allowedLegacyNames?: ?$ReadOnlyArray, +|}; + +export type GraphQLSchemaConfig = {| + query?: ?GraphQLObjectType, + mutation?: ?GraphQLObjectType, + subscription?: ?GraphQLObjectType, + types?: ?Array, + directives?: ?Array, + astNode?: ?SchemaDefinitionNode, + extensionASTNodes?: ?$ReadOnlyArray, + ...GraphQLSchemaValidationOptions, +|}; + +function typeMapReducer(map: TypeMap, type: ?GraphQLType): TypeMap { + if (!type) { + return map; + } + if (isWrappingType(type)) { + return typeMapReducer(map, type.ofType); + } + if (map[type.name]) { + invariant( + map[type.name] === type, + 'Schema must contain unique named types but contains multiple ' + + `types named "${type.name}".`, + ); + return map; + } + map[type.name] = type; + + let reducedMap = map; + + if (isUnionType(type)) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type)) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type) || isInterfaceType(type)) { + for (const field of objectValues(type.getFields())) { + if (field.args) { + const fieldArgTypes = field.args.map(arg => arg.type); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + reducedMap = typeMapReducer(reducedMap, field.type); + } + } + + if (isInputObjectType(type)) { + for (const field of objectValues(type.getFields())) { + reducedMap = typeMapReducer(reducedMap, field.type); + } + } + + return reducedMap; +} + +function typeMapDirectiveReducer( + map: TypeMap, + directive: ?GraphQLDirective, +): TypeMap { + // Directives are not validated until validateSchema() is called. + if (!isDirective(directive)) { + return map; + } + return directive.args.reduce( + (_map, arg) => typeMapReducer(_map, arg.type), + map, + ); +} diff --git a/node_modules/graphql/type/schema.mjs b/node_modules/graphql/type/schema.mjs new file mode 100644 index 00000000..5e3ef733 --- /dev/null +++ b/node_modules/graphql/type/schema.mjs @@ -0,0 +1,325 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isAbstractType, isObjectType, isInterfaceType, isUnionType, isInputObjectType, isWrappingType } from './definition'; +import { GraphQLDirective, isDirective, specifiedDirectives } from './directives'; +import inspect from '../jsutils/inspect'; +import { __Schema } from './introspection'; +import defineToStringTag from '../jsutils/defineToStringTag'; +import find from '../jsutils/find'; +import instanceOf from '../jsutils/instanceOf'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +// eslint-disable-next-line no-redeclare +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * + * Example: + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }) + * + * Note: If an array of `directives` are provided to GraphQLSchema, that will be + * the exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. @include and + * @skip) will be used. If you wish to provide *additional* directives to these + * specified directives, you must explicitly declare them. Example: + * + * const MyAppSchema = new GraphQLSchema({ + * ... + * directives: specifiedDirectives.concat([ myCustomDirective ]), + * }) + * + */ + +export var GraphQLSchema = +/*#__PURE__*/ +function () { + // Used as a cache for validateSchema(). + // Referenced by validateSchema(). + function GraphQLSchema(config) { + _defineProperty(this, "astNode", void 0); + + _defineProperty(this, "extensionASTNodes", void 0); + + _defineProperty(this, "_queryType", void 0); + + _defineProperty(this, "_mutationType", void 0); + + _defineProperty(this, "_subscriptionType", void 0); + + _defineProperty(this, "_directives", void 0); + + _defineProperty(this, "_typeMap", void 0); + + _defineProperty(this, "_implementations", void 0); + + _defineProperty(this, "_possibleTypeMap", void 0); + + _defineProperty(this, "__validationErrors", void 0); + + _defineProperty(this, "__allowedLegacyNames", void 0); + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + if (config && config.assumeValid) { + this.__validationErrors = []; + } else { + // Otherwise check for common mistakes during construction to produce + // clear and early error messages. + !(_typeof(config) === 'object') ? invariant(0, 'Must provide configuration object.') : void 0; + !(!config.types || Array.isArray(config.types)) ? invariant(0, "\"types\" must be Array if provided but got: ".concat(inspect(config.types), ".")) : void 0; + !(!config.directives || Array.isArray(config.directives)) ? invariant(0, '"directives" must be Array if provided but got: ' + "".concat(inspect(config.directives), ".")) : void 0; + !(!config.allowedLegacyNames || Array.isArray(config.allowedLegacyNames)) ? invariant(0, '"allowedLegacyNames" must be Array if provided but got: ' + "".concat(inspect(config.allowedLegacyNames), ".")) : void 0; + } + + this.__allowedLegacyNames = config.allowedLegacyNames || []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = config.directives || specifiedDirectives; + this.astNode = config.astNode; + this.extensionASTNodes = config.extensionASTNodes; // Build type map now to detect any errors within this schema. + + var initialTypes = [this.getQueryType(), this.getMutationType(), this.getSubscriptionType(), __Schema]; + var types = config.types; + + if (types) { + initialTypes = initialTypes.concat(types); + } // Keep track of all types referenced within the schema. + + + var typeMap = Object.create(null); // First by deeply visiting all initial types. + + typeMap = initialTypes.reduce(typeMapReducer, typeMap); // Then by deeply visiting all directive types. + + typeMap = this._directives.reduce(typeMapDirectiveReducer, typeMap); // Storing the resulting map for reference by the schema. + + this._typeMap = typeMap; // Keep track of all implementations by interface name. + + this._implementations = Object.create(null); + + var _arr = Object.keys(this._typeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + var type = this._typeMap[typeName]; + + if (isObjectType(type)) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = type.getInterfaces()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var iface = _step.value; + + if (isInterfaceType(iface)) { + var impls = this._implementations[iface.name]; + + if (impls) { + impls.push(type); + } else { + this._implementations[iface.name] = [type]; + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } else if (isAbstractType(type) && !this._implementations[type.name]) { + this._implementations[type.name] = []; + } + } + } + + var _proto = GraphQLSchema.prototype; + + _proto.getQueryType = function getQueryType() { + return this._queryType; + }; + + _proto.getMutationType = function getMutationType() { + return this._mutationType; + }; + + _proto.getSubscriptionType = function getSubscriptionType() { + return this._subscriptionType; + }; + + _proto.getTypeMap = function getTypeMap() { + return this._typeMap; + }; + + _proto.getType = function getType(name) { + return this.getTypeMap()[name]; + }; + + _proto.getPossibleTypes = function getPossibleTypes(abstractType) { + if (isUnionType(abstractType)) { + return abstractType.getTypes(); + } + + return this._implementations[abstractType.name]; + }; + + _proto.isPossibleType = function isPossibleType(abstractType, possibleType) { + var possibleTypeMap = this._possibleTypeMap; + + if (!possibleTypeMap) { + this._possibleTypeMap = possibleTypeMap = Object.create(null); + } + + if (!possibleTypeMap[abstractType.name]) { + var possibleTypes = this.getPossibleTypes(abstractType); + possibleTypeMap[abstractType.name] = possibleTypes.reduce(function (map, type) { + return map[type.name] = true, map; + }, Object.create(null)); + } + + return Boolean(possibleTypeMap[abstractType.name][possibleType.name]); + }; + + _proto.getDirectives = function getDirectives() { + return this._directives; + }; + + _proto.getDirective = function getDirective(name) { + return find(this.getDirectives(), function (directive) { + return directive.name === name; + }); + }; + + return GraphQLSchema; +}(); // Conditionally apply `[Symbol.toStringTag]` if `Symbol`s are supported + +defineToStringTag(GraphQLSchema); + +function typeMapReducer(map, type) { + if (!type) { + return map; + } + + if (isWrappingType(type)) { + return typeMapReducer(map, type.ofType); + } + + if (map[type.name]) { + !(map[type.name] === type) ? invariant(0, 'Schema must contain unique named types but contains multiple ' + "types named \"".concat(type.name, "\".")) : void 0; + return map; + } + + map[type.name] = type; + var reducedMap = map; + + if (isUnionType(type)) { + reducedMap = type.getTypes().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type)) { + reducedMap = type.getInterfaces().reduce(typeMapReducer, reducedMap); + } + + if (isObjectType(type) || isInterfaceType(type)) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = objectValues(type.getFields())[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var field = _step2.value; + + if (field.args) { + var fieldArgTypes = field.args.map(function (arg) { + return arg.type; + }); + reducedMap = fieldArgTypes.reduce(typeMapReducer, reducedMap); + } + + reducedMap = typeMapReducer(reducedMap, field.type); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + if (isInputObjectType(type)) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = objectValues(type.getFields())[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _field = _step3.value; + reducedMap = typeMapReducer(reducedMap, _field.type); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return reducedMap; +} + +function typeMapDirectiveReducer(map, directive) { + // Directives are not validated until validateSchema() is called. + if (!isDirective(directive)) { + return map; + } + + return directive.args.reduce(function (_map, arg) { + return typeMapReducer(_map, arg.type); + }, map); +} \ No newline at end of file diff --git a/node_modules/graphql/type/validate.js b/node_modules/graphql/type/validate.js new file mode 100644 index 00000000..274ce594 --- /dev/null +++ b/node_modules/graphql/type/validate.js @@ -0,0 +1,808 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validateSchema = validateSchema; +exports.assertValidSchema = assertValidSchema; + +var _definition = require("./definition"); + +var _directives = require("./directives"); + +var _introspection = require("./introspection"); + +var _schema = require("./schema"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _GraphQLError = require("../error/GraphQLError"); + +var _assertValidName = require("../utilities/assertValidName"); + +var _typeComparators = require("../utilities/typeComparators"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + !(0, _schema.isSchema)(schema) ? (0, _invariant.default)(0, "Expected ".concat((0, _inspect.default)(schema), " to be a GraphQL schema.")) : void 0; // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + + var context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + var errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + + +function assertValidSchema(schema) { + var errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} + +var SchemaValidationContext = +/*#__PURE__*/ +function () { + function SchemaValidationContext(schema) { + _defineProperty(this, "_errors", void 0); + + _defineProperty(this, "schema", void 0); + + this._errors = []; + this.schema = schema; + } + + var _proto = SchemaValidationContext.prototype; + + _proto.reportError = function reportError(message, nodes) { + var _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean); + + this.addError(new _GraphQLError.GraphQLError(message, _nodes)); + }; + + _proto.addError = function addError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + return SchemaValidationContext; +}(); + +function validateRootTypes(context) { + var schema = context.schema; + var queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError("Query root type must be provided.", schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + context.reportError("Query root type must be Object type, it cannot be ".concat((0, _inspect.default)(queryType), "."), getOperationTypeNode(schema, queryType, 'query')); + } + + var mutationType = schema.getMutationType(); + + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(mutationType), "."), getOperationTypeNode(schema, mutationType, 'mutation')); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat((0, _inspect.default)(subscriptionType), "."), getOperationTypeNode(schema, subscriptionType, 'subscription')); + } +} + +function getOperationTypeNode(schema, type, operation) { + var operationNodes = getAllSubNodes(schema, function (node) { + return node.operationTypes; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = operationNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.operation === operation) { + return node.type; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return type.astNode; +} + +function validateDirectives(context) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = context.schema.getDirectives()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError("Expected directive but got: ".concat((0, _inspect.default)(directive), "."), directive && directive.astNode); + continue; + } // Ensure they are named correctly. + + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + var argNames = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directive.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var arg = _step3.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per directive. + + if (argNames[argName]) { + context.reportError("Argument @".concat(directive.name, "(").concat(argName, ":) can only be defined once."), getAllDirectiveArgNodes(directive, argName)); + continue; + } + + argNames[argName] = true; // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError("The type of @".concat(directive.name, "(").concat(argName, ":) must be Input Type ") + "but got: ".concat((0, _inspect.default)(arg.type), "."), getDirectiveArgTypeNode(directive, argName)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } +} + +function validateName(context, node) { + // If a schema explicitly allows some legacy name which is no longer valid, + // allow it to be assumed valid. + if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) { + return; + } // Ensure names are valid, however introspection types opt out. + + + var error = (0, _assertValidName.isValidNameError)(node.name, node.astNode || undefined); + + if (error) { + context.addError(error); + } +} + +function validateTypes(context) { + var typeMap = context.schema.getTypeMap(); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = (0, _objectValues.default)(typeMap)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var type = _step4.value; + + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError("Expected GraphQL named type but got: ".concat((0, _inspect.default)(type), "."), type && type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateObjectInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } +} + +function validateFields(context, type) { + var fields = (0, _objectValues.default)(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type)); + } + + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = fields[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var field = _step5.value; + // Ensure they are named correctly. + validateName(context, field); // Ensure they were defined at most once. + + var fieldNodes = getAllFieldNodes(type, field.name); + + if (fieldNodes.length > 1) { + context.reportError("Field ".concat(type.name, ".").concat(field.name, " can only be defined once."), fieldNodes); + continue; + } // Ensure the type is an output type + + + if (!(0, _definition.isOutputType)(field.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), getFieldTypeNode(type, field.name)); + } // Ensure the arguments are valid + + + var argNames = Object.create(null); + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = field.args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var arg = _step6.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per field. + + if (argNames[argName]) { + context.reportError("Field argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) can only ") + 'be defined once.', getAllFieldArgNodes(type, field.name, argName)); + } + + argNames[argName] = true; // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat((0, _inspect.default)(arg.type), "."), getFieldArgTypeNode(type, field.name, argName)); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } +} + +function validateObjectInterfaces(context, object) { + var implementedTypeNames = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = object.getInterfaces()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var iface = _step7.value; + + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError("Type ".concat((0, _inspect.default)(object), " must only implement Interface types, ") + "it cannot implement ".concat((0, _inspect.default)(iface), "."), getImplementsInterfaceNode(object, iface)); + continue; + } + + if (implementedTypeNames[iface.name]) { + context.reportError("Type ".concat(object.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(object, iface)); + continue; + } + + implementedTypeNames[iface.name] = true; + validateObjectImplementsInterface(context, object, iface); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } +} + +function validateObjectImplementsInterface(context, object, iface) { + var objectFieldMap = object.getFields(); + var ifaceFieldMap = iface.getFields(); // Assert each interface field is implemented. + + var _arr = Object.keys(ifaceFieldMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var objectField = objectFieldMap[fieldName]; + var ifaceField = ifaceFieldMap[fieldName]; // Assert interface field exists on object. + + if (!objectField) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ") + "".concat(object.name, " does not provide it."), [getFieldNode(iface, fieldName)].concat(getAllNodes(object))); + continue; + } // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + + + if (!(0, _typeComparators.isTypeSubTypeOf)(context.schema, objectField.type, ifaceField.type)) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat((0, _inspect.default)(ifaceField.type), " but ").concat(object.name, ".").concat(fieldName, " ") + "is type ".concat((0, _inspect.default)(objectField.type), "."), [getFieldTypeNode(iface, fieldName), getFieldTypeNode(object, fieldName)]); + } // Assert each interface field arg is implemented. + + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + var _loop = function _loop() { + var ifaceArg = _step8.value; + var argName = ifaceArg.name; + var objectArg = (0, _find.default)(objectField.args, function (arg) { + return arg.name === argName; + }); // Assert interface field arg exists on object field. + + if (!objectArg) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expected but ".concat(object.name, ".").concat(fieldName, " does not provide it."), [getFieldArgNode(iface, fieldName, argName), getFieldNode(object, fieldName)]); + return "continue"; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, objectArg.type)) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat((0, _inspect.default)(ifaceArg.type), " but ") + "".concat(object.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat((0, _inspect.default)(objectArg.type), "."), [getFieldArgTypeNode(iface, fieldName, argName), getFieldArgTypeNode(object, fieldName, argName)]); + } // TODO: validate default values? + + }; + + for (var _iterator8 = ifaceField.args[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _ret = _loop(); + + if (_ret === "continue") continue; + } // Assert additional arguments must not be required. + + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + var _loop2 = function _loop2() { + var objectArg = _step9.value; + var argName = objectArg.name; + var ifaceArg = (0, _find.default)(ifaceField.args, function (arg) { + return arg.name === argName; + }); + + if (!ifaceArg && (0, _definition.isRequiredArgument)(objectArg)) { + context.reportError("Object field ".concat(object.name, ".").concat(fieldName, " includes required ") + "argument ".concat(argName, " that is missing from the Interface field ") + "".concat(iface.name, ".").concat(fieldName, "."), [getFieldArgNode(object, fieldName, argName), getFieldNode(iface, fieldName)]); + } + }; + + for (var _iterator9 = objectField.args[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } +} + +function validateUnionMembers(context, union) { + var memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union)); + } + + var includedTypeNames = Object.create(null); + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = memberTypes[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var memberType = _step10.value; + + if (includedTypeNames[memberType.name]) { + context.reportError("Union type ".concat(union.name, " can only include type ") + "".concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat((0, _inspect.default)(memberType), "."), getUnionMemberTypeNodes(union, String(memberType))); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } +} + +function validateEnumValues(context, enumType) { + var enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType)); + } + + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = enumValues[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var enumValue = _step11.value; + var valueName = enumValue.name; // Ensure no duplicates. + + var allNodes = getEnumValueNodes(enumType, valueName); + + if (allNodes && allNodes.length > 1) { + context.reportError("Enum type ".concat(enumType.name, " can include value ").concat(valueName, " only once."), allNodes); + } // Ensure valid name. + + + validateName(context, enumValue); + + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode); + } + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } +} + +function validateInputFields(context, inputObj) { + var fields = (0, _objectValues.default)(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj)); + } // Ensure the arguments are valid + + + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = fields[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var field = _step12.value; + // Ensure they are named correctly. + validateName(context, field); // TODO: Ensure they are unique per field. + // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat((0, _inspect.default)(field.type), "."), field.astNode && field.astNode.type); + } + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } +} + +function getAllNodes(object) { + var astNode = object.astNode, + extensionASTNodes = object.extensionASTNodes; + return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes || []; +} + +function getAllSubNodes(object, getter) { + var result = []; + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = getAllNodes(object)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var astNode = _step13.value; + + if (astNode) { + var subNodes = getter(astNode); + + if (subNodes) { + result = result.concat(subNodes); + } + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return result; +} + +function getImplementsInterfaceNode(type, iface) { + return getAllImplementsInterfaceNodes(type, iface)[0]; +} + +function getAllImplementsInterfaceNodes(type, iface) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.interfaces; + }).filter(function (ifaceNode) { + return ifaceNode.name.value === iface.name; + }); +} + +function getFieldNode(type, fieldName) { + return getAllFieldNodes(type, fieldName)[0]; +} + +function getAllFieldNodes(type, fieldName) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.fields; + }).filter(function (fieldNode) { + return fieldNode.name.value === fieldName; + }); +} + +function getFieldTypeNode(type, fieldName) { + var fieldNode = getFieldNode(type, fieldName); + return fieldNode && fieldNode.type; +} + +function getFieldArgNode(type, fieldName, argName) { + return getAllFieldArgNodes(type, fieldName, argName)[0]; +} + +function getAllFieldArgNodes(type, fieldName, argName) { + var argNodes = []; + var fieldNode = getFieldNode(type, fieldName); + + if (fieldNode && fieldNode.arguments) { + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = fieldNode.arguments[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var node = _step14.value; + + if (node.name.value === argName) { + argNodes.push(node); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + } + + return argNodes; +} + +function getFieldArgTypeNode(type, fieldName, argName) { + var fieldArgNode = getFieldArgNode(type, fieldName, argName); + return fieldArgNode && fieldArgNode.type; +} + +function getAllDirectiveArgNodes(directive, argName) { + return getAllSubNodes(directive, function (directiveNode) { + return directiveNode.arguments; + }).filter(function (argNode) { + return argNode.name.value === argName; + }); +} + +function getDirectiveArgTypeNode(directive, argName) { + var argNode = getAllDirectiveArgNodes(directive, argName)[0]; + return argNode && argNode.type; +} + +function getUnionMemberTypeNodes(union, typeName) { + return getAllSubNodes(union, function (unionNode) { + return unionNode.types; + }).filter(function (typeNode) { + return typeNode.name.value === typeName; + }); +} + +function getEnumValueNodes(enumType, valueName) { + return getAllSubNodes(enumType, function (enumNode) { + return enumNode.values; + }).filter(function (valueNode) { + return valueNode.name.value === valueName; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/type/validate.js.flow b/node_modules/graphql/type/validate.js.flow new file mode 100644 index 00000000..22f3423d --- /dev/null +++ b/node_modules/graphql/type/validate.js.flow @@ -0,0 +1,697 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isNamedType, + isInputType, + isOutputType, + isRequiredArgument, +} from './definition'; +import type { + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, +} from './definition'; +import { isDirective } from './directives'; +import type { GraphQLDirective } from './directives'; +import { isIntrospectionType } from './introspection'; +import { isSchema } from './schema'; +import type { GraphQLSchema } from './schema'; +import inspect from '../jsutils/inspect'; +import find from '../jsutils/find'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLError } from '../error/GraphQLError'; +import type { + ASTNode, + FieldDefinitionNode, + EnumValueDefinitionNode, + InputValueDefinitionNode, + NamedTypeNode, + TypeNode, +} from '../language/ast'; +import { isValidNameError } from '../utilities/assertValidName'; +import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators'; + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ +export function validateSchema( + schema: GraphQLSchema, +): $ReadOnlyArray { + // First check to ensure the provided value is in fact a GraphQLSchema. + invariant( + isSchema(schema), + `Expected ${inspect(schema)} to be a GraphQL schema.`, + ); + + // If this Schema has already been validated, return the previous results. + if (schema.__validationErrors) { + return schema.__validationErrors; + } + + // Validate the schema, producing a list of errors. + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); + + // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} + +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ +export function assertValidSchema(schema: GraphQLSchema): void { + const errors = validateSchema(schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} + +class SchemaValidationContext { + +_errors: Array; + +schema: GraphQLSchema; + + constructor(schema) { + this._errors = []; + this.schema = schema; + } + + reportError( + message: string, + nodes?: $ReadOnlyArray | ?ASTNode, + ): void { + const _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean); + this.addError(new GraphQLError(message, _nodes)); + } + + addError(error: GraphQLError): void { + this._errors.push(error); + } + + getErrors(): $ReadOnlyArray { + return this._errors; + } +} + +function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + if (!queryType) { + context.reportError(`Query root type must be provided.`, schema.astNode); + } else if (!isObjectType(queryType)) { + context.reportError( + `Query root type must be Object type, it cannot be ${inspect( + queryType, + )}.`, + getOperationTypeNode(schema, queryType, 'query'), + ); + } + + const mutationType = schema.getMutationType(); + if (mutationType && !isObjectType(mutationType)) { + context.reportError( + 'Mutation root type must be Object type if provided, it cannot be ' + + `${inspect(mutationType)}.`, + getOperationTypeNode(schema, mutationType, 'mutation'), + ); + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && !isObjectType(subscriptionType)) { + context.reportError( + 'Subscription root type must be Object type if provided, it cannot be ' + + `${inspect(subscriptionType)}.`, + getOperationTypeNode(schema, subscriptionType, 'subscription'), + ); + } +} + +function getOperationTypeNode( + schema: GraphQLSchema, + type: GraphQLObjectType, + operation: string, +): ?ASTNode { + const operationNodes = getAllSubNodes(schema, node => node.operationTypes); + for (const node of operationNodes) { + if (node.operation === operation) { + return node.type; + } + } + + return type.astNode; +} + +function validateDirectives(context: SchemaValidationContext): void { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError( + `Expected directive but got: ${inspect(directive)}.`, + directive && directive.astNode, + ); + continue; + } + + // Ensure they are named correctly. + validateName(context, directive); + + // TODO: Ensure proper locations. + + // Ensure the arguments are valid. + const argNames = Object.create(null); + for (const arg of directive.args) { + const argName = arg.name; + + // Ensure they are named correctly. + validateName(context, arg); + + // Ensure they are unique per directive. + if (argNames[argName]) { + context.reportError( + `Argument @${directive.name}(${argName}:) can only be defined once.`, + getAllDirectiveArgNodes(directive, argName), + ); + continue; + } + argNames[argName] = true; + + // Ensure the type is an input type. + if (!isInputType(arg.type)) { + context.reportError( + `The type of @${directive.name}(${argName}:) must be Input Type ` + + `but got: ${inspect(arg.type)}.`, + getDirectiveArgTypeNode(directive, argName), + ); + } + } + } +} + +function validateName( + context: SchemaValidationContext, + node: { +name: string, +astNode: ?ASTNode }, +): void { + // If a schema explicitly allows some legacy name which is no longer valid, + // allow it to be assumed valid. + if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) { + return; + } + // Ensure names are valid, however introspection types opt out. + const error = isValidNameError(node.name, node.astNode || undefined); + if (error) { + context.addError(error); + } +} + +function validateTypes(context: SchemaValidationContext): void { + const typeMap = context.schema.getTypeMap(); + for (const type of objectValues(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError( + `Expected GraphQL named type but got: ${inspect(type)}.`, + type && type.astNode, + ); + continue; + } + + // Ensure it is named correctly (excluding introspection types). + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); + + // Ensure objects implement the interfaces they claim to. + validateObjectInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + } + } +} + +function validateFields( + context: SchemaValidationContext, + type: GraphQLObjectType | GraphQLInterfaceType, +): void { + const fields = objectValues(type.getFields()); + + // Objects and Interfaces both must define one or more fields. + if (fields.length === 0) { + context.reportError( + `Type ${type.name} must define one or more fields.`, + getAllNodes(type), + ); + } + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); + + // Ensure they were defined at most once. + const fieldNodes = getAllFieldNodes(type, field.name); + if (fieldNodes.length > 1) { + context.reportError( + `Field ${type.name}.${field.name} can only be defined once.`, + fieldNodes, + ); + continue; + } + + // Ensure the type is an output type + if (!isOutputType(field.type)) { + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${inspect(field.type)}.`, + getFieldTypeNode(type, field.name), + ); + } + + // Ensure the arguments are valid + const argNames = Object.create(null); + for (const arg of field.args) { + const argName = arg.name; + + // Ensure they are named correctly. + validateName(context, arg); + + // Ensure they are unique per field. + if (argNames[argName]) { + context.reportError( + `Field argument ${type.name}.${field.name}(${argName}:) can only ` + + 'be defined once.', + getAllFieldArgNodes(type, field.name, argName), + ); + } + argNames[argName] = true; + + // Ensure the type is an input type + if (!isInputType(arg.type)) { + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${inspect(arg.type)}.`, + getFieldArgTypeNode(type, field.name, argName), + ); + } + } + } +} + +function validateObjectInterfaces( + context: SchemaValidationContext, + object: GraphQLObjectType, +): void { + const implementedTypeNames = Object.create(null); + for (const iface of object.getInterfaces()) { + if (!isInterfaceType(iface)) { + context.reportError( + `Type ${inspect(object)} must only implement Interface types, ` + + `it cannot implement ${inspect(iface)}.`, + getImplementsInterfaceNode(object, iface), + ); + continue; + } + + if (implementedTypeNames[iface.name]) { + context.reportError( + `Type ${object.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(object, iface), + ); + continue; + } + implementedTypeNames[iface.name] = true; + validateObjectImplementsInterface(context, object, iface); + } +} + +function validateObjectImplementsInterface( + context: SchemaValidationContext, + object: GraphQLObjectType, + iface: GraphQLInterfaceType, +): void { + const objectFieldMap = object.getFields(); + const ifaceFieldMap = iface.getFields(); + + // Assert each interface field is implemented. + for (const fieldName of Object.keys(ifaceFieldMap)) { + const objectField = objectFieldMap[fieldName]; + const ifaceField = ifaceFieldMap[fieldName]; + + // Assert interface field exists on object. + if (!objectField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ` + + `${object.name} does not provide it.`, + [getFieldNode(iface, fieldName), ...getAllNodes(object)], + ); + continue; + } + + // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + if (!isTypeSubTypeOf(context.schema, objectField.type, ifaceField.type)) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${inspect(ifaceField.type)} but ${object.name}.${fieldName} ` + + `is type ${inspect(objectField.type)}.`, + [ + getFieldTypeNode(iface, fieldName), + getFieldTypeNode(object, fieldName), + ], + ); + } + + // Assert each interface field arg is implemented. + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const objectArg = find(objectField.args, arg => arg.name === argName); + + // Assert interface field arg exists on object field. + if (!objectArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expected but ${object.name}.${fieldName} does not provide it.`, + [ + getFieldArgNode(iface, fieldName, argName), + getFieldNode(object, fieldName), + ], + ); + continue; + } + + // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + if (!isEqualType(ifaceArg.type, objectArg.type)) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${inspect(ifaceArg.type)} but ` + + `${object.name}.${fieldName}(${argName}:) is type ` + + `${inspect(objectArg.type)}.`, + [ + getFieldArgTypeNode(iface, fieldName, argName), + getFieldArgTypeNode(object, fieldName, argName), + ], + ); + } + + // TODO: validate default values? + } + + // Assert additional arguments must not be required. + for (const objectArg of objectField.args) { + const argName = objectArg.name; + const ifaceArg = find(ifaceField.args, arg => arg.name === argName); + if (!ifaceArg && isRequiredArgument(objectArg)) { + context.reportError( + `Object field ${object.name}.${fieldName} includes required ` + + `argument ${argName} that is missing from the Interface field ` + + `${iface.name}.${fieldName}.`, + [ + getFieldArgNode(object, fieldName, argName), + getFieldNode(iface, fieldName), + ], + ); + } + } + } +} + +function validateUnionMembers( + context: SchemaValidationContext, + union: GraphQLUnionType, +): void { + const memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + getAllNodes(union), + ); + } + + const includedTypeNames = Object.create(null); + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ` + + `${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name), + ); + continue; + } + includedTypeNames[memberType.name] = true; + if (!isObjectType(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${inspect(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)), + ); + } + } +} + +function validateEnumValues( + context: SchemaValidationContext, + enumType: GraphQLEnumType, +): void { + const enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + getAllNodes(enumType), + ); + } + + for (const enumValue of enumValues) { + const valueName = enumValue.name; + + // Ensure no duplicates. + const allNodes = getEnumValueNodes(enumType, valueName); + if (allNodes && allNodes.length > 1) { + context.reportError( + `Enum type ${enumType.name} can include value ${valueName} only once.`, + allNodes, + ); + } + + // Ensure valid name. + validateName(context, enumValue); + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError( + `Enum type ${enumType.name} cannot include value: ${valueName}.`, + enumValue.astNode, + ); + } + } +} + +function validateInputFields( + context: SchemaValidationContext, + inputObj: GraphQLInputObjectType, +): void { + const fields = objectValues(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + getAllNodes(inputObj), + ); + } + + // Ensure the arguments are valid + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); + + // TODO: Ensure they are unique per field. + + // Ensure the type is an input type + if (!isInputType(field.type)) { + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${inspect(field.type)}.`, + field.astNode && field.astNode.type, + ); + } + } +} + +type SDLDefinedObject = { + +astNode: ?T, + +extensionASTNodes?: ?$ReadOnlyArray, +}; + +function getAllNodes( + object: SDLDefinedObject, +): $ReadOnlyArray { + const { astNode, extensionASTNodes } = object; + return astNode + ? extensionASTNodes + ? [astNode].concat(extensionASTNodes) + : [astNode] + : extensionASTNodes || []; +} + +function getAllSubNodes( + object: SDLDefinedObject, + getter: (T | K) => ?(L | $ReadOnlyArray), +): $ReadOnlyArray { + let result = []; + for (const astNode of getAllNodes(object)) { + if (astNode) { + const subNodes = getter(astNode); + if (subNodes) { + result = result.concat(subNodes); + } + } + } + return result; +} + +function getImplementsInterfaceNode( + type: GraphQLObjectType, + iface: GraphQLInterfaceType, +): ?NamedTypeNode { + return getAllImplementsInterfaceNodes(type, iface)[0]; +} + +function getAllImplementsInterfaceNodes( + type: GraphQLObjectType, + iface: GraphQLInterfaceType, +): $ReadOnlyArray { + return getAllSubNodes(type, typeNode => typeNode.interfaces).filter( + ifaceNode => ifaceNode.name.value === iface.name, + ); +} + +function getFieldNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, +): ?FieldDefinitionNode { + return getAllFieldNodes(type, fieldName)[0]; +} + +function getAllFieldNodes( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, +): $ReadOnlyArray { + return getAllSubNodes(type, typeNode => typeNode.fields).filter( + fieldNode => fieldNode.name.value === fieldName, + ); +} + +function getFieldTypeNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, +): ?TypeNode { + const fieldNode = getFieldNode(type, fieldName); + return fieldNode && fieldNode.type; +} + +function getFieldArgNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, + argName: string, +): ?InputValueDefinitionNode { + return getAllFieldArgNodes(type, fieldName, argName)[0]; +} + +function getAllFieldArgNodes( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, + argName: string, +): $ReadOnlyArray { + const argNodes = []; + const fieldNode = getFieldNode(type, fieldName); + if (fieldNode && fieldNode.arguments) { + for (const node of fieldNode.arguments) { + if (node.name.value === argName) { + argNodes.push(node); + } + } + } + return argNodes; +} + +function getFieldArgTypeNode( + type: GraphQLObjectType | GraphQLInterfaceType, + fieldName: string, + argName: string, +): ?TypeNode { + const fieldArgNode = getFieldArgNode(type, fieldName, argName); + return fieldArgNode && fieldArgNode.type; +} + +function getAllDirectiveArgNodes( + directive: GraphQLDirective, + argName: string, +): $ReadOnlyArray { + return getAllSubNodes( + directive, + directiveNode => directiveNode.arguments, + ).filter(argNode => argNode.name.value === argName); +} + +function getDirectiveArgTypeNode( + directive: GraphQLDirective, + argName: string, +): ?TypeNode { + const argNode = getAllDirectiveArgNodes(directive, argName)[0]; + return argNode && argNode.type; +} + +function getUnionMemberTypeNodes( + union: GraphQLUnionType, + typeName: string, +): ?$ReadOnlyArray { + return getAllSubNodes(union, unionNode => unionNode.types).filter( + typeNode => typeNode.name.value === typeName, + ); +} + +function getEnumValueNodes( + enumType: GraphQLEnumType, + valueName: string, +): ?$ReadOnlyArray { + return getAllSubNodes(enumType, enumNode => enumNode.values).filter( + valueNode => valueNode.name.value === valueName, + ); +} diff --git a/node_modules/graphql/type/validate.mjs b/node_modules/graphql/type/validate.mjs new file mode 100644 index 00000000..10de50d0 --- /dev/null +++ b/node_modules/graphql/type/validate.mjs @@ -0,0 +1,795 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isNamedType, isInputType, isOutputType, isRequiredArgument } from './definition'; +import { isDirective } from './directives'; +import { isIntrospectionType } from './introspection'; +import { isSchema } from './schema'; +import inspect from '../jsutils/inspect'; +import find from '../jsutils/find'; +import invariant from '../jsutils/invariant'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLError } from '../error/GraphQLError'; +import { isValidNameError } from '../utilities/assertValidName'; +import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators'; +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + */ + +export function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + !isSchema(schema) ? invariant(0, "Expected ".concat(inspect(schema), " to be a GraphQL schema.")) : void 0; // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + + var context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + var errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + */ + +export function assertValidSchema(schema) { + var errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} + +var SchemaValidationContext = +/*#__PURE__*/ +function () { + function SchemaValidationContext(schema) { + _defineProperty(this, "_errors", void 0); + + _defineProperty(this, "schema", void 0); + + this._errors = []; + this.schema = schema; + } + + var _proto = SchemaValidationContext.prototype; + + _proto.reportError = function reportError(message, nodes) { + var _nodes = (Array.isArray(nodes) ? nodes : [nodes]).filter(Boolean); + + this.addError(new GraphQLError(message, _nodes)); + }; + + _proto.addError = function addError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + return SchemaValidationContext; +}(); + +function validateRootTypes(context) { + var schema = context.schema; + var queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError("Query root type must be provided.", schema.astNode); + } else if (!isObjectType(queryType)) { + context.reportError("Query root type must be Object type, it cannot be ".concat(inspect(queryType), "."), getOperationTypeNode(schema, queryType, 'query')); + } + + var mutationType = schema.getMutationType(); + + if (mutationType && !isObjectType(mutationType)) { + context.reportError('Mutation root type must be Object type if provided, it cannot be ' + "".concat(inspect(mutationType), "."), getOperationTypeNode(schema, mutationType, 'mutation')); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !isObjectType(subscriptionType)) { + context.reportError('Subscription root type must be Object type if provided, it cannot be ' + "".concat(inspect(subscriptionType), "."), getOperationTypeNode(schema, subscriptionType, 'subscription')); + } +} + +function getOperationTypeNode(schema, type, operation) { + var operationNodes = getAllSubNodes(schema, function (node) { + return node.operationTypes; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = operationNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var node = _step.value; + + if (node.operation === operation) { + return node.type; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return type.astNode; +} + +function validateDirectives(context) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = context.schema.getDirectives()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError("Expected directive but got: ".concat(inspect(directive), "."), directive && directive.astNode); + continue; + } // Ensure they are named correctly. + + + validateName(context, directive); // TODO: Ensure proper locations. + // Ensure the arguments are valid. + + var argNames = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directive.args[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var arg = _step3.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per directive. + + if (argNames[argName]) { + context.reportError("Argument @".concat(directive.name, "(").concat(argName, ":) can only be defined once."), getAllDirectiveArgNodes(directive, argName)); + continue; + } + + argNames[argName] = true; // Ensure the type is an input type. + + if (!isInputType(arg.type)) { + context.reportError("The type of @".concat(directive.name, "(").concat(argName, ":) must be Input Type ") + "but got: ".concat(inspect(arg.type), "."), getDirectiveArgTypeNode(directive, argName)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } +} + +function validateName(context, node) { + // If a schema explicitly allows some legacy name which is no longer valid, + // allow it to be assumed valid. + if (context.schema.__allowedLegacyNames.indexOf(node.name) !== -1) { + return; + } // Ensure names are valid, however introspection types opt out. + + + var error = isValidNameError(node.name, node.astNode || undefined); + + if (error) { + context.addError(error); + } +} + +function validateTypes(context) { + var typeMap = context.schema.getTypeMap(); + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = objectValues(typeMap)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var type = _step4.value; + + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError("Expected GraphQL named type but got: ".concat(inspect(type), "."), type && type.astNode); + continue; + } // Ensure it is named correctly (excluding introspection types). + + + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateObjectInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } +} + +function validateFields(context, type) { + var fields = objectValues(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError("Type ".concat(type.name, " must define one or more fields."), getAllNodes(type)); + } + + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = fields[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var field = _step5.value; + // Ensure they are named correctly. + validateName(context, field); // Ensure they were defined at most once. + + var fieldNodes = getAllFieldNodes(type, field.name); + + if (fieldNodes.length > 1) { + context.reportError("Field ".concat(type.name, ".").concat(field.name, " can only be defined once."), fieldNodes); + continue; + } // Ensure the type is an output type + + + if (!isOutputType(field.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, " must be Output Type ") + "but got: ".concat(inspect(field.type), "."), getFieldTypeNode(type, field.name)); + } // Ensure the arguments are valid + + + var argNames = Object.create(null); + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = field.args[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var arg = _step6.value; + var argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure they are unique per field. + + if (argNames[argName]) { + context.reportError("Field argument ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) can only ") + 'be defined once.', getAllFieldArgNodes(type, field.name, argName)); + } + + argNames[argName] = true; // Ensure the type is an input type + + if (!isInputType(arg.type)) { + context.reportError("The type of ".concat(type.name, ".").concat(field.name, "(").concat(argName, ":) must be Input ") + "Type but got: ".concat(inspect(arg.type), "."), getFieldArgTypeNode(type, field.name, argName)); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } +} + +function validateObjectInterfaces(context, object) { + var implementedTypeNames = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = object.getInterfaces()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var iface = _step7.value; + + if (!isInterfaceType(iface)) { + context.reportError("Type ".concat(inspect(object), " must only implement Interface types, ") + "it cannot implement ".concat(inspect(iface), "."), getImplementsInterfaceNode(object, iface)); + continue; + } + + if (implementedTypeNames[iface.name]) { + context.reportError("Type ".concat(object.name, " can only implement ").concat(iface.name, " once."), getAllImplementsInterfaceNodes(object, iface)); + continue; + } + + implementedTypeNames[iface.name] = true; + validateObjectImplementsInterface(context, object, iface); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } +} + +function validateObjectImplementsInterface(context, object, iface) { + var objectFieldMap = object.getFields(); + var ifaceFieldMap = iface.getFields(); // Assert each interface field is implemented. + + var _arr = Object.keys(ifaceFieldMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var objectField = objectFieldMap[fieldName]; + var ifaceField = ifaceFieldMap[fieldName]; // Assert interface field exists on object. + + if (!objectField) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expected but ") + "".concat(object.name, " does not provide it."), [getFieldNode(iface, fieldName)].concat(getAllNodes(object))); + continue; + } // Assert interface field type is satisfied by object field type, by being + // a valid subtype. (covariant) + + + if (!isTypeSubTypeOf(context.schema, objectField.type, ifaceField.type)) { + context.reportError("Interface field ".concat(iface.name, ".").concat(fieldName, " expects type ") + "".concat(inspect(ifaceField.type), " but ").concat(object.name, ".").concat(fieldName, " ") + "is type ".concat(inspect(objectField.type), "."), [getFieldTypeNode(iface, fieldName), getFieldTypeNode(object, fieldName)]); + } // Assert each interface field arg is implemented. + + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + var _loop = function _loop() { + var ifaceArg = _step8.value; + var argName = ifaceArg.name; + var objectArg = find(objectField.args, function (arg) { + return arg.name === argName; + }); // Assert interface field arg exists on object field. + + if (!objectArg) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expected but ".concat(object.name, ".").concat(fieldName, " does not provide it."), [getFieldArgNode(iface, fieldName, argName), getFieldNode(object, fieldName)]); + return "continue"; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + + if (!isEqualType(ifaceArg.type, objectArg.type)) { + context.reportError("Interface field argument ".concat(iface.name, ".").concat(fieldName, "(").concat(argName, ":) ") + "expects type ".concat(inspect(ifaceArg.type), " but ") + "".concat(object.name, ".").concat(fieldName, "(").concat(argName, ":) is type ") + "".concat(inspect(objectArg.type), "."), [getFieldArgTypeNode(iface, fieldName, argName), getFieldArgTypeNode(object, fieldName, argName)]); + } // TODO: validate default values? + + }; + + for (var _iterator8 = ifaceField.args[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _ret = _loop(); + + if (_ret === "continue") continue; + } // Assert additional arguments must not be required. + + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + var _loop2 = function _loop2() { + var objectArg = _step9.value; + var argName = objectArg.name; + var ifaceArg = find(ifaceField.args, function (arg) { + return arg.name === argName; + }); + + if (!ifaceArg && isRequiredArgument(objectArg)) { + context.reportError("Object field ".concat(object.name, ".").concat(fieldName, " includes required ") + "argument ".concat(argName, " that is missing from the Interface field ") + "".concat(iface.name, ".").concat(fieldName, "."), [getFieldArgNode(object, fieldName, argName), getFieldNode(iface, fieldName)]); + } + }; + + for (var _iterator9 = objectField.args[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } +} + +function validateUnionMembers(context, union) { + var memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError("Union type ".concat(union.name, " must define one or more member types."), getAllNodes(union)); + } + + var includedTypeNames = Object.create(null); + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = memberTypes[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var memberType = _step10.value; + + if (includedTypeNames[memberType.name]) { + context.reportError("Union type ".concat(union.name, " can only include type ") + "".concat(memberType.name, " once."), getUnionMemberTypeNodes(union, memberType.name)); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!isObjectType(memberType)) { + context.reportError("Union type ".concat(union.name, " can only include Object types, ") + "it cannot include ".concat(inspect(memberType), "."), getUnionMemberTypeNodes(union, String(memberType))); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } +} + +function validateEnumValues(context, enumType) { + var enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError("Enum type ".concat(enumType.name, " must define one or more values."), getAllNodes(enumType)); + } + + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = enumValues[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var enumValue = _step11.value; + var valueName = enumValue.name; // Ensure no duplicates. + + var allNodes = getEnumValueNodes(enumType, valueName); + + if (allNodes && allNodes.length > 1) { + context.reportError("Enum type ".concat(enumType.name, " can include value ").concat(valueName, " only once."), allNodes); + } // Ensure valid name. + + + validateName(context, enumValue); + + if (valueName === 'true' || valueName === 'false' || valueName === 'null') { + context.reportError("Enum type ".concat(enumType.name, " cannot include value: ").concat(valueName, "."), enumValue.astNode); + } + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } +} + +function validateInputFields(context, inputObj) { + var fields = objectValues(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError("Input Object type ".concat(inputObj.name, " must define one or more fields."), getAllNodes(inputObj)); + } // Ensure the arguments are valid + + + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = fields[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var field = _step12.value; + // Ensure they are named correctly. + validateName(context, field); // TODO: Ensure they are unique per field. + // Ensure the type is an input type + + if (!isInputType(field.type)) { + context.reportError("The type of ".concat(inputObj.name, ".").concat(field.name, " must be Input Type ") + "but got: ".concat(inspect(field.type), "."), field.astNode && field.astNode.type); + } + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } +} + +function getAllNodes(object) { + var astNode = object.astNode, + extensionASTNodes = object.extensionASTNodes; + return astNode ? extensionASTNodes ? [astNode].concat(extensionASTNodes) : [astNode] : extensionASTNodes || []; +} + +function getAllSubNodes(object, getter) { + var result = []; + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = getAllNodes(object)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var astNode = _step13.value; + + if (astNode) { + var subNodes = getter(astNode); + + if (subNodes) { + result = result.concat(subNodes); + } + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return result; +} + +function getImplementsInterfaceNode(type, iface) { + return getAllImplementsInterfaceNodes(type, iface)[0]; +} + +function getAllImplementsInterfaceNodes(type, iface) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.interfaces; + }).filter(function (ifaceNode) { + return ifaceNode.name.value === iface.name; + }); +} + +function getFieldNode(type, fieldName) { + return getAllFieldNodes(type, fieldName)[0]; +} + +function getAllFieldNodes(type, fieldName) { + return getAllSubNodes(type, function (typeNode) { + return typeNode.fields; + }).filter(function (fieldNode) { + return fieldNode.name.value === fieldName; + }); +} + +function getFieldTypeNode(type, fieldName) { + var fieldNode = getFieldNode(type, fieldName); + return fieldNode && fieldNode.type; +} + +function getFieldArgNode(type, fieldName, argName) { + return getAllFieldArgNodes(type, fieldName, argName)[0]; +} + +function getAllFieldArgNodes(type, fieldName, argName) { + var argNodes = []; + var fieldNode = getFieldNode(type, fieldName); + + if (fieldNode && fieldNode.arguments) { + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = fieldNode.arguments[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var node = _step14.value; + + if (node.name.value === argName) { + argNodes.push(node); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + } + + return argNodes; +} + +function getFieldArgTypeNode(type, fieldName, argName) { + var fieldArgNode = getFieldArgNode(type, fieldName, argName); + return fieldArgNode && fieldArgNode.type; +} + +function getAllDirectiveArgNodes(directive, argName) { + return getAllSubNodes(directive, function (directiveNode) { + return directiveNode.arguments; + }).filter(function (argNode) { + return argNode.name.value === argName; + }); +} + +function getDirectiveArgTypeNode(directive, argName) { + var argNode = getAllDirectiveArgNodes(directive, argName)[0]; + return argNode && argNode.type; +} + +function getUnionMemberTypeNodes(union, typeName) { + return getAllSubNodes(union, function (unionNode) { + return unionNode.types; + }).filter(function (typeNode) { + return typeNode.name.value === typeName; + }); +} + +function getEnumValueNodes(enumType, valueName) { + return getAllSubNodes(enumType, function (enumNode) { + return enumNode.values; + }).filter(function (valueNode) { + return valueNode.name.value === valueName; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/TypeInfo.js b/node_modules/graphql/utilities/TypeInfo.js new file mode 100644 index 00000000..81813c18 --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.js @@ -0,0 +1,345 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.TypeInfo = void 0; + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +var _introspection = require("../type/introspection"); + +var _typeFromAST = require("./typeFromAST"); + +var _find = _interopRequireDefault(require("../jsutils/find")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +var TypeInfo = +/*#__PURE__*/ +function () { + function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals + initialType) { + _defineProperty(this, "_schema", void 0); + + _defineProperty(this, "_typeStack", void 0); + + _defineProperty(this, "_parentTypeStack", void 0); + + _defineProperty(this, "_inputTypeStack", void 0); + + _defineProperty(this, "_fieldDefStack", void 0); + + _defineProperty(this, "_defaultValueStack", void 0); + + _defineProperty(this, "_directive", void 0); + + _defineProperty(this, "_argument", void 0); + + _defineProperty(this, "_enumValue", void 0); + + _defineProperty(this, "_getFieldDef", void 0); + + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + + var _proto = TypeInfo.prototype; + + _proto.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + _proto.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + _proto.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + _proto.getParentInputType = function getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + }; + + _proto.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + _proto.getDefaultValue = function getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + }; + + _proto.getDirective = function getDirective() { + return this._directive; + }; + + _proto.getArgument = function getArgument() { + return this._argument; + }; + + _proto.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + _proto.enter = function enter(node) { + var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + var namedType = (0, _definition.getNamedType)(this.getType()); + + this._parentTypeStack.push((0, _definition.isCompositeType)(namedType) ? namedType : undefined); + + break; + + case _kinds.Kind.FIELD: + var parentType = this.getParentType(); + var fieldDef; + var fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push((0, _definition.isOutputType)(fieldType) ? fieldType : undefined); + + break; + + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case _kinds.Kind.OPERATION_DEFINITION: + var type; + + if (node.operation === 'query') { + type = schema.getQueryType(); + } else if (node.operation === 'mutation') { + type = schema.getMutationType(); + } else if (node.operation === 'subscription') { + type = schema.getSubscriptionType(); + } + + this._typeStack.push((0, _definition.isObjectType)(type) ? type : undefined); + + break; + + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + var typeConditionAST = node.typeCondition; + var outputType = typeConditionAST ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) : (0, _definition.getNamedType)(this.getType()); + + this._typeStack.push((0, _definition.isOutputType)(outputType) ? outputType : undefined); + + break; + + case _kinds.Kind.VARIABLE_DEFINITION: + var inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + + this._inputTypeStack.push((0, _definition.isInputType)(inputType) ? inputType : undefined); + + break; + + case _kinds.Kind.ARGUMENT: + var argDef; + var argType; + var fieldOrDirective = this.getDirective() || this.getFieldDef(); + + if (fieldOrDirective) { + argDef = (0, _find.default)(fieldOrDirective.args, function (arg) { + return arg.name === node.name.value; + }); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push((0, _definition.isInputType)(argType) ? argType : undefined); + + break; + + case _kinds.Kind.LIST: + var listType = (0, _definition.getNullableType)(this.getInputType()); + var itemType = (0, _definition.isListType)(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push((0, _definition.isInputType)(itemType) ? itemType : undefined); + + break; + + case _kinds.Kind.OBJECT_FIELD: + var objectType = (0, _definition.getNamedType)(this.getInputType()); + var inputFieldType; + var inputField; + + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); + + this._inputTypeStack.push((0, _definition.isInputType)(inputFieldType) ? inputFieldType : undefined); + + break; + + case _kinds.Kind.ENUM: + var enumType = (0, _definition.getNamedType)(this.getInputType()); + var enumValue; + + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + }; + + _proto.leave = function leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + } + }; + + return TypeInfo; +}(); +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ + + +exports.TypeInfo = TypeInfo; + +function getFieldDef(schema, parentType, fieldNode) { + var name = fieldNode.name.value; + + if (name === _introspection.SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.SchemaMetaFieldDef; + } + + if (name === _introspection.TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return _introspection.TypeMetaFieldDef; + } + + if (name === _introspection.TypeNameMetaFieldDef.name && (0, _definition.isCompositeType)(parentType)) { + return _introspection.TypeNameMetaFieldDef; + } + + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + return parentType.getFields()[name]; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/TypeInfo.js.flow b/node_modules/graphql/utilities/TypeInfo.js.flow new file mode 100644 index 00000000..b217131a --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.js.flow @@ -0,0 +1,313 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { Kind } from '../language/kinds'; +import { + isObjectType, + isInterfaceType, + isEnumType, + isInputObjectType, + isListType, + isCompositeType, + isInputType, + isOutputType, + getNullableType, + getNamedType, +} from '../type/definition'; +import type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, + GraphQLInputField, + GraphQLEnumValue, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection'; +import type { GraphQLSchema } from '../type/schema'; +import type { ASTNode, FieldNode } from '../language/ast'; +import { typeFromAST } from './typeFromAST'; +import find from '../jsutils/find'; + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +export class TypeInfo { + _schema: GraphQLSchema; + _typeStack: Array; + _parentTypeStack: Array; + _inputTypeStack: Array; + _fieldDefStack: Array>; + _defaultValueStack: Array; + _directive: ?GraphQLDirective; + _argument: ?GraphQLArgument; + _enumValue: ?GraphQLEnumValue; + _getFieldDef: typeof getFieldDef; + + constructor( + schema: GraphQLSchema, + // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + // It may disappear in the future. + getFieldDefFn?: typeof getFieldDef, + // Initial type may be provided in rare cases to facilitate traversals + // beginning somewhere other than documents. + initialType?: GraphQLType, + ): void { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + if (initialType) { + if (isInputType(initialType)) { + this._inputTypeStack.push(initialType); + } + if (isCompositeType(initialType)) { + this._parentTypeStack.push(initialType); + } + if (isOutputType(initialType)) { + this._typeStack.push(initialType); + } + } + } + + getType(): ?GraphQLOutputType { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + + getParentType(): ?GraphQLCompositeType { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + + getInputType(): ?GraphQLInputType { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + + getParentInputType(): ?GraphQLInputType { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + + getFieldDef(): ?GraphQLField<*, *> { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + + getDefaultValue(): ?mixed { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + + getDirective(): ?GraphQLDirective { + return this._directive; + } + + getArgument(): ?GraphQLArgument { + return this._argument; + } + + getEnumValue(): ?GraphQLEnumValue { + return this._enumValue; + } + + enter(node: ASTNode) { + const schema = this._schema; + // Note: many of the types below are explicitly typed as "mixed" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + switch (node.kind) { + case Kind.SELECTION_SET: + const namedType: mixed = getNamedType(this.getType()); + this._parentTypeStack.push( + isCompositeType(namedType) ? namedType : undefined, + ); + break; + case Kind.FIELD: + const parentType = this.getParentType(); + let fieldDef; + let fieldType: mixed; + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + if (fieldDef) { + fieldType = fieldDef.type; + } + } + this._fieldDefStack.push(fieldDef); + this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined); + break; + case Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + case Kind.OPERATION_DEFINITION: + let type: mixed; + if (node.operation === 'query') { + type = schema.getQueryType(); + } else if (node.operation === 'mutation') { + type = schema.getMutationType(); + } else if (node.operation === 'subscription') { + type = schema.getSubscriptionType(); + } + this._typeStack.push(isObjectType(type) ? type : undefined); + break; + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + const typeConditionAST = node.typeCondition; + const outputType: mixed = typeConditionAST + ? typeFromAST(schema, typeConditionAST) + : getNamedType(this.getType()); + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + break; + case Kind.VARIABLE_DEFINITION: + const inputType: mixed = typeFromAST(schema, node.type); + this._inputTypeStack.push( + isInputType(inputType) ? inputType : undefined, + ); + break; + case Kind.ARGUMENT: + let argDef; + let argType: mixed; + const fieldOrDirective = this.getDirective() || this.getFieldDef(); + if (fieldOrDirective) { + argDef = find( + fieldOrDirective.args, + arg => arg.name === node.name.value, + ); + if (argDef) { + argType = argDef.type; + } + } + this._argument = argDef; + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + this._inputTypeStack.push(isInputType(argType) ? argType : undefined); + break; + case Kind.LIST: + const listType: mixed = getNullableType(this.getInputType()); + const itemType: mixed = isListType(listType) + ? listType.ofType + : listType; + // List positions never have a default value. + this._defaultValueStack.push(undefined); + this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined); + break; + case Kind.OBJECT_FIELD: + const objectType: mixed = getNamedType(this.getInputType()); + let inputFieldType: GraphQLInputType | void; + let inputField: GraphQLInputField | void; + if (isInputObjectType(objectType)) { + inputField = objectType.getFields()[node.name.value]; + if (inputField) { + inputFieldType = inputField.type; + } + } + this._defaultValueStack.push( + inputField ? inputField.defaultValue : undefined, + ); + this._inputTypeStack.push( + isInputType(inputFieldType) ? inputFieldType : undefined, + ); + break; + case Kind.ENUM: + const enumType: mixed = getNamedType(this.getInputType()); + let enumValue; + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + this._enumValue = enumValue; + break; + } + } + + leave(node: ASTNode) { + switch (node.kind) { + case Kind.SELECTION_SET: + this._parentTypeStack.pop(); + break; + case Kind.FIELD: + this._fieldDefStack.pop(); + this._typeStack.pop(); + break; + case Kind.DIRECTIVE: + this._directive = null; + break; + case Kind.OPERATION_DEFINITION: + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + break; + case Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + break; + case Kind.ARGUMENT: + this._argument = null; + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case Kind.LIST: + case Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + this._inputTypeStack.pop(); + break; + case Kind.ENUM: + this._enumValue = null; + break; + } + } +} + +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ +function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +): ?GraphQLField<*, *> { + const name = fieldNode.name.value; + if ( + name === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } + if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } + if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) { + return TypeNameMetaFieldDef; + } + if (isObjectType(parentType) || isInterfaceType(parentType)) { + return parentType.getFields()[name]; + } +} diff --git a/node_modules/graphql/utilities/TypeInfo.mjs b/node_modules/graphql/utilities/TypeInfo.mjs new file mode 100644 index 00000000..d74e661d --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.mjs @@ -0,0 +1,337 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from '../language/kinds'; +import { isObjectType, isInterfaceType, isEnumType, isInputObjectType, isListType, isCompositeType, isInputType, isOutputType, getNullableType, getNamedType } from '../type/definition'; +import { SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef } from '../type/introspection'; +import { typeFromAST } from './typeFromAST'; +import find from '../jsutils/find'; +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + +export var TypeInfo = +/*#__PURE__*/ +function () { + function TypeInfo(schema, // NOTE: this experimental optional second parameter is only needed in order + // to support non-spec-compliant codebases. You should never need to use it. + getFieldDefFn, // Initial type may be provided in rare cases to facilitate traversals + initialType) { + _defineProperty(this, "_schema", void 0); + + _defineProperty(this, "_typeStack", void 0); + + _defineProperty(this, "_parentTypeStack", void 0); + + _defineProperty(this, "_inputTypeStack", void 0); + + _defineProperty(this, "_fieldDefStack", void 0); + + _defineProperty(this, "_defaultValueStack", void 0); + + _defineProperty(this, "_directive", void 0); + + _defineProperty(this, "_argument", void 0); + + _defineProperty(this, "_enumValue", void 0); + + _defineProperty(this, "_getFieldDef", void 0); + + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = getFieldDefFn || getFieldDef; + + if (initialType) { + if (isInputType(initialType)) { + this._inputTypeStack.push(initialType); + } + + if (isCompositeType(initialType)) { + this._parentTypeStack.push(initialType); + } + + if (isOutputType(initialType)) { + this._typeStack.push(initialType); + } + } + } + + var _proto = TypeInfo.prototype; + + _proto.getType = function getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + }; + + _proto.getParentType = function getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + }; + + _proto.getInputType = function getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + }; + + _proto.getParentInputType = function getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + }; + + _proto.getFieldDef = function getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + }; + + _proto.getDefaultValue = function getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + }; + + _proto.getDirective = function getDirective() { + return this._directive; + }; + + _proto.getArgument = function getArgument() { + return this._argument; + }; + + _proto.getEnumValue = function getEnumValue() { + return this._enumValue; + }; + + _proto.enter = function enter(node) { + var schema = this._schema; // Note: many of the types below are explicitly typed as "mixed" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case Kind.SELECTION_SET: + var namedType = getNamedType(this.getType()); + + this._parentTypeStack.push(isCompositeType(namedType) ? namedType : undefined); + + break; + + case Kind.FIELD: + var parentType = this.getParentType(); + var fieldDef; + var fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined); + + break; + + case Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case Kind.OPERATION_DEFINITION: + var type; + + if (node.operation === 'query') { + type = schema.getQueryType(); + } else if (node.operation === 'mutation') { + type = schema.getMutationType(); + } else if (node.operation === 'subscription') { + type = schema.getSubscriptionType(); + } + + this._typeStack.push(isObjectType(type) ? type : undefined); + + break; + + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + var typeConditionAST = node.typeCondition; + var outputType = typeConditionAST ? typeFromAST(schema, typeConditionAST) : getNamedType(this.getType()); + + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + + break; + + case Kind.VARIABLE_DEFINITION: + var inputType = typeFromAST(schema, node.type); + + this._inputTypeStack.push(isInputType(inputType) ? inputType : undefined); + + break; + + case Kind.ARGUMENT: + var argDef; + var argType; + var fieldOrDirective = this.getDirective() || this.getFieldDef(); + + if (fieldOrDirective) { + argDef = find(fieldOrDirective.args, function (arg) { + return arg.name === node.name.value; + }); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push(isInputType(argType) ? argType : undefined); + + break; + + case Kind.LIST: + var listType = getNullableType(this.getInputType()); + var itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined); + + break; + + case Kind.OBJECT_FIELD: + var objectType = getNamedType(this.getInputType()); + var inputFieldType; + var inputField; + + if (isInputObjectType(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push(inputField ? inputField.defaultValue : undefined); + + this._inputTypeStack.push(isInputType(inputFieldType) ? inputFieldType : undefined); + + break; + + case Kind.ENUM: + var enumType = getNamedType(this.getInputType()); + var enumValue; + + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + }; + + _proto.leave = function leave(node) { + switch (node.kind) { + case Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case Kind.DIRECTIVE: + this._directive = null; + break; + + case Kind.OPERATION_DEFINITION: + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case Kind.LIST: + case Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case Kind.ENUM: + this._enumValue = null; + break; + } + }; + + return TypeInfo; +}(); +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + */ + +function getFieldDef(schema, parentType, fieldNode) { + var name = fieldNode.name.value; + + if (name === SchemaMetaFieldDef.name && schema.getQueryType() === parentType) { + return SchemaMetaFieldDef; + } + + if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } + + if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) { + return TypeNameMetaFieldDef; + } + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + return parentType.getFields()[name]; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/assertValidName.js b/node_modules/graphql/utilities/assertValidName.js new file mode 100644 index 00000000..3d203083 --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.assertValidName = assertValidName; +exports.isValidNameError = isValidNameError; + +var _GraphQLError = require("../error/GraphQLError"); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * Upholds the spec rules about naming. + */ + +function assertValidName(name) { + var error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. + */ + + +function isValidNameError(name, node) { + !(typeof name === 'string') ? (0, _invariant.default)(0, 'Expected string') : void 0; + + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new _GraphQLError.GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node); + } + + if (!NAME_RX.test(name)) { + return new _GraphQLError.GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/assertValidName.js.flow b/node_modules/graphql/utilities/assertValidName.js.flow new file mode 100644 index 00000000..cdc20b1d --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.js.flow @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import type { ASTNode } from '../language/ast'; +import invariant from '../jsutils/invariant'; + +const NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * Upholds the spec rules about naming. + */ +export function assertValidName(name: string): string { + const error = isValidNameError(name); + if (error) { + throw error; + } + return name; +} + +/** + * Returns an Error if a name is invalid. + */ +export function isValidNameError( + name: string, + node?: ASTNode | void, +): GraphQLError | void { + invariant(typeof name === 'string', 'Expected string'); + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by ` + + 'GraphQL introspection.', + node, + ); + } + if (!NAME_RX.test(name)) { + return new GraphQLError( + `Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "${name}" does not.`, + node, + ); + } +} diff --git a/node_modules/graphql/utilities/assertValidName.mjs b/node_modules/graphql/utilities/assertValidName.mjs new file mode 100644 index 00000000..e7375293 --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.mjs @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; +import invariant from '../jsutils/invariant'; +var NAME_RX = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * Upholds the spec rules about naming. + */ + +export function assertValidName(name) { + var error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. + */ + +export function isValidNameError(name, node) { + !(typeof name === 'string') ? invariant(0, 'Expected string') : void 0; + + if (name.length > 1 && name[0] === '_' && name[1] === '_') { + return new GraphQLError("Name \"".concat(name, "\" must not begin with \"__\", which is reserved by ") + 'GraphQL introspection.', node); + } + + if (!NAME_RX.test(name)) { + return new GraphQLError("Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but \"".concat(name, "\" does not."), node); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/astFromValue.js b/node_modules/graphql/utilities/astFromValue.js new file mode 100644 index 00000000..bbebca57 --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.js @@ -0,0 +1,207 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.astFromValue = astFromValue; + +var _iterall = require("iterall"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _isNullish = _interopRequireDefault(require("../jsutils/isNullish")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +var _scalars = require("../type/scalars"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + var astValue = astFromValue(value, type.ofType); + + if (astValue && astValue.kind === _kinds.Kind.NULL) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + + if (value === null) { + return { + kind: _kinds.Kind.NULL + }; + } // undefined, NaN + + + if ((0, _isInvalid.default)(value)) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + + if ((0, _iterall.isCollection)(value)) { + var valuesNodes = []; + (0, _iterall.forEach)(value, function (item) { + var itemNode = astFromValue(item, itemType); + + if (itemNode) { + valuesNodes.push(itemNode); + } + }); + return { + kind: _kinds.Kind.LIST, + values: valuesNodes + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + + if ((0, _definition.isInputObjectType)(type)) { + if (value === null || _typeof(value) !== 'object') { + return null; + } + + var fields = (0, _objectValues.default)(type.getFields()); + var fieldNodes = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var field = _step.value; + var fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name + }, + value: fieldValue + }); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes + }; + } + + if ((0, _definition.isScalarType)(type) || (0, _definition.isEnumType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + var serialized = type.serialize(value); + + if ((0, _isNullish.default)(serialized)) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + + if (typeof serialized === 'boolean') { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized + }; + } // JavaScript numbers can be Int or Float values. + + + if (typeof serialized === 'number') { + var stringNum = String(serialized); + return integerStringRegExp.test(stringNum) ? { + kind: _kinds.Kind.INT, + value: stringNum + } : { + kind: _kinds.Kind.FLOAT, + value: stringNum + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized + }; + } // ID types can use Int literals. + + + if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: _kinds.Kind.INT, + value: serialized + }; + } + + return { + kind: _kinds.Kind.STRING, + value: serialized + }; + } + + throw new TypeError("Cannot convert value to AST: ".concat((0, _inspect.default)(serialized))); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + + +var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/; \ No newline at end of file diff --git a/node_modules/graphql/utilities/astFromValue.js.flow b/node_modules/graphql/utilities/astFromValue.js.flow new file mode 100644 index 00000000..cf73305c --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.js.flow @@ -0,0 +1,152 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { forEach, isCollection } from 'iterall'; + +import inspect from '../jsutils/inspect'; +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import type { ValueNode } from '../language/ast'; +import { Kind } from '../language/kinds'; +import type { GraphQLInputType } from '../type/definition'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; +import { GraphQLID } from '../type/scalars'; + +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ +export function astFromValue(value: mixed, type: GraphQLInputType): ?ValueNode { + if (isNonNullType(type)) { + const astValue = astFromValue(value, type.ofType); + if (astValue && astValue.kind === Kind.NULL) { + return null; + } + return astValue; + } + + // only explicit null, not undefined, NaN + if (value === null) { + return { kind: Kind.NULL }; + } + + // undefined, NaN + if (isInvalid(value)) { + return null; + } + + // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + if (isListType(type)) { + const itemType = type.ofType; + if (isCollection(value)) { + const valuesNodes = []; + forEach((value: any), item => { + const itemNode = astFromValue(item, itemType); + if (itemNode) { + valuesNodes.push(itemNode); + } + }); + return { kind: Kind.LIST, values: valuesNodes }; + } + return astFromValue(value, itemType); + } + + // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + if (isInputObjectType(type)) { + if (value === null || typeof value !== 'object') { + return null; + } + const fields = objectValues(type.getFields()); + const fieldNodes = []; + for (const field of fields) { + const fieldValue = astFromValue(value[field.name], field.type); + if (fieldValue) { + fieldNodes.push({ + kind: Kind.OBJECT_FIELD, + name: { kind: Kind.NAME, value: field.name }, + value: fieldValue, + }); + } + } + return { kind: Kind.OBJECT, fields: fieldNodes }; + } + + if (isScalarType(type) || isEnumType(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + if (isNullish(serialized)) { + return null; + } + + // Others serialize based on their corresponding JavaScript scalar types. + if (typeof serialized === 'boolean') { + return { kind: Kind.BOOLEAN, value: serialized }; + } + + // JavaScript numbers can be Int or Float values. + if (typeof serialized === 'number') { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) + ? { kind: Kind.INT, value: stringNum } + : { kind: Kind.FLOAT, value: stringNum }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if (isEnumType(type)) { + return { kind: Kind.ENUM, value: serialized }; + } + + // ID types can use Int literals. + if (type === GraphQLID && integerStringRegExp.test(serialized)) { + return { kind: Kind.INT, value: serialized }; + } + + return { + kind: Kind.STRING, + value: serialized, + }; + } + + throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}`); + } + + /* istanbul ignore next */ + throw new Error(`Unknown type: ${(type: empty)}.`); +} + +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ +const integerStringRegExp = /^-?(0|[1-9][0-9]*)$/; diff --git a/node_modules/graphql/utilities/astFromValue.mjs b/node_modules/graphql/utilities/astFromValue.mjs new file mode 100644 index 00000000..1403f3da --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.mjs @@ -0,0 +1,198 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { forEach, isCollection } from 'iterall'; +import inspect from '../jsutils/inspect'; +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { Kind } from '../language/kinds'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition'; +import { GraphQLID } from '../type/scalars'; +/** + * Produces a GraphQL Value AST given a JavaScript value. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Mixed | Enum Value | + * | null | NullValue | + * + */ + +export function astFromValue(value, type) { + if (isNonNullType(type)) { + var astValue = astFromValue(value, type.ofType); + + if (astValue && astValue.kind === Kind.NULL) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + + if (value === null) { + return { + kind: Kind.NULL + }; + } // undefined, NaN + + + if (isInvalid(value)) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + + if (isListType(type)) { + var itemType = type.ofType; + + if (isCollection(value)) { + var valuesNodes = []; + forEach(value, function (item) { + var itemNode = astFromValue(item, itemType); + + if (itemNode) { + valuesNodes.push(itemNode); + } + }); + return { + kind: Kind.LIST, + values: valuesNodes + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + + if (isInputObjectType(type)) { + if (value === null || _typeof(value) !== 'object') { + return null; + } + + var fields = objectValues(type.getFields()); + var fieldNodes = []; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var field = _step.value; + var fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: Kind.OBJECT_FIELD, + name: { + kind: Kind.NAME, + value: field.name + }, + value: fieldValue + }); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return { + kind: Kind.OBJECT, + fields: fieldNodes + }; + } + + if (isScalarType(type) || isEnumType(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + var serialized = type.serialize(value); + + if (isNullish(serialized)) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + + if (typeof serialized === 'boolean') { + return { + kind: Kind.BOOLEAN, + value: serialized + }; + } // JavaScript numbers can be Int or Float values. + + + if (typeof serialized === 'number') { + var stringNum = String(serialized); + return integerStringRegExp.test(stringNum) ? { + kind: Kind.INT, + value: stringNum + } : { + kind: Kind.FLOAT, + value: stringNum + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if (isEnumType(type)) { + return { + kind: Kind.ENUM, + value: serialized + }; + } // ID types can use Int literals. + + + if (type === GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: Kind.INT, + value: serialized + }; + } + + return { + kind: Kind.STRING, + value: serialized + }; + } + + throw new TypeError("Cannot convert value to AST: ".concat(inspect(serialized))); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + */ + +var integerStringRegExp = /^-?(0|[1-9][0-9]*)$/; \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildASTSchema.js b/node_modules/graphql/utilities/buildASTSchema.js new file mode 100644 index 00000000..39a5cbfa --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.js @@ -0,0 +1,487 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildASTSchema = buildASTSchema; +exports.getDescription = getDescription; +exports.buildSchema = buildSchema; +exports.ASTDefinitionBuilder = void 0; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _valueFromAST = require("./valueFromAST"); + +var _validate = require("../validation/validate"); + +var _blockStringValue = _interopRequireDefault(require("../language/blockStringValue")); + +var _lexer = require("../language/lexer"); + +var _parser = require("../language/parser"); + +var _values = require("../execution/values"); + +var _kinds = require("../language/kinds"); + +var _predicates = require("../language/predicates"); + +var _definition = require("../type/definition"); + +var _directives = require("../type/directives"); + +var _introspection = require("../type/introspection"); + +var _scalars = require("../type/scalars"); + +var _schema = require("../type/schema"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function buildASTSchema(documentAST, options) { + !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + (0, _validate.assertValidSDL)(documentAST); + } + + var schemaDef; + var typeDefs = []; + var nodeMap = Object.create(null); + var directiveDefs = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + var typeName = def.name.value; + + if (nodeMap[typeName]) { + throw new Error("Type \"".concat(typeName, "\" was defined more than once.")); + } + + typeDefs.push(def); + nodeMap[typeName] = def; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } + + var operationTypes = schemaDef ? getOperationTypes(schemaDef) : { + query: nodeMap.Query, + mutation: nodeMap.Mutation, + subscription: nodeMap.Subscription + }; + var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeRef) { + throw new Error("Type \"".concat(typeRef.name.value, "\" not found in document.")); + }); + var directives = directiveDefs.map(function (def) { + return definitionBuilder.buildDirective(def); + }); // If specified directives were not explicitly declared, add them. + + if (!directives.some(function (directive) { + return directive.name === 'skip'; + })) { + directives.push(_directives.GraphQLSkipDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'include'; + })) { + directives.push(_directives.GraphQLIncludeDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'deprecated'; + })) { + directives.push(_directives.GraphQLDeprecatedDirective); + } // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + return new _schema.GraphQLSchema({ + query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null, + mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null, + subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null, + types: typeDefs.map(function (node) { + return definitionBuilder.buildType(node); + }), + directives: directives, + astNode: schemaDef, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); + + function getOperationTypes(schema) { + var opTypes = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var operationType = _step.value; + var _typeName = operationType.type.name.value; + var operation = operationType.operation; + + if (opTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } + + if (!nodeMap[_typeName]) { + throw new Error("Specified ".concat(operation, " type \"").concat(_typeName, "\" not found in document.")); + } + + opTypes[operation] = operationType.type; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return opTypes; + } +} + +var ASTDefinitionBuilder = +/*#__PURE__*/ +function () { + function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) { + _defineProperty(this, "_typeDefinitionsMap", void 0); + + _defineProperty(this, "_options", void 0); + + _defineProperty(this, "_resolveType", void 0); + + _defineProperty(this, "_cache", void 0); + + this._typeDefinitionsMap = typeDefinitionsMap; + this._options = options; + this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types. + + this._cache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) { + return type.name; + }); + } + + var _proto = ASTDefinitionBuilder.prototype; + + _proto.buildType = function buildType(node) { + var typeName = node.name.value; + + if (!this._cache[typeName]) { + if (node.kind === _kinds.Kind.NAMED_TYPE) { + var defNode = this._typeDefinitionsMap[typeName]; + this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node); + } else { + this._cache[typeName] = this._makeSchemaDef(node); + } + } + + return this._cache[typeName]; + }; + + _proto._buildWrappedType = function _buildWrappedType(typeNode) { + if (typeNode.kind === _kinds.Kind.LIST_TYPE) { + return (0, _definition.GraphQLList)(this._buildWrappedType(typeNode.type)); + } + + if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) { + return (0, _definition.GraphQLNonNull)( // Note: GraphQLNonNull constructor validates this type + this._buildWrappedType(typeNode.type)); + } + + return this.buildType(typeNode); + }; + + _proto.buildDirective = function buildDirective(directiveNode) { + return new _directives.GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode, this._options), + locations: directiveNode.locations.map(function (node) { + return node.value; + }), + args: directiveNode.arguments && this._makeInputValues(directiveNode.arguments), + astNode: directiveNode + }); + }; + + _proto.buildField = function buildField(field) { + return { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: this._buildWrappedType(field.type), + description: getDescription(field, this._options), + args: field.arguments && this._makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + }; + + _proto.buildInputField = function buildInputField(value) { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + var type = this._buildWrappedType(value.type); + + return { + name: value.name.value, + type: type, + description: getDescription(value, this._options), + defaultValue: (0, _valueFromAST.valueFromAST)(value.defaultValue, type), + astNode: value + }; + }; + + _proto.buildEnumValue = function buildEnumValue(value) { + return { + description: getDescription(value, this._options), + deprecationReason: getDeprecationReason(value), + astNode: value + }; + }; + + _proto._makeSchemaDef = function _makeSchemaDef(def) { + switch (def.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + return this._makeTypeDef(def); + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + return this._makeInterfaceDef(def); + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + return this._makeEnumDef(def); + + case _kinds.Kind.UNION_TYPE_DEFINITION: + return this._makeUnionDef(def); + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + return this._makeScalarDef(def); + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + return this._makeInputObjectDef(def); + + default: + throw new Error("Type kind \"".concat(def.kind, "\" not supported.")); + } + }; + + _proto._makeTypeDef = function _makeTypeDef(def) { + var _this = this; + + var interfaces = def.interfaces; + return new _definition.GraphQLObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this._makeFieldDefMap(def); + }, + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces: interfaces ? function () { + return interfaces.map(function (ref) { + return _this.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeFieldDefMap = function _makeFieldDefMap(def) { + var _this2 = this; + + return def.fields ? (0, _keyValMap.default)(def.fields, function (field) { + return field.name.value; + }, function (field) { + return _this2.buildField(field); + }) : {}; + }; + + _proto._makeInputValues = function _makeInputValues(values) { + var _this3 = this; + + return (0, _keyValMap.default)(values, function (value) { + return value.name.value; + }, function (value) { + return _this3.buildInputField(value); + }); + }; + + _proto._makeInterfaceDef = function _makeInterfaceDef(def) { + var _this4 = this; + + return new _definition.GraphQLInterfaceType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this4._makeFieldDefMap(def); + }, + astNode: def + }); + }; + + _proto._makeEnumDef = function _makeEnumDef(def) { + return new _definition.GraphQLEnumType({ + name: def.name.value, + description: getDescription(def, this._options), + values: this._makeValueDefMap(def), + astNode: def + }); + }; + + _proto._makeValueDefMap = function _makeValueDefMap(def) { + var _this5 = this; + + return def.values ? (0, _keyValMap.default)(def.values, function (enumValue) { + return enumValue.name.value; + }, function (enumValue) { + return _this5.buildEnumValue(enumValue); + }) : {}; + }; + + _proto._makeUnionDef = function _makeUnionDef(def) { + var _this6 = this; + + var types = def.types; + return new _definition.GraphQLUnionType({ + name: def.name.value, + description: getDescription(def, this._options), + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + types: types ? function () { + return types.map(function (ref) { + return _this6.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeScalarDef = function _makeScalarDef(def) { + return new _definition.GraphQLScalarType({ + name: def.name.value, + description: getDescription(def, this._options), + astNode: def, + serialize: function serialize(value) { + return value; + } + }); + }; + + _proto._makeInputObjectDef = function _makeInputObjectDef(def) { + var _this7 = this; + + return new _definition.GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return def.fields ? _this7._makeInputValues(def.fields) : {}; + }, + astNode: def + }); + }; + + return ASTDefinitionBuilder; +}(); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + + +exports.ASTDefinitionBuilder = ASTDefinitionBuilder; + +function getDeprecationReason(node) { + var deprecated = (0, _values.getDirectiveValues)(_directives.GraphQLDeprecatedDirective, node); + return deprecated && deprecated.reason; +} +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ + + +function getDescription(node, options) { + if (node.description) { + return node.description.value; + } + + if (options && options.commentDescriptions) { + var rawValue = getLeadingCommentBlock(node); + + if (rawValue !== undefined) { + return (0, _blockStringValue.default)('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node) { + var loc = node.loc; + + if (!loc) { + return; + } + + var comments = []; + var token = loc.startToken.prev; + + while (token && token.kind === _lexer.TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) { + var value = String(token.value); + comments.push(value); + token = token.prev; + } + + return comments.reverse().join('\n'); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + + +function buildSchema(source, options) { + return buildASTSchema((0, _parser.parse)(source, options), options); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildASTSchema.js.flow b/node_modules/graphql/utilities/buildASTSchema.js.flow new file mode 100644 index 00000000..2319e740 --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.js.flow @@ -0,0 +1,506 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { valueFromAST } from './valueFromAST'; +import { assertValidSDL } from '../validation/validate'; +import blockStringValue from '../language/blockStringValue'; +import { TokenKind } from '../language/lexer'; +import { parse } from '../language/parser'; +import type { ParseOptions } from '../language/parser'; +import type { Source } from '../language/source'; +import { getDirectiveValues } from '../execution/values'; +import { Kind } from '../language/kinds'; + +import type { + DocumentNode, + TypeNode, + NamedTypeNode, + SchemaDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + StringValueNode, + Location, +} from '../language/ast'; +import { isTypeDefinitionNode } from '../language/predicates'; + +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +import type { + GraphQLType, + GraphQLNamedType, + GraphQLFieldConfig, + GraphQLEnumValueConfig, + GraphQLInputField, +} from '../type/definition'; + +import { + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, +} from '../type/definition'; + +import { + GraphQLDirective, + GraphQLSkipDirective, + GraphQLIncludeDirective, + GraphQLDeprecatedDirective, +} from '../type/directives'; + +import { introspectionTypes } from '../type/introspection'; + +import { specifiedScalarTypes } from '../type/scalars'; + +import { GraphQLSchema } from '../type/schema'; +import type { GraphQLSchemaValidationOptions } from '../type/schema'; + +export type BuildSchemaOptions = { + ...GraphQLSchemaValidationOptions, + + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean, +}; + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema( + documentAST: DocumentNode, + options?: BuildSchemaOptions, +): GraphQLSchema { + invariant( + documentAST && documentAST.kind === Kind.DOCUMENT, + 'Must provide valid Document AST', + ); + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDL(documentAST); + } + + let schemaDef: ?SchemaDefinitionNode; + + const typeDefs: Array = []; + const nodeMap: ObjMap = Object.create(null); + const directiveDefs: Array = []; + for (let i = 0; i < documentAST.definitions.length; i++) { + const def = documentAST.definitions[i]; + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (isTypeDefinitionNode(def)) { + const typeName = def.name.value; + if (nodeMap[typeName]) { + throw new Error(`Type "${typeName}" was defined more than once.`); + } + typeDefs.push(def); + nodeMap[typeName] = def; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } + + const operationTypes = schemaDef + ? getOperationTypes(schemaDef) + : { + query: nodeMap.Query, + mutation: nodeMap.Mutation, + subscription: nodeMap.Subscription, + }; + + const definitionBuilder = new ASTDefinitionBuilder( + nodeMap, + options, + typeRef => { + throw new Error(`Type "${typeRef.name.value}" not found in document.`); + }, + ); + + const directives = directiveDefs.map(def => + definitionBuilder.buildDirective(def), + ); + + // If specified directives were not explicitly declared, add them. + if (!directives.some(directive => directive.name === 'skip')) { + directives.push(GraphQLSkipDirective); + } + + if (!directives.some(directive => directive.name === 'include')) { + directives.push(GraphQLIncludeDirective); + } + + if (!directives.some(directive => directive.name === 'deprecated')) { + directives.push(GraphQLDeprecatedDirective); + } + + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return new GraphQLSchema({ + query: operationTypes.query + ? (definitionBuilder.buildType(operationTypes.query): any) + : null, + mutation: operationTypes.mutation + ? (definitionBuilder.buildType(operationTypes.mutation): any) + : null, + subscription: operationTypes.subscription + ? (definitionBuilder.buildType(operationTypes.subscription): any) + : null, + types: typeDefs.map(node => definitionBuilder.buildType(node)), + directives, + astNode: schemaDef, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames, + }); + + function getOperationTypes(schema: SchemaDefinitionNode) { + const opTypes = {}; + for (const operationType of schema.operationTypes) { + const typeName = operationType.type.name.value; + const operation = operationType.operation; + if (opTypes[operation]) { + throw new Error(`Must provide only one ${operation} type in schema.`); + } + if (!nodeMap[typeName]) { + throw new Error( + `Specified ${operation} type "${typeName}" not found in document.`, + ); + } + opTypes[operation] = operationType.type; + } + return opTypes; + } +} + +type TypeDefinitionsMap = ObjMap; +type TypeResolver = (typeRef: NamedTypeNode) => GraphQLNamedType; + +export class ASTDefinitionBuilder { + _typeDefinitionsMap: TypeDefinitionsMap; + _options: ?BuildSchemaOptions; + _resolveType: TypeResolver; + _cache: ObjMap; + + constructor( + typeDefinitionsMap: TypeDefinitionsMap, + options: ?BuildSchemaOptions, + resolveType: TypeResolver, + ) { + this._typeDefinitionsMap = typeDefinitionsMap; + this._options = options; + this._resolveType = resolveType; + // Initialize to the GraphQL built in scalars and introspection types. + this._cache = keyMap( + specifiedScalarTypes.concat(introspectionTypes), + type => type.name, + ); + } + + buildType(node: NamedTypeNode | TypeDefinitionNode): GraphQLNamedType { + const typeName = node.name.value; + if (!this._cache[typeName]) { + if (node.kind === Kind.NAMED_TYPE) { + const defNode = this._typeDefinitionsMap[typeName]; + this._cache[typeName] = defNode + ? this._makeSchemaDef(defNode) + : this._resolveType(node); + } else { + this._cache[typeName] = this._makeSchemaDef(node); + } + } + return this._cache[typeName]; + } + + _buildWrappedType(typeNode: TypeNode): GraphQLType { + if (typeNode.kind === Kind.LIST_TYPE) { + return GraphQLList(this._buildWrappedType(typeNode.type)); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + return GraphQLNonNull( + // Note: GraphQLNonNull constructor validates this type + (this._buildWrappedType(typeNode.type): any), + ); + } + return this.buildType(typeNode); + } + + buildDirective(directiveNode: DirectiveDefinitionNode): GraphQLDirective { + return new GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode, this._options), + locations: directiveNode.locations.map( + node => ((node.value: any): DirectiveLocationEnum), + ), + args: + directiveNode.arguments && + this._makeInputValues(directiveNode.arguments), + astNode: directiveNode, + }); + } + + buildField(field: FieldDefinitionNode): GraphQLFieldConfig<*, *> { + return { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: (this._buildWrappedType(field.type): any), + description: getDescription(field, this._options), + args: field.arguments && this._makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + + buildInputField(value: InputValueDefinitionNode): GraphQLInputField { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type: any = this._buildWrappedType(value.type); + return { + name: value.name.value, + type, + description: getDescription(value, this._options), + defaultValue: valueFromAST(value.defaultValue, type), + astNode: value, + }; + } + + buildEnumValue(value: EnumValueDefinitionNode): GraphQLEnumValueConfig { + return { + description: getDescription(value, this._options), + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } + + _makeSchemaDef(def: TypeDefinitionNode): GraphQLNamedType { + switch (def.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + return this._makeTypeDef(def); + case Kind.INTERFACE_TYPE_DEFINITION: + return this._makeInterfaceDef(def); + case Kind.ENUM_TYPE_DEFINITION: + return this._makeEnumDef(def); + case Kind.UNION_TYPE_DEFINITION: + return this._makeUnionDef(def); + case Kind.SCALAR_TYPE_DEFINITION: + return this._makeScalarDef(def); + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return this._makeInputObjectDef(def); + default: + throw new Error(`Type kind "${def.kind}" not supported.`); + } + } + + _makeTypeDef(def: ObjectTypeDefinitionNode) { + const interfaces: ?$ReadOnlyArray = def.interfaces; + return new GraphQLObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: () => this._makeFieldDefMap(def), + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces: interfaces + ? () => interfaces.map(ref => (this.buildType(ref): any)) + : [], + astNode: def, + }); + } + + _makeFieldDefMap( + def: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode, + ) { + return def.fields + ? keyValMap( + def.fields, + field => field.name.value, + field => this.buildField(field), + ) + : {}; + } + + _makeInputValues(values: $ReadOnlyArray) { + return keyValMap( + values, + value => value.name.value, + value => this.buildInputField(value), + ); + } + + _makeInterfaceDef(def: InterfaceTypeDefinitionNode) { + return new GraphQLInterfaceType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: () => this._makeFieldDefMap(def), + astNode: def, + }); + } + + _makeEnumDef(def: EnumTypeDefinitionNode) { + return new GraphQLEnumType({ + name: def.name.value, + description: getDescription(def, this._options), + values: this._makeValueDefMap(def), + astNode: def, + }); + } + + _makeValueDefMap(def: EnumTypeDefinitionNode) { + return def.values + ? keyValMap( + def.values, + enumValue => enumValue.name.value, + enumValue => this.buildEnumValue(enumValue), + ) + : {}; + } + + _makeUnionDef(def: UnionTypeDefinitionNode) { + const types: ?$ReadOnlyArray = def.types; + return new GraphQLUnionType({ + name: def.name.value, + description: getDescription(def, this._options), + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + types: types ? () => types.map(ref => (this.buildType(ref): any)) : [], + astNode: def, + }); + } + + _makeScalarDef(def: ScalarTypeDefinitionNode) { + return new GraphQLScalarType({ + name: def.name.value, + description: getDescription(def, this._options), + astNode: def, + serialize: value => value, + }); + } + + _makeInputObjectDef(def: InputObjectTypeDefinitionNode) { + return new GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: () => (def.fields ? this._makeInputValues(def.fields) : {}), + astNode: def, + }); + } +} + +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ +function getDeprecationReason( + node: EnumValueDefinitionNode | FieldDefinitionNode, +): ?string { + const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); + return deprecated && (deprecated.reason: any); +} + +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function getDescription( + node: { +description?: StringValueNode, +loc?: Location }, + options: ?BuildSchemaOptions, +): void | string { + if (node.description) { + return node.description.value; + } + if (options && options.commentDescriptions) { + const rawValue = getLeadingCommentBlock(node); + if (rawValue !== undefined) { + return blockStringValue('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node): void | string { + const loc = node.loc; + if (!loc) { + return; + } + const comments = []; + let token = loc.startToken.prev; + while ( + token && + token.kind === TokenKind.COMMENT && + token.next && + token.prev && + token.line + 1 === token.next.line && + token.line !== token.prev.line + ) { + const value = String(token.value); + comments.push(value); + token = token.prev; + } + return comments.reverse().join('\n'); +} + +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ +export function buildSchema( + source: string | Source, + options?: BuildSchemaOptions & ParseOptions, +): GraphQLSchema { + return buildASTSchema(parse(source, options), options); +} diff --git a/node_modules/graphql/utilities/buildASTSchema.mjs b/node_modules/graphql/utilities/buildASTSchema.mjs new file mode 100644 index 00000000..a57c6d5b --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.mjs @@ -0,0 +1,464 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import { valueFromAST } from './valueFromAST'; +import { assertValidSDL } from '../validation/validate'; +import blockStringValue from '../language/blockStringValue'; +import { TokenKind } from '../language/lexer'; +import { parse } from '../language/parser'; +import { getDirectiveValues } from '../execution/values'; +import { Kind } from '../language/kinds'; +import { isTypeDefinitionNode } from '../language/predicates'; +import { GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from '../type/definition'; +import { GraphQLDirective, GraphQLSkipDirective, GraphQLIncludeDirective, GraphQLDeprecatedDirective } from '../type/directives'; +import { introspectionTypes } from '../type/introspection'; +import { specifiedScalarTypes } from '../type/scalars'; +import { GraphQLSchema } from '../type/schema'; + +/** + * This takes the ast of a schema document produced by the parse function in + * src/language/parser.js. + * + * If no schema definition is provided, then it will look for types named Query + * and Mutation. + * + * Given that AST it constructs a GraphQLSchema. The resulting schema + * has no resolve methods, so execution will use default resolvers. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function buildASTSchema(documentAST, options) { + !(documentAST && documentAST.kind === Kind.DOCUMENT) ? invariant(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDL(documentAST); + } + + var schemaDef; + var typeDefs = []; + var nodeMap = Object.create(null); + var directiveDefs = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (isTypeDefinitionNode(def)) { + var typeName = def.name.value; + + if (nodeMap[typeName]) { + throw new Error("Type \"".concat(typeName, "\" was defined more than once.")); + } + + typeDefs.push(def); + nodeMap[typeName] = def; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } + } + + var operationTypes = schemaDef ? getOperationTypes(schemaDef) : { + query: nodeMap.Query, + mutation: nodeMap.Mutation, + subscription: nodeMap.Subscription + }; + var definitionBuilder = new ASTDefinitionBuilder(nodeMap, options, function (typeRef) { + throw new Error("Type \"".concat(typeRef.name.value, "\" not found in document.")); + }); + var directives = directiveDefs.map(function (def) { + return definitionBuilder.buildDirective(def); + }); // If specified directives were not explicitly declared, add them. + + if (!directives.some(function (directive) { + return directive.name === 'skip'; + })) { + directives.push(GraphQLSkipDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'include'; + })) { + directives.push(GraphQLIncludeDirective); + } + + if (!directives.some(function (directive) { + return directive.name === 'deprecated'; + })) { + directives.push(GraphQLDeprecatedDirective); + } // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + return new GraphQLSchema({ + query: operationTypes.query ? definitionBuilder.buildType(operationTypes.query) : null, + mutation: operationTypes.mutation ? definitionBuilder.buildType(operationTypes.mutation) : null, + subscription: operationTypes.subscription ? definitionBuilder.buildType(operationTypes.subscription) : null, + types: typeDefs.map(function (node) { + return definitionBuilder.buildType(node); + }), + directives: directives, + astNode: schemaDef, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); + + function getOperationTypes(schema) { + var opTypes = {}; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var operationType = _step.value; + var _typeName = operationType.type.name.value; + var operation = operationType.operation; + + if (opTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } + + if (!nodeMap[_typeName]) { + throw new Error("Specified ".concat(operation, " type \"").concat(_typeName, "\" not found in document.")); + } + + opTypes[operation] = operationType.type; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return opTypes; + } +} +export var ASTDefinitionBuilder = +/*#__PURE__*/ +function () { + function ASTDefinitionBuilder(typeDefinitionsMap, options, resolveType) { + _defineProperty(this, "_typeDefinitionsMap", void 0); + + _defineProperty(this, "_options", void 0); + + _defineProperty(this, "_resolveType", void 0); + + _defineProperty(this, "_cache", void 0); + + this._typeDefinitionsMap = typeDefinitionsMap; + this._options = options; + this._resolveType = resolveType; // Initialize to the GraphQL built in scalars and introspection types. + + this._cache = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) { + return type.name; + }); + } + + var _proto = ASTDefinitionBuilder.prototype; + + _proto.buildType = function buildType(node) { + var typeName = node.name.value; + + if (!this._cache[typeName]) { + if (node.kind === Kind.NAMED_TYPE) { + var defNode = this._typeDefinitionsMap[typeName]; + this._cache[typeName] = defNode ? this._makeSchemaDef(defNode) : this._resolveType(node); + } else { + this._cache[typeName] = this._makeSchemaDef(node); + } + } + + return this._cache[typeName]; + }; + + _proto._buildWrappedType = function _buildWrappedType(typeNode) { + if (typeNode.kind === Kind.LIST_TYPE) { + return GraphQLList(this._buildWrappedType(typeNode.type)); + } + + if (typeNode.kind === Kind.NON_NULL_TYPE) { + return GraphQLNonNull( // Note: GraphQLNonNull constructor validates this type + this._buildWrappedType(typeNode.type)); + } + + return this.buildType(typeNode); + }; + + _proto.buildDirective = function buildDirective(directiveNode) { + return new GraphQLDirective({ + name: directiveNode.name.value, + description: getDescription(directiveNode, this._options), + locations: directiveNode.locations.map(function (node) { + return node.value; + }), + args: directiveNode.arguments && this._makeInputValues(directiveNode.arguments), + astNode: directiveNode + }); + }; + + _proto.buildField = function buildField(field) { + return { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: this._buildWrappedType(field.type), + description: getDescription(field, this._options), + args: field.arguments && this._makeInputValues(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field + }; + }; + + _proto.buildInputField = function buildInputField(value) { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + var type = this._buildWrappedType(value.type); + + return { + name: value.name.value, + type: type, + description: getDescription(value, this._options), + defaultValue: valueFromAST(value.defaultValue, type), + astNode: value + }; + }; + + _proto.buildEnumValue = function buildEnumValue(value) { + return { + description: getDescription(value, this._options), + deprecationReason: getDeprecationReason(value), + astNode: value + }; + }; + + _proto._makeSchemaDef = function _makeSchemaDef(def) { + switch (def.kind) { + case Kind.OBJECT_TYPE_DEFINITION: + return this._makeTypeDef(def); + + case Kind.INTERFACE_TYPE_DEFINITION: + return this._makeInterfaceDef(def); + + case Kind.ENUM_TYPE_DEFINITION: + return this._makeEnumDef(def); + + case Kind.UNION_TYPE_DEFINITION: + return this._makeUnionDef(def); + + case Kind.SCALAR_TYPE_DEFINITION: + return this._makeScalarDef(def); + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + return this._makeInputObjectDef(def); + + default: + throw new Error("Type kind \"".concat(def.kind, "\" not supported.")); + } + }; + + _proto._makeTypeDef = function _makeTypeDef(def) { + var _this = this; + + var interfaces = def.interfaces; + return new GraphQLObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this._makeFieldDefMap(def); + }, + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces: interfaces ? function () { + return interfaces.map(function (ref) { + return _this.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeFieldDefMap = function _makeFieldDefMap(def) { + var _this2 = this; + + return def.fields ? keyValMap(def.fields, function (field) { + return field.name.value; + }, function (field) { + return _this2.buildField(field); + }) : {}; + }; + + _proto._makeInputValues = function _makeInputValues(values) { + var _this3 = this; + + return keyValMap(values, function (value) { + return value.name.value; + }, function (value) { + return _this3.buildInputField(value); + }); + }; + + _proto._makeInterfaceDef = function _makeInterfaceDef(def) { + var _this4 = this; + + return new GraphQLInterfaceType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return _this4._makeFieldDefMap(def); + }, + astNode: def + }); + }; + + _proto._makeEnumDef = function _makeEnumDef(def) { + return new GraphQLEnumType({ + name: def.name.value, + description: getDescription(def, this._options), + values: this._makeValueDefMap(def), + astNode: def + }); + }; + + _proto._makeValueDefMap = function _makeValueDefMap(def) { + var _this5 = this; + + return def.values ? keyValMap(def.values, function (enumValue) { + return enumValue.name.value; + }, function (enumValue) { + return _this5.buildEnumValue(enumValue); + }) : {}; + }; + + _proto._makeUnionDef = function _makeUnionDef(def) { + var _this6 = this; + + var types = def.types; + return new GraphQLUnionType({ + name: def.name.value, + description: getDescription(def, this._options), + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + types: types ? function () { + return types.map(function (ref) { + return _this6.buildType(ref); + }); + } : [], + astNode: def + }); + }; + + _proto._makeScalarDef = function _makeScalarDef(def) { + return new GraphQLScalarType({ + name: def.name.value, + description: getDescription(def, this._options), + astNode: def, + serialize: function serialize(value) { + return value; + } + }); + }; + + _proto._makeInputObjectDef = function _makeInputObjectDef(def) { + var _this7 = this; + + return new GraphQLInputObjectType({ + name: def.name.value, + description: getDescription(def, this._options), + fields: function fields() { + return def.fields ? _this7._makeInputValues(def.fields) : {}; + }, + astNode: def + }); + }; + + return ASTDefinitionBuilder; +}(); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + */ + +function getDeprecationReason(node) { + var deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); + return deprecated && deprecated.reason; +} +/** + * Given an ast node, returns its string description. + * @deprecated: provided to ease adoption and will be removed in v16. + * + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ + + +export function getDescription(node, options) { + if (node.description) { + return node.description.value; + } + + if (options && options.commentDescriptions) { + var rawValue = getLeadingCommentBlock(node); + + if (rawValue !== undefined) { + return blockStringValue('\n' + rawValue); + } + } +} + +function getLeadingCommentBlock(node) { + var loc = node.loc; + + if (!loc) { + return; + } + + var comments = []; + var token = loc.startToken.prev; + + while (token && token.kind === TokenKind.COMMENT && token.next && token.prev && token.line + 1 === token.next.line && token.line !== token.prev.line) { + var value = String(token.value); + comments.push(value); + token = token.prev; + } + + return comments.reverse().join('\n'); +} +/** + * A helper function to build a GraphQLSchema directly from a source + * document. + */ + + +export function buildSchema(source, options) { + return buildASTSchema(parse(source, options), options); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildClientSchema.js b/node_modules/graphql/utilities/buildClientSchema.js new file mode 100644 index 00000000..432f844c --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.js @@ -0,0 +1,323 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.buildClientSchema = buildClientSchema; + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _valueFromAST = require("./valueFromAST"); + +var _parser = require("../language/parser"); + +var _schema = require("../type/schema"); + +var _definition = require("../type/definition"); + +var _directives = require("../type/directives"); + +var _introspection = require("../type/introspection"); + +var _scalars = require("../type/scalars"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +function buildClientSchema(introspection, options) { + // Get the schema from the introspection result. + var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names. + + var typeIntrospectionMap = (0, _keyMap.default)(schemaIntrospection.types, function (type) { + return type.name; + }); // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars. All functions below are inline + // so that this type def cache is within the scope of the closure. + + var typeDefCache = (0, _keyMap.default)(_scalars.specifiedScalarTypes.concat(_introspection.introspectionTypes), function (type) { + return type.name; + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + var itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return (0, _definition.GraphQLList)(getType(itemRef)); + } + + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + var nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + var nullableType = getType(nullableRef); + return (0, _definition.GraphQLNonNull)((0, _definition.assertNullableType)(nullableType)); + } + + if (!typeRef.name) { + throw new Error('Unknown type reference: ' + (0, _inspect.default)(typeRef)); + } + + return getNamedType(typeRef.name); + } + + function getNamedType(typeName) { + if (typeDefCache[typeName]) { + return typeDefCache[typeName]; + } + + var typeIntrospection = typeIntrospectionMap[typeName]; + + if (!typeIntrospection) { + throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.'); + } + + var typeDef = buildType(typeIntrospection); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + function getInputType(typeRef) { + var type = getType(typeRef); + !(0, _definition.isInputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide input type for arguments.') : void 0; + return type; + } + + function getOutputType(typeRef) { + var type = getType(typeRef); + !(0, _definition.isOutputType)(type) ? (0, _invariant.default)(0, 'Introspection must provide output type for fields.') : void 0; + return type; + } + + function getObjectType(typeRef) { + var type = getType(typeRef); + return (0, _definition.assertObjectType)(type); + } + + function getInterfaceType(typeRef) { + var type = getType(typeRef); + return (0, _definition.assertInterfaceType)(type); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + + function buildType(type) { + if (type && type.name && type.kind) { + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + (0, _inspect.default)(type)); + } + + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: function serialize(value) { + return value; + } + }); + } + + function buildObjectDef(objectIntrospection) { + if (!objectIntrospection.interfaces) { + throw new Error('Introspection result missing interfaces: ' + (0, _inspect.default)(objectIntrospection)); + } + + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: function interfaces() { + return objectIntrospection.interfaces.map(getInterfaceType); + }, + fields: function fields() { + return buildFieldDefMap(objectIntrospection); + } + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + fields: function fields() { + return buildFieldDefMap(interfaceIntrospection); + } + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + throw new Error('Introspection result missing possibleTypes: ' + (0, _inspect.default)(unionIntrospection)); + } + + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: function types() { + return unionIntrospection.possibleTypes.map(getObjectType); + } + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + throw new Error('Introspection result missing enumValues: ' + (0, _inspect.default)(enumIntrospection)); + } + + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.default)(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + throw new Error('Introspection result missing inputFields: ' + (0, _inspect.default)(inputObjectIntrospection)); + } + + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error('Introspection result missing fields: ' + (0, _inspect.default)(typeIntrospection)); + } + + return (0, _keyValMap.default)(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, function (fieldIntrospection) { + if (!fieldIntrospection.args) { + throw new Error('Introspection result missing field args: ' + (0, _inspect.default)(fieldIntrospection)); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args) + }; + }); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.default)(inputValueIntrospections, function (inputValue) { + return inputValue.name; + }, buildInputValue); + } + + function buildInputValue(inputValueIntrospection) { + var type = getInputType(inputValueIntrospection.type); + var defaultValue = inputValueIntrospection.defaultValue ? (0, _valueFromAST.valueFromAST)((0, _parser.parseValue)(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + throw new Error('Introspection result missing directive args: ' + (0, _inspect.default)(directiveIntrospection)); + } + + if (!directiveIntrospection.locations) { + throw new Error('Introspection result missing directive locations: ' + (0, _inspect.default)(directiveIntrospection)); + } + + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + + + var types = schemaIntrospection.types.map(function (typeIntrospection) { + return getNamedType(typeIntrospection.name); + }); // Get the root Query, Mutation, and Subscription types. + + var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: types, + directives: directives, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/buildClientSchema.js.flow b/node_modules/graphql/utilities/buildClientSchema.js.flow new file mode 100644 index 00000000..531036dc --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.js.flow @@ -0,0 +1,396 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import { valueFromAST } from './valueFromAST'; +import { parseValue } from '../language/parser'; +import { GraphQLSchema } from '../type/schema'; + +import { + isInputType, + isOutputType, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + assertNullableType, + assertObjectType, + assertInterfaceType, +} from '../type/definition'; + +import type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLNamedType, +} from '../type/definition'; + +import { GraphQLDirective } from '../type/directives'; + +import { introspectionTypes, TypeKind } from '../type/introspection'; + +import { specifiedScalarTypes } from '../type/scalars'; + +import type { + IntrospectionQuery, + IntrospectionType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, +} from './introspectionQuery'; + +import type { GraphQLSchemaValidationOptions } from '../type/schema'; + +type Options = {| + ...GraphQLSchemaValidationOptions, +|}; + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +export function buildClientSchema( + introspection: IntrospectionQuery, + options?: Options, +): GraphQLSchema { + // Get the schema from the introspection result. + const schemaIntrospection = introspection.__schema; + + // Converts the list of types into a keyMap based on the type names. + const typeIntrospectionMap = keyMap( + schemaIntrospection.types, + type => type.name, + ); + + // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars. All functions below are inline + // so that this type def cache is within the scope of the closure. + const typeDefCache = keyMap( + specifiedScalarTypes.concat(introspectionTypes), + type => type.name, + ); + + // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + function getType(typeRef: IntrospectionTypeRef): GraphQLType { + if (typeRef.kind === TypeKind.LIST) { + const itemRef = typeRef.ofType; + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + return GraphQLList(getType(itemRef)); + } + if (typeRef.kind === TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + const nullableType = getType(nullableRef); + return GraphQLNonNull(assertNullableType(nullableType)); + } + if (!typeRef.name) { + throw new Error('Unknown type reference: ' + inspect(typeRef)); + } + return getNamedType(typeRef.name); + } + + function getNamedType(typeName: string): GraphQLNamedType { + if (typeDefCache[typeName]) { + return typeDefCache[typeName]; + } + const typeIntrospection = typeIntrospectionMap[typeName]; + if (!typeIntrospection) { + throw new Error( + `Invalid or incomplete schema, unknown type: ${typeName}. Ensure ` + + 'that a full introspection query is used in order to build a ' + + 'client schema.', + ); + } + const typeDef = buildType(typeIntrospection); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + function getInputType(typeRef: IntrospectionInputTypeRef): GraphQLInputType { + const type = getType(typeRef); + invariant( + isInputType(type), + 'Introspection must provide input type for arguments.', + ); + return type; + } + + function getOutputType( + typeRef: IntrospectionOutputTypeRef, + ): GraphQLOutputType { + const type = getType(typeRef); + invariant( + isOutputType(type), + 'Introspection must provide output type for fields.', + ); + return type; + } + + function getObjectType( + typeRef: IntrospectionNamedTypeRef, + ): GraphQLObjectType { + const type = getType(typeRef); + return assertObjectType(type); + } + + function getInterfaceType( + typeRef: IntrospectionTypeRef, + ): GraphQLInterfaceType { + const type = getType(typeRef); + return assertInterfaceType(type); + } + + // Given a type's introspection result, construct the correct + // GraphQLType instance. + function buildType(type: IntrospectionType): GraphQLNamedType { + if (type && type.name && type.kind) { + switch (type.kind) { + case TypeKind.SCALAR: + return buildScalarDef(type); + case TypeKind.OBJECT: + return buildObjectDef(type); + case TypeKind.INTERFACE: + return buildInterfaceDef(type); + case TypeKind.UNION: + return buildUnionDef(type); + case TypeKind.ENUM: + return buildEnumDef(type); + case TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + throw new Error( + 'Invalid or incomplete introspection result. Ensure that a full ' + + 'introspection query is used in order to build a client schema:' + + inspect(type), + ); + } + + function buildScalarDef( + scalarIntrospection: IntrospectionScalarType, + ): GraphQLScalarType { + return new GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: value => value, + }); + } + + function buildObjectDef( + objectIntrospection: IntrospectionObjectType, + ): GraphQLObjectType { + if (!objectIntrospection.interfaces) { + throw new Error( + 'Introspection result missing interfaces: ' + + inspect(objectIntrospection), + ); + } + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => objectIntrospection.interfaces.map(getInterfaceType), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + + function buildInterfaceDef( + interfaceIntrospection: IntrospectionInterfaceType, + ): GraphQLInterfaceType { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + + function buildUnionDef( + unionIntrospection: IntrospectionUnionType, + ): GraphQLUnionType { + if (!unionIntrospection.possibleTypes) { + throw new Error( + 'Introspection result missing possibleTypes: ' + + inspect(unionIntrospection), + ); + } + return new GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType), + }); + } + + function buildEnumDef( + enumIntrospection: IntrospectionEnumType, + ): GraphQLEnumType { + if (!enumIntrospection.enumValues) { + throw new Error( + 'Introspection result missing enumValues: ' + + inspect(enumIntrospection), + ); + } + return new GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: keyValMap( + enumIntrospection.enumValues, + valueIntrospection => valueIntrospection.name, + valueIntrospection => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason, + }), + ), + }); + } + + function buildInputObjectDef( + inputObjectIntrospection: IntrospectionInputObjectType, + ): GraphQLInputObjectType { + if (!inputObjectIntrospection.inputFields) { + throw new Error( + 'Introspection result missing inputFields: ' + + inspect(inputObjectIntrospection), + ); + } + return new GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error( + 'Introspection result missing fields: ' + inspect(typeIntrospection), + ); + } + return keyValMap( + typeIntrospection.fields, + fieldIntrospection => fieldIntrospection.name, + fieldIntrospection => { + if (!fieldIntrospection.args) { + throw new Error( + 'Introspection result missing field args: ' + + inspect(fieldIntrospection), + ); + } + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args), + }; + }, + ); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return keyValMap( + inputValueIntrospections, + inputValue => inputValue.name, + buildInputValue, + ); + } + + function buildInputValue(inputValueIntrospection) { + const type = getInputType(inputValueIntrospection.type); + const defaultValue = inputValueIntrospection.defaultValue + ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) + : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + throw new Error( + 'Introspection result missing directive args: ' + + inspect(directiveIntrospection), + ); + } + if (!directiveIntrospection.locations) { + throw new Error( + 'Introspection result missing directive locations: ' + + inspect(directiveIntrospection), + ); + } + return new GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args), + }); + } + + // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + const types = schemaIntrospection.types.map(typeIntrospection => + getNamedType(typeIntrospection.name), + ); + + // Get the root Query, Mutation, and Subscription types. + const queryType = schemaIntrospection.queryType + ? getObjectType(schemaIntrospection.queryType) + : null; + + const mutationType = schemaIntrospection.mutationType + ? getObjectType(schemaIntrospection.mutationType) + : null; + + const subscriptionType = schemaIntrospection.subscriptionType + ? getObjectType(schemaIntrospection.subscriptionType) + : null; + + // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + const directives = schemaIntrospection.directives + ? schemaIntrospection.directives.map(buildDirective) + : []; + + // Then produce and return a Schema with these types. + return new GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types, + directives, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames, + }); +} diff --git a/node_modules/graphql/utilities/buildClientSchema.mjs b/node_modules/graphql/utilities/buildClientSchema.mjs new file mode 100644 index 00000000..83936227 --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.mjs @@ -0,0 +1,303 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../jsutils/inspect'; +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import { valueFromAST } from './valueFromAST'; +import { parseValue } from '../language/parser'; +import { GraphQLSchema } from '../type/schema'; +import { isInputType, isOutputType, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, assertNullableType, assertObjectType, assertInterfaceType } from '../type/definition'; +import { GraphQLDirective } from '../type/directives'; +import { introspectionTypes, TypeKind } from '../type/introspection'; +import { specifiedScalarTypes } from '../type/scalars'; + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + */ +export function buildClientSchema(introspection, options) { + // Get the schema from the introspection result. + var schemaIntrospection = introspection.__schema; // Converts the list of types into a keyMap based on the type names. + + var typeIntrospectionMap = keyMap(schemaIntrospection.types, function (type) { + return type.name; + }); // A cache to use to store the actual GraphQLType definition objects by name. + // Initialize to the GraphQL built in scalars. All functions below are inline + // so that this type def cache is within the scope of the closure. + + var typeDefCache = keyMap(specifiedScalarTypes.concat(introspectionTypes), function (type) { + return type.name; + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === TypeKind.LIST) { + var itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return GraphQLList(getType(itemRef)); + } + + if (typeRef.kind === TypeKind.NON_NULL) { + var nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + var nullableType = getType(nullableRef); + return GraphQLNonNull(assertNullableType(nullableType)); + } + + if (!typeRef.name) { + throw new Error('Unknown type reference: ' + inspect(typeRef)); + } + + return getNamedType(typeRef.name); + } + + function getNamedType(typeName) { + if (typeDefCache[typeName]) { + return typeDefCache[typeName]; + } + + var typeIntrospection = typeIntrospectionMap[typeName]; + + if (!typeIntrospection) { + throw new Error("Invalid or incomplete schema, unknown type: ".concat(typeName, ". Ensure ") + 'that a full introspection query is used in order to build a ' + 'client schema.'); + } + + var typeDef = buildType(typeIntrospection); + typeDefCache[typeName] = typeDef; + return typeDef; + } + + function getInputType(typeRef) { + var type = getType(typeRef); + !isInputType(type) ? invariant(0, 'Introspection must provide input type for arguments.') : void 0; + return type; + } + + function getOutputType(typeRef) { + var type = getType(typeRef); + !isOutputType(type) ? invariant(0, 'Introspection must provide output type for fields.') : void 0; + return type; + } + + function getObjectType(typeRef) { + var type = getType(typeRef); + return assertObjectType(type); + } + + function getInterfaceType(typeRef) { + var type = getType(typeRef); + return assertInterfaceType(type); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + + function buildType(type) { + if (type && type.name && type.kind) { + switch (type.kind) { + case TypeKind.SCALAR: + return buildScalarDef(type); + + case TypeKind.OBJECT: + return buildObjectDef(type); + + case TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case TypeKind.UNION: + return buildUnionDef(type); + + case TypeKind.ENUM: + return buildEnumDef(type); + + case TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + throw new Error('Invalid or incomplete introspection result. Ensure that a full ' + 'introspection query is used in order to build a client schema:' + inspect(type)); + } + + function buildScalarDef(scalarIntrospection) { + return new GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + serialize: function serialize(value) { + return value; + } + }); + } + + function buildObjectDef(objectIntrospection) { + if (!objectIntrospection.interfaces) { + throw new Error('Introspection result missing interfaces: ' + inspect(objectIntrospection)); + } + + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: function interfaces() { + return objectIntrospection.interfaces.map(getInterfaceType); + }, + fields: function fields() { + return buildFieldDefMap(objectIntrospection); + } + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + fields: function fields() { + return buildFieldDefMap(interfaceIntrospection); + } + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + throw new Error('Introspection result missing possibleTypes: ' + inspect(unionIntrospection)); + } + + return new GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: function types() { + return unionIntrospection.possibleTypes.map(getObjectType); + } + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + throw new Error('Introspection result missing enumValues: ' + inspect(enumIntrospection)); + } + + return new GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: keyValMap(enumIntrospection.enumValues, function (valueIntrospection) { + return valueIntrospection.name; + }, function (valueIntrospection) { + return { + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason + }; + }) + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + throw new Error('Introspection result missing inputFields: ' + inspect(inputObjectIntrospection)); + } + + return new GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: function fields() { + return buildInputValueDefMap(inputObjectIntrospection.inputFields); + } + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error('Introspection result missing fields: ' + inspect(typeIntrospection)); + } + + return keyValMap(typeIntrospection.fields, function (fieldIntrospection) { + return fieldIntrospection.name; + }, function (fieldIntrospection) { + if (!fieldIntrospection.args) { + throw new Error('Introspection result missing field args: ' + inspect(fieldIntrospection)); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type: getOutputType(fieldIntrospection.type), + args: buildInputValueDefMap(fieldIntrospection.args) + }; + }); + } + + function buildInputValueDefMap(inputValueIntrospections) { + return keyValMap(inputValueIntrospections, function (inputValue) { + return inputValue.name; + }, buildInputValue); + } + + function buildInputValue(inputValueIntrospection) { + var type = getInputType(inputValueIntrospection.type); + var defaultValue = inputValueIntrospection.defaultValue ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) : undefined; + return { + description: inputValueIntrospection.description, + type: type, + defaultValue: defaultValue + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + throw new Error('Introspection result missing directive args: ' + inspect(directiveIntrospection)); + } + + if (!directiveIntrospection.locations) { + throw new Error('Introspection result missing directive locations: ' + inspect(directiveIntrospection)); + } + + return new GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args) + }); + } // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + + + var types = schemaIntrospection.types.map(function (typeIntrospection) { + return getNamedType(typeIntrospection.name); + }); // Get the root Query, Mutation, and Subscription types. + + var queryType = schemaIntrospection.queryType ? getObjectType(schemaIntrospection.queryType) : null; + var mutationType = schemaIntrospection.mutationType ? getObjectType(schemaIntrospection.mutationType) : null; + var subscriptionType = schemaIntrospection.subscriptionType ? getObjectType(schemaIntrospection.subscriptionType) : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + var directives = schemaIntrospection.directives ? schemaIntrospection.directives.map(buildDirective) : []; // Then produce and return a Schema with these types. + + return new GraphQLSchema({ + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: types, + directives: directives, + assumeValid: options && options.assumeValid, + allowedLegacyNames: options && options.allowedLegacyNames + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/coerceValue.js b/node_modules/graphql/utilities/coerceValue.js new file mode 100644 index 00000000..17df0ce1 --- /dev/null +++ b/node_modules/graphql/utilities/coerceValue.js @@ -0,0 +1,202 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.coerceValue = coerceValue; + +var _iterall = require("iterall"); + +var _inspect = _interopRequireDefault(require("../jsutils/inspect")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _orList = _interopRequireDefault(require("../jsutils/orList")); + +var _suggestionList = _interopRequireDefault(require("../jsutils/suggestionList")); + +var _GraphQLError = require("../error/GraphQLError"); + +var _definition = require("../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +function coerceValue(value, type, blameNode, path) { + // A value must be provided if the type is non-null. + if ((0, _definition.isNonNullType)(type)) { + if (value == null) { + return ofErrors([coercionError("Expected non-nullable type ".concat((0, _inspect.default)(type), " not to be null"), blameNode, path)]); + } + + return coerceValue(value, type.ofType, blameNode, path); + } + + if (value == null) { + // Explicitly return the value null. + return ofValue(null); + } + + if ((0, _definition.isScalarType)(type)) { + // Scalars determine if a value is valid via parseValue(), which can + // throw to indicate failure. If it throws, maintain a reference to + // the original error. + try { + var parseResult = type.parseValue(value); + + if ((0, _isInvalid.default)(parseResult)) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]); + } + + return ofValue(parseResult); + } catch (error) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]); + } + } + + if ((0, _definition.isEnumType)(type)) { + if (typeof value === 'string') { + var enumValue = type.getValue(value); + + if (enumValue) { + return ofValue(enumValue.value); + } + } + + var suggestions = (0, _suggestionList.default)(String(value), type.getValues().map(function (enumValue) { + return enumValue.name; + })); + var didYouMean = suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined; + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]); + } + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + + if ((0, _iterall.isCollection)(value)) { + var errors; + var coercedValue = []; + (0, _iterall.forEach)(value, function (itemValue, index) { + var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index)); + + if (coercedItem.errors) { + errors = add(errors, coercedItem.errors); + } else if (!errors) { + coercedValue.push(coercedItem.value); + } + }); + return errors ? ofErrors(errors) : ofValue(coercedValue); + } // Lists accept a non-list value as a list of one. + + + var coercedItem = coerceValue(value, itemType, blameNode); + return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]); + } + + if ((0, _definition.isInputObjectType)(type)) { + if (_typeof(value) !== 'object') { + return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]); + } + + var _errors; + + var _coercedValue = {}; + var fields = type.getFields(); // Ensure every defined field is valid. + + for (var fieldName in fields) { + if (hasOwnProperty.call(fields, fieldName)) { + var field = fields[fieldName]; + var fieldValue = value[fieldName]; + + if ((0, _isInvalid.default)(fieldValue)) { + if (!(0, _isInvalid.default)(field.defaultValue)) { + _coercedValue[fieldName] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + _errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, fieldName)), " of required ") + "type ".concat((0, _inspect.default)(field.type), " was not provided"), blameNode)); + } + } else { + var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, fieldName)); + + if (coercedField.errors) { + _errors = add(_errors, coercedField.errors); + } else if (!_errors) { + _coercedValue[fieldName] = coercedField.value; + } + } + } + } // Ensure every provided field is defined. + + + for (var _fieldName in value) { + if (hasOwnProperty.call(value, _fieldName)) { + if (!fields[_fieldName]) { + var _suggestions = (0, _suggestionList.default)(_fieldName, Object.keys(fields)); + + var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat((0, _orList.default)(_suggestions), "?") : undefined; + + _errors = add(_errors, coercionError("Field \"".concat(_fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean)); + } + } + } + + return _errors ? ofErrors(_errors) : ofValue(_coercedValue); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type: ".concat(type, ".")); +} + +function ofValue(value) { + return { + errors: undefined, + value: value + }; +} + +function ofErrors(errors) { + return { + errors: errors, + value: undefined + }; +} + +function add(errors, moreErrors) { + return (errors || []).concat(moreErrors); +} + +function atPath(prev, key) { + return { + prev: prev, + key: key + }; +} + +function coercionError(message, blameNode, path, subMessage, originalError) { + var pathStr = printPath(path); // Return a GraphQLError instance + + return new _GraphQLError.GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError); +} // Build a string describing the path into the value where the error was found + + +function printPath(path) { + var pathStr = ''; + var currentPath = path; + + while (currentPath) { + pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr; + currentPath = currentPath.prev; + } + + return pathStr ? 'value' + pathStr : ''; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; \ No newline at end of file diff --git a/node_modules/graphql/utilities/coerceValue.js.flow b/node_modules/graphql/utilities/coerceValue.js.flow new file mode 100644 index 00000000..000d19dd --- /dev/null +++ b/node_modules/graphql/utilities/coerceValue.js.flow @@ -0,0 +1,257 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { forEach, isCollection } from 'iterall'; +import inspect from '../jsutils/inspect'; +import isInvalid from '../jsutils/isInvalid'; +import orList from '../jsutils/orList'; +import suggestionList from '../jsutils/suggestionList'; +import { GraphQLError } from '../error/GraphQLError'; +import type { ASTNode } from '../language/ast'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; +import type { GraphQLInputType } from '../type/definition'; + +type CoercedValue = {| + +errors: $ReadOnlyArray | void, + +value: mixed, +|}; + +type Path = {| +prev: Path | void, +key: string | number |}; + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +export function coerceValue( + value: mixed, + type: GraphQLInputType, + blameNode?: ASTNode, + path?: Path, +): CoercedValue { + // A value must be provided if the type is non-null. + if (isNonNullType(type)) { + if (value == null) { + return ofErrors([ + coercionError( + `Expected non-nullable type ${inspect(type)} not to be null`, + blameNode, + path, + ), + ]); + } + return coerceValue(value, type.ofType, blameNode, path); + } + + if (value == null) { + // Explicitly return the value null. + return ofValue(null); + } + + if (isScalarType(type)) { + // Scalars determine if a value is valid via parseValue(), which can + // throw to indicate failure. If it throws, maintain a reference to + // the original error. + try { + const parseResult = type.parseValue(value); + if (isInvalid(parseResult)) { + return ofErrors([ + coercionError(`Expected type ${type.name}`, blameNode, path), + ]); + } + return ofValue(parseResult); + } catch (error) { + return ofErrors([ + coercionError( + `Expected type ${type.name}`, + blameNode, + path, + error.message, + error, + ), + ]); + } + } + + if (isEnumType(type)) { + if (typeof value === 'string') { + const enumValue = type.getValue(value); + if (enumValue) { + return ofValue(enumValue.value); + } + } + const suggestions = suggestionList( + String(value), + type.getValues().map(enumValue => enumValue.name), + ); + const didYouMean = + suggestions.length !== 0 + ? `did you mean ${orList(suggestions)}?` + : undefined; + return ofErrors([ + coercionError(`Expected type ${type.name}`, blameNode, path, didYouMean), + ]); + } + + if (isListType(type)) { + const itemType = type.ofType; + if (isCollection(value)) { + let errors; + const coercedValue = []; + forEach((value: any), (itemValue, index) => { + const coercedItem = coerceValue( + itemValue, + itemType, + blameNode, + atPath(path, index), + ); + if (coercedItem.errors) { + errors = add(errors, coercedItem.errors); + } else if (!errors) { + coercedValue.push(coercedItem.value); + } + }); + return errors ? ofErrors(errors) : ofValue(coercedValue); + } + // Lists accept a non-list value as a list of one. + const coercedItem = coerceValue(value, itemType, blameNode); + return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]); + } + + if (isInputObjectType(type)) { + if (typeof value !== 'object') { + return ofErrors([ + coercionError( + `Expected type ${type.name} to be an object`, + blameNode, + path, + ), + ]); + } + let errors; + const coercedValue = {}; + const fields = type.getFields(); + + // Ensure every defined field is valid. + for (const fieldName in fields) { + if (hasOwnProperty.call(fields, fieldName)) { + const field = fields[fieldName]; + const fieldValue = value[fieldName]; + if (isInvalid(fieldValue)) { + if (!isInvalid(field.defaultValue)) { + coercedValue[fieldName] = field.defaultValue; + } else if (isNonNullType(field.type)) { + errors = add( + errors, + coercionError( + `Field ${printPath(atPath(path, fieldName))} of required ` + + `type ${inspect(field.type)} was not provided`, + blameNode, + ), + ); + } + } else { + const coercedField = coerceValue( + fieldValue, + field.type, + blameNode, + atPath(path, fieldName), + ); + if (coercedField.errors) { + errors = add(errors, coercedField.errors); + } else if (!errors) { + coercedValue[fieldName] = coercedField.value; + } + } + } + } + + // Ensure every provided field is defined. + for (const fieldName in value) { + if (hasOwnProperty.call(value, fieldName)) { + if (!fields[fieldName]) { + const suggestions = suggestionList(fieldName, Object.keys(fields)); + const didYouMean = + suggestions.length !== 0 + ? `did you mean ${orList(suggestions)}?` + : undefined; + errors = add( + errors, + coercionError( + `Field "${fieldName}" is not defined by type ${type.name}`, + blameNode, + path, + didYouMean, + ), + ); + } + } + } + + return errors ? ofErrors(errors) : ofValue(coercedValue); + } + + /* istanbul ignore next */ + throw new Error(`Unexpected type: ${(type: empty)}.`); +} + +function ofValue(value) { + return { errors: undefined, value }; +} + +function ofErrors(errors) { + return { errors, value: undefined }; +} + +function add(errors, moreErrors) { + return (errors || []).concat(moreErrors); +} + +function atPath(prev, key) { + return { prev, key }; +} + +function coercionError(message, blameNode, path, subMessage, originalError) { + const pathStr = printPath(path); + // Return a GraphQLError instance + return new GraphQLError( + message + + (pathStr ? ' at ' + pathStr : '') + + (subMessage ? '; ' + subMessage : '.'), + blameNode, + undefined, + undefined, + undefined, + originalError, + ); +} + +// Build a string describing the path into the value where the error was found +function printPath(path) { + let pathStr = ''; + let currentPath = path; + while (currentPath) { + pathStr = + (typeof currentPath.key === 'string' + ? '.' + currentPath.key + : '[' + String(currentPath.key) + ']') + pathStr; + currentPath = currentPath.prev; + } + return pathStr ? 'value' + pathStr : ''; +} + +const hasOwnProperty = Object.prototype.hasOwnProperty; diff --git a/node_modules/graphql/utilities/coerceValue.mjs b/node_modules/graphql/utilities/coerceValue.mjs new file mode 100644 index 00000000..2fdcd4e3 --- /dev/null +++ b/node_modules/graphql/utilities/coerceValue.mjs @@ -0,0 +1,195 @@ +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { forEach, isCollection } from 'iterall'; +import inspect from '../jsutils/inspect'; +import isInvalid from '../jsutils/isInvalid'; +import orList from '../jsutils/orList'; +import suggestionList from '../jsutils/suggestionList'; +import { GraphQLError } from '../error/GraphQLError'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition'; + +/** + * Coerces a JavaScript value given a GraphQL Type. + * + * Returns either a value which is valid for the provided type or a list of + * encountered coercion errors. + * + */ +export function coerceValue(value, type, blameNode, path) { + // A value must be provided if the type is non-null. + if (isNonNullType(type)) { + if (value == null) { + return ofErrors([coercionError("Expected non-nullable type ".concat(inspect(type), " not to be null"), blameNode, path)]); + } + + return coerceValue(value, type.ofType, blameNode, path); + } + + if (value == null) { + // Explicitly return the value null. + return ofValue(null); + } + + if (isScalarType(type)) { + // Scalars determine if a value is valid via parseValue(), which can + // throw to indicate failure. If it throws, maintain a reference to + // the original error. + try { + var parseResult = type.parseValue(value); + + if (isInvalid(parseResult)) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path)]); + } + + return ofValue(parseResult); + } catch (error) { + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, error.message, error)]); + } + } + + if (isEnumType(type)) { + if (typeof value === 'string') { + var enumValue = type.getValue(value); + + if (enumValue) { + return ofValue(enumValue.value); + } + } + + var suggestions = suggestionList(String(value), type.getValues().map(function (enumValue) { + return enumValue.name; + })); + var didYouMean = suggestions.length !== 0 ? "did you mean ".concat(orList(suggestions), "?") : undefined; + return ofErrors([coercionError("Expected type ".concat(type.name), blameNode, path, didYouMean)]); + } + + if (isListType(type)) { + var itemType = type.ofType; + + if (isCollection(value)) { + var errors; + var coercedValue = []; + forEach(value, function (itemValue, index) { + var coercedItem = coerceValue(itemValue, itemType, blameNode, atPath(path, index)); + + if (coercedItem.errors) { + errors = add(errors, coercedItem.errors); + } else if (!errors) { + coercedValue.push(coercedItem.value); + } + }); + return errors ? ofErrors(errors) : ofValue(coercedValue); + } // Lists accept a non-list value as a list of one. + + + var coercedItem = coerceValue(value, itemType, blameNode); + return coercedItem.errors ? coercedItem : ofValue([coercedItem.value]); + } + + if (isInputObjectType(type)) { + if (_typeof(value) !== 'object') { + return ofErrors([coercionError("Expected type ".concat(type.name, " to be an object"), blameNode, path)]); + } + + var _errors; + + var _coercedValue = {}; + var fields = type.getFields(); // Ensure every defined field is valid. + + for (var fieldName in fields) { + if (hasOwnProperty.call(fields, fieldName)) { + var field = fields[fieldName]; + var fieldValue = value[fieldName]; + + if (isInvalid(fieldValue)) { + if (!isInvalid(field.defaultValue)) { + _coercedValue[fieldName] = field.defaultValue; + } else if (isNonNullType(field.type)) { + _errors = add(_errors, coercionError("Field ".concat(printPath(atPath(path, fieldName)), " of required ") + "type ".concat(inspect(field.type), " was not provided"), blameNode)); + } + } else { + var coercedField = coerceValue(fieldValue, field.type, blameNode, atPath(path, fieldName)); + + if (coercedField.errors) { + _errors = add(_errors, coercedField.errors); + } else if (!_errors) { + _coercedValue[fieldName] = coercedField.value; + } + } + } + } // Ensure every provided field is defined. + + + for (var _fieldName in value) { + if (hasOwnProperty.call(value, _fieldName)) { + if (!fields[_fieldName]) { + var _suggestions = suggestionList(_fieldName, Object.keys(fields)); + + var _didYouMean = _suggestions.length !== 0 ? "did you mean ".concat(orList(_suggestions), "?") : undefined; + + _errors = add(_errors, coercionError("Field \"".concat(_fieldName, "\" is not defined by type ").concat(type.name), blameNode, path, _didYouMean)); + } + } + } + + return _errors ? ofErrors(_errors) : ofValue(_coercedValue); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type: ".concat(type, ".")); +} + +function ofValue(value) { + return { + errors: undefined, + value: value + }; +} + +function ofErrors(errors) { + return { + errors: errors, + value: undefined + }; +} + +function add(errors, moreErrors) { + return (errors || []).concat(moreErrors); +} + +function atPath(prev, key) { + return { + prev: prev, + key: key + }; +} + +function coercionError(message, blameNode, path, subMessage, originalError) { + var pathStr = printPath(path); // Return a GraphQLError instance + + return new GraphQLError(message + (pathStr ? ' at ' + pathStr : '') + (subMessage ? '; ' + subMessage : '.'), blameNode, undefined, undefined, undefined, originalError); +} // Build a string describing the path into the value where the error was found + + +function printPath(path) { + var pathStr = ''; + var currentPath = path; + + while (currentPath) { + pathStr = (typeof currentPath.key === 'string' ? '.' + currentPath.key : '[' + String(currentPath.key) + ']') + pathStr; + currentPath = currentPath.prev; + } + + return pathStr ? 'value' + pathStr : ''; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; \ No newline at end of file diff --git a/node_modules/graphql/utilities/concatAST.js b/node_modules/graphql/utilities/concatAST.js new file mode 100644 index 00000000..609185dc --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.js @@ -0,0 +1,37 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.concatAST = concatAST; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +function concatAST(asts) { + var batchDefinitions = []; + + for (var i = 0; i < asts.length; i++) { + var definitions = asts[i].definitions; + + for (var j = 0; j < definitions.length; j++) { + batchDefinitions.push(definitions[j]); + } + } + + return { + kind: 'Document', + definitions: batchDefinitions + }; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/concatAST.js.flow b/node_modules/graphql/utilities/concatAST.js.flow new file mode 100644 index 00000000..edeaa8f4 --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.js.flow @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { DocumentNode } from '../language/ast'; + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +export function concatAST(asts: $ReadOnlyArray): DocumentNode { + const batchDefinitions = []; + for (let i = 0; i < asts.length; i++) { + const definitions = asts[i].definitions; + for (let j = 0; j < definitions.length; j++) { + batchDefinitions.push(definitions[j]); + } + } + return { + kind: 'Document', + definitions: batchDefinitions, + }; +} diff --git a/node_modules/graphql/utilities/concatAST.mjs b/node_modules/graphql/utilities/concatAST.mjs new file mode 100644 index 00000000..6e5ddc4a --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.mjs @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + */ +export function concatAST(asts) { + var batchDefinitions = []; + + for (var i = 0; i < asts.length; i++) { + var definitions = asts[i].definitions; + + for (var j = 0; j < definitions.length; j++) { + batchDefinitions.push(definitions[j]); + } + } + + return { + kind: 'Document', + definitions: batchDefinitions + }; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/extendSchema.js b/node_modules/graphql/utilities/extendSchema.js new file mode 100644 index 00000000..125d63a4 --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.js @@ -0,0 +1,794 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.extendSchema = extendSchema; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _buildASTSchema = require("./buildASTSchema"); + +var _validate = require("../validation/validate"); + +var _GraphQLError = require("../error/GraphQLError"); + +var _schema = require("../type/schema"); + +var _introspection = require("../type/introspection"); + +var _scalars = require("../type/scalars"); + +var _definition = require("../type/definition"); + +var _directives = require("../type/directives"); + +var _kinds = require("../language/kinds"); + +var _predicates = require("../language/predicates"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function extendSchema(schema, documentAST, options) { + !(0, _schema.isSchema)(schema) ? (0, _invariant.default)(0, 'Must provide valid GraphQLSchema') : void 0; + !(documentAST && documentAST.kind === _kinds.Kind.DOCUMENT) ? (0, _invariant.default)(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); + } // Collect the type definitions and extensions found in the document. + + + var typeDefinitionMap = Object.create(null); + var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + var directiveDefinitions = []; + var schemaDef; // Schema extensions are collected which may add additional operation types. + + var schemaExtensions = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + // Sanity check that none of the defined types conflict with the + // schema's existing types. + var typeName = def.name.value; + + if (schema.getType(typeName)) { + throw new _GraphQLError.GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also ") + 'be defined in this type definition.', [def]); + } + + typeDefinitionMap[typeName] = def; + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + // Sanity check that this type extension exists within the + // schema's existing types. + var extendedTypeName = def.name.value; + var existingType = schema.getType(extendedTypeName); + + if (!existingType) { + throw new _GraphQLError.GraphQLError("Cannot extend type \"".concat(extendedTypeName, "\" because it does not ") + 'exist in the existing schema.', [def]); + } + + checkExtensionNode(existingType, def); + var existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var directiveName = def.name.value; + var existingDirective = schema.getDirective(directiveName); + + if (existingDirective) { + throw new _GraphQLError.GraphQLError("Directive \"".concat(directiveName, "\" already exists in the schema. It ") + 'cannot be redefined.', [def]); + } + + directiveDefinitions.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + + if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) { + return schema; + } + + var astBuilder = new _buildASTSchema.ASTDefinitionBuilder(typeDefinitionMap, options, function (typeRef) { + var typeName = typeRef.name.value; + var existingType = schema.getType(typeName); + + if (existingType) { + return extendNamedType(existingType); + } + + throw new _GraphQLError.GraphQLError("Unknown type: \"".concat(typeName, "\". Ensure that this type exists ") + 'either in the original schema, or is added in a type definition.', [typeRef]); + }); + var extendTypeCache = Object.create(null); // Get the extended root operation types. + + var operationTypes = { + query: extendMaybeNamedType(schema.getQueryType()), + mutation: extendMaybeNamedType(schema.getMutationType()), + subscription: extendMaybeNamedType(schema.getSubscriptionType()) + }; + + if (schemaDef) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schemaDef.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var operation = _ref2.operation, + type = _ref2.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } // Then, incorporate schema definition and all schema extensions. + + + for (var _i = 0; _i < schemaExtensions.length; _i++) { + var schemaExtension = schemaExtensions[_i]; + + if (schemaExtension.operationTypes) { + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = schemaExtension.operationTypes[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var _ref4 = _step12.value; + var operation = _ref4.operation, + type = _ref4.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + } + + var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes; + var types = (0, _objectValues.default)(schema.getTypeMap()).map(function (type) { + return extendNamedType(type); + }).concat((0, _objectValues.default)(typeDefinitionMap).map(function (type) { + return astBuilder.buildType(type); + })); // Support both original legacy names and extended legacy names. + + var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types. + + + return new _schema.GraphQLSchema(_objectSpread({}, operationTypes, { + types: types, + directives: getMergedDirectives(), + astNode: schema.astNode, + extensionASTNodes: schemaExtensionASTNodes, + allowedLegacyNames: allowedLegacyNames + })); // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function getMergedDirectives() { + var existingDirectives = schema.getDirectives().map(extendDirective); + !existingDirectives ? (0, _invariant.default)(0, 'schema must have default directives') : void 0; + return existingDirectives.concat(directiveDefinitions.map(function (node) { + return astBuilder.buildDirective(node); + })); + } + + function extendMaybeNamedType(type) { + return type ? extendNamedType(type) : null; + } + + function extendNamedType(type) { + if ((0, _introspection.isIntrospectionType)(type) || (0, _scalars.isSpecifiedScalarType)(type)) { + // Builtin types are not extended. + return type; + } + + var name = type.name; + + if (!extendTypeCache[name]) { + if ((0, _definition.isScalarType)(type)) { + extendTypeCache[name] = extendScalarType(type); + } else if ((0, _definition.isObjectType)(type)) { + extendTypeCache[name] = extendObjectType(type); + } else if ((0, _definition.isInterfaceType)(type)) { + extendTypeCache[name] = extendInterfaceType(type); + } else if ((0, _definition.isUnionType)(type)) { + extendTypeCache[name] = extendUnionType(type); + } else if ((0, _definition.isEnumType)(type)) { + extendTypeCache[name] = extendEnumType(type); + } else if ((0, _definition.isInputObjectType)(type)) { + extendTypeCache[name] = extendInputObjectType(type); + } + } + + return extendTypeCache[name]; + } + + function extendDirective(directive) { + return new _directives.GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: directive.locations, + args: extendArgs(directive.args), + astNode: directive.astNode + }); + } + + function extendInputObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLInputObjectType({ + name: name, + description: type.description, + fields: function fields() { + return extendInputFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendInputFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr = Object.keys(oldFieldMap); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var _fieldName = _arr[_i2]; + var _field = oldFieldMap[_fieldName]; + newFieldMap[_fieldName] = { + description: _field.description, + type: extendType(_field.type), + defaultValue: _field.defaultValue, + astNode: _field.astNode + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = extensions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var extension = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = extension.fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var field = _step3.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildInputField(field); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return newFieldMap; + } + + function extendEnumType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLEnumType({ + name: name, + description: type.description, + values: extendValueMap(type), + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendValueMap(type) { + var newValueMap = Object.create(null); + var oldValueMap = (0, _keyMap.default)(type.getValues(), function (value) { + return value.name; + }); + + var _arr2 = Object.keys(oldValueMap); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var _valueName = _arr2[_i3]; + var _value = oldValueMap[_valueName]; + newValueMap[_valueName] = { + name: _value.name, + description: _value.description, + value: _value.value, + deprecationReason: _value.deprecationReason, + astNode: _value.astNode + }; + } // If there are any extensions to the values, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = extensions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var extension = _step4.value; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = extension.values[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var value = _step5.value; + var valueName = value.name.value; + + if (oldValueMap[valueName]) { + throw new _GraphQLError.GraphQLError("Enum value \"".concat(type.name, ".").concat(valueName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [value]); + } + + newValueMap[valueName] = astBuilder.buildEnumValue(value); + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return newValueMap; + } + + function extendScalarType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLScalarType({ + name: name, + description: type.description, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + serialize: type.serialize, + parseValue: type.parseValue, + parseLiteral: type.parseLiteral + }); + } + + function extendObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLObjectType({ + name: name, + description: type.description, + interfaces: function interfaces() { + return extendImplementedInterfaces(type); + }, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + isTypeOf: type.isTypeOf + }); + } + + function extendArgs(args) { + return (0, _keyValMap.default)(args, function (arg) { + return arg.name; + }, function (arg) { + return { + type: extendType(arg.type), + defaultValue: arg.defaultValue, + description: arg.description, + astNode: arg.astNode + }; + }); + } + + function extendInterfaceType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + resolveType: type.resolveType + }); + } + + function extendUnionType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new _definition.GraphQLUnionType({ + name: name, + description: type.description, + types: function types() { + return extendPossibleTypes(type); + }, + astNode: type.astNode, + resolveType: type.resolveType, + extensionASTNodes: extensionASTNodes + }); + } + + function extendPossibleTypes(type) { + var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var extension = _step6.value; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = extension.types[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var namedType = _step7.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + possibleTypes.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return possibleTypes; + } + + function extendImplementedInterfaces(type) { + var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var extension = _step8.value; + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = extension.interfaces[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var namedType = _step9.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return interfaces; + } + + function extendFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr3 = Object.keys(oldFieldMap); + + for (var _i4 = 0; _i4 < _arr3.length; _i4++) { + var _fieldName2 = _arr3[_i4]; + var _field2 = oldFieldMap[_fieldName2]; + newFieldMap[_fieldName2] = { + description: _field2.description, + deprecationReason: _field2.deprecationReason, + type: extendType(_field2.type), + args: extendArgs(_field2.args), + astNode: _field2.astNode, + resolve: _field2.resolve + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var extension = _step10.value; + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = extension.fields[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var field = _step11.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new _GraphQLError.GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildField(field); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return newFieldMap; + } + + function extendType(typeDef) { + if ((0, _definition.isListType)(typeDef)) { + return (0, _definition.GraphQLList)(extendType(typeDef.ofType)); + } + + if ((0, _definition.isNonNullType)(typeDef)) { + return (0, _definition.GraphQLNonNull)(extendType(typeDef.ofType)); + } + + return extendNamedType(typeDef); + } +} + +function checkExtensionNode(type, node) { + switch (node.kind) { + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + if (!(0, _definition.isObjectType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-object type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + if (!(0, _definition.isInterfaceType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-interface type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.ENUM_TYPE_EXTENSION: + if (!(0, _definition.isEnumType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-enum type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.UNION_TYPE_EXTENSION: + if (!(0, _definition.isUnionType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-union type \"".concat(type.name, "\"."), [node]); + } + + break; + + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + if (!(0, _definition.isInputObjectType)(type)) { + throw new _GraphQLError.GraphQLError("Cannot extend non-input object type \"".concat(type.name, "\"."), [node]); + } + + break; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/extendSchema.js.flow b/node_modules/graphql/utilities/extendSchema.js.flow new file mode 100644 index 00000000..62b184a5 --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.js.flow @@ -0,0 +1,645 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { ASTDefinitionBuilder } from './buildASTSchema'; +import { assertValidSDLExtension } from '../validation/validate'; +import { GraphQLError } from '../error/GraphQLError'; +import { isSchema, GraphQLSchema } from '../type/schema'; +import { isIntrospectionType } from '../type/introspection'; +import { isSpecifiedScalarType } from '../type/scalars'; + +import type { GraphQLSchemaValidationOptions } from '../type/schema'; + +import type { + GraphQLType, + GraphQLNamedType, + GraphQLArgument, + GraphQLFieldConfigArgumentMap, +} from '../type/definition'; + +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isListType, + isNonNullType, + isEnumType, + isInputObjectType, + GraphQLList, + GraphQLNonNull, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, +} from '../type/definition'; + +import { GraphQLDirective } from '../type/directives'; + +import { Kind } from '../language/kinds'; + +import type { + DocumentNode, + DirectiveDefinitionNode, + SchemaExtensionNode, + SchemaDefinitionNode, +} from '../language/ast'; +import { + isTypeDefinitionNode, + isTypeExtensionNode, +} from '../language/predicates'; + +type Options = {| + ...GraphQLSchemaValidationOptions, + + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, + + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean, +|}; + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema( + schema: GraphQLSchema, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchema { + invariant(isSchema(schema), 'Must provide valid GraphQLSchema'); + + invariant( + documentAST && documentAST.kind === Kind.DOCUMENT, + 'Must provide valid Document AST', + ); + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDLExtension(documentAST, schema); + } + + // Collect the type definitions and extensions found in the document. + const typeDefinitionMap = Object.create(null); + const typeExtensionsMap = Object.create(null); + + // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + const directiveDefinitions: Array = []; + + let schemaDef: ?SchemaDefinitionNode; + // Schema extensions are collected which may add additional operation types. + const schemaExtensions: Array = []; + + for (let i = 0; i < documentAST.definitions.length; i++) { + const def = documentAST.definitions[i]; + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if (isTypeDefinitionNode(def)) { + // Sanity check that none of the defined types conflict with the + // schema's existing types. + const typeName = def.name.value; + if (schema.getType(typeName)) { + throw new GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also ` + + 'be defined in this type definition.', + [def], + ); + } + typeDefinitionMap[typeName] = def; + } else if (isTypeExtensionNode(def)) { + // Sanity check that this type extension exists within the + // schema's existing types. + const extendedTypeName = def.name.value; + const existingType = schema.getType(extendedTypeName); + if (!existingType) { + throw new GraphQLError( + `Cannot extend type "${extendedTypeName}" because it does not ` + + 'exist in the existing schema.', + [def], + ); + } + checkExtensionNode(existingType, def); + + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions + ? existingTypeExtensions.concat([def]) + : [def]; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + const directiveName = def.name.value; + const existingDirective = schema.getDirective(directiveName); + if (existingDirective) { + throw new GraphQLError( + `Directive "${directiveName}" already exists in the schema. It ` + + 'cannot be redefined.', + [def], + ); + } + directiveDefinitions.push(def); + } + } + + // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + if ( + Object.keys(typeExtensionsMap).length === 0 && + Object.keys(typeDefinitionMap).length === 0 && + directiveDefinitions.length === 0 && + schemaExtensions.length === 0 && + !schemaDef + ) { + return schema; + } + + const astBuilder = new ASTDefinitionBuilder( + typeDefinitionMap, + options, + typeRef => { + const typeName = typeRef.name.value; + const existingType = schema.getType(typeName); + if (existingType) { + return extendNamedType(existingType); + } + + throw new GraphQLError( + `Unknown type: "${typeName}". Ensure that this type exists ` + + 'either in the original schema, or is added in a type definition.', + [typeRef], + ); + }, + ); + + const extendTypeCache = Object.create(null); + + // Get the extended root operation types. + const operationTypes = { + query: extendMaybeNamedType(schema.getQueryType()), + mutation: extendMaybeNamedType(schema.getMutationType()), + subscription: extendMaybeNamedType(schema.getSubscriptionType()), + }; + + if (schemaDef) { + for (const { operation, type } of schemaDef.operationTypes) { + if (operationTypes[operation]) { + throw new Error(`Must provide only one ${operation} type in schema.`); + } + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + operationTypes[operation] = (astBuilder.buildType(type): any); + } + } + // Then, incorporate schema definition and all schema extensions. + for (const schemaExtension of schemaExtensions) { + if (schemaExtension.operationTypes) { + for (const { operation, type } of schemaExtension.operationTypes) { + if (operationTypes[operation]) { + throw new Error(`Must provide only one ${operation} type in schema.`); + } + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + operationTypes[operation] = (astBuilder.buildType(type): any); + } + } + } + + const schemaExtensionASTNodes = schemaExtensions + ? schema.extensionASTNodes + ? schema.extensionASTNodes.concat(schemaExtensions) + : schemaExtensions + : schema.extensionASTNodes; + + const types = [ + // Iterate through all types, getting the type definition for each, ensuring + // that any type not directly referenced by a field will get created. + ...objectValues(schema.getTypeMap()).map(type => extendNamedType(type)), + // Do the same with new types. + ...objectValues(typeDefinitionMap).map(type => astBuilder.buildType(type)), + ]; + + // Support both original legacy names and extended legacy names. + const allowedLegacyNames = schema.__allowedLegacyNames.concat( + (options && options.allowedLegacyNames) || [], + ); + + // Then produce and return a Schema with these types. + return new GraphQLSchema({ + ...operationTypes, + types, + directives: getMergedDirectives(), + astNode: schema.astNode, + extensionASTNodes: schemaExtensionASTNodes, + allowedLegacyNames, + }); + + // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function getMergedDirectives(): Array { + const existingDirectives = schema.getDirectives().map(extendDirective); + invariant(existingDirectives, 'schema must have default directives'); + + return existingDirectives.concat( + directiveDefinitions.map(node => astBuilder.buildDirective(node)), + ); + } + + function extendMaybeNamedType(type: ?T): ?T { + return type ? extendNamedType(type) : null; + } + + function extendNamedType(type: T): T { + if (isIntrospectionType(type) || isSpecifiedScalarType(type)) { + // Builtin types are not extended. + return type; + } + + const name = type.name; + if (!extendTypeCache[name]) { + if (isScalarType(type)) { + extendTypeCache[name] = extendScalarType(type); + } else if (isObjectType(type)) { + extendTypeCache[name] = extendObjectType(type); + } else if (isInterfaceType(type)) { + extendTypeCache[name] = extendInterfaceType(type); + } else if (isUnionType(type)) { + extendTypeCache[name] = extendUnionType(type); + } else if (isEnumType(type)) { + extendTypeCache[name] = extendEnumType(type); + } else if (isInputObjectType(type)) { + extendTypeCache[name] = extendInputObjectType(type); + } + } + return (extendTypeCache[name]: any); + } + + function extendDirective(directive: GraphQLDirective): GraphQLDirective { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: directive.locations, + args: extendArgs(directive.args), + astNode: directive.astNode, + }); + } + + function extendInputObjectType( + type: GraphQLInputObjectType, + ): GraphQLInputObjectType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLInputObjectType({ + name, + description: type.description, + fields: () => extendInputFieldMap(type), + astNode: type.astNode, + extensionASTNodes, + }); + } + + function extendInputFieldMap(type: GraphQLInputObjectType) { + const newFieldMap = Object.create(null); + const oldFieldMap = type.getFields(); + for (const fieldName of Object.keys(oldFieldMap)) { + const field = oldFieldMap[fieldName]; + newFieldMap[fieldName] = { + description: field.description, + type: extendType(field.type), + defaultValue: field.defaultValue, + astNode: field.astNode, + }; + } + + // If there are any extensions to the fields, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const field of extension.fields) { + const fieldName = field.name.value; + if (oldFieldMap[fieldName]) { + throw new GraphQLError( + `Field "${type.name}.${fieldName}" already exists in the ` + + 'schema. It cannot also be defined in this type extension.', + [field], + ); + } + newFieldMap[fieldName] = astBuilder.buildInputField(field); + } + } + } + + return newFieldMap; + } + + function extendEnumType(type: GraphQLEnumType): GraphQLEnumType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLEnumType({ + name, + description: type.description, + values: extendValueMap(type), + astNode: type.astNode, + extensionASTNodes, + }); + } + + function extendValueMap(type: GraphQLEnumType) { + const newValueMap = Object.create(null); + const oldValueMap = keyMap(type.getValues(), value => value.name); + for (const valueName of Object.keys(oldValueMap)) { + const value = oldValueMap[valueName]; + newValueMap[valueName] = { + name: value.name, + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + astNode: value.astNode, + }; + } + + // If there are any extensions to the values, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const value of extension.values) { + const valueName = value.name.value; + if (oldValueMap[valueName]) { + throw new GraphQLError( + `Enum value "${type.name}.${valueName}" already exists in the ` + + 'schema. It cannot also be defined in this type extension.', + [value], + ); + } + newValueMap[valueName] = astBuilder.buildEnumValue(value); + } + } + } + + return newValueMap; + } + + function extendScalarType(type: GraphQLScalarType): GraphQLScalarType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLScalarType({ + name, + description: type.description, + astNode: type.astNode, + extensionASTNodes, + serialize: type.serialize, + parseValue: type.parseValue, + parseLiteral: type.parseLiteral, + }); + } + + function extendObjectType(type: GraphQLObjectType): GraphQLObjectType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLObjectType({ + name, + description: type.description, + interfaces: () => extendImplementedInterfaces(type), + fields: () => extendFieldMap(type), + astNode: type.astNode, + extensionASTNodes, + isTypeOf: type.isTypeOf, + }); + } + + function extendArgs( + args: Array, + ): GraphQLFieldConfigArgumentMap { + return keyValMap( + args, + arg => arg.name, + arg => ({ + type: extendType(arg.type), + defaultValue: arg.defaultValue, + description: arg.description, + astNode: arg.astNode, + }), + ); + } + + function extendInterfaceType( + type: GraphQLInterfaceType, + ): GraphQLInterfaceType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: () => extendFieldMap(type), + astNode: type.astNode, + extensionASTNodes, + resolveType: type.resolveType, + }); + } + + function extendUnionType(type: GraphQLUnionType): GraphQLUnionType { + const name = type.name; + const extensionASTNodes = typeExtensionsMap[name] + ? type.extensionASTNodes + ? type.extensionASTNodes.concat(typeExtensionsMap[name]) + : typeExtensionsMap[name] + : type.extensionASTNodes; + return new GraphQLUnionType({ + name, + description: type.description, + types: () => extendPossibleTypes(type), + astNode: type.astNode, + resolveType: type.resolveType, + extensionASTNodes, + }); + } + + function extendPossibleTypes( + type: GraphQLUnionType, + ): Array { + const possibleTypes = type.getTypes().map(extendNamedType); + + // If there are any extensions to the union, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const namedType of extension.types) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + possibleTypes.push((astBuilder.buildType(namedType): any)); + } + } + } + return possibleTypes; + } + + function extendImplementedInterfaces( + type: GraphQLObjectType, + ): Array { + const interfaces = type.getInterfaces().map(extendNamedType); + + // If there are any extensions to the interfaces, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const namedType of extension.interfaces) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces.push((astBuilder.buildType(namedType): any)); + } + } + } + + return interfaces; + } + + function extendFieldMap(type: GraphQLObjectType | GraphQLInterfaceType) { + const newFieldMap = Object.create(null); + const oldFieldMap = type.getFields(); + for (const fieldName of Object.keys(oldFieldMap)) { + const field = oldFieldMap[fieldName]; + newFieldMap[fieldName] = { + description: field.description, + deprecationReason: field.deprecationReason, + type: extendType(field.type), + args: extendArgs(field.args), + astNode: field.astNode, + resolve: field.resolve, + }; + } + + // If there are any extensions to the fields, apply those here. + const extensions = typeExtensionsMap[type.name]; + if (extensions) { + for (const extension of extensions) { + for (const field of extension.fields) { + const fieldName = field.name.value; + if (oldFieldMap[fieldName]) { + throw new GraphQLError( + `Field "${type.name}.${fieldName}" already exists in the ` + + 'schema. It cannot also be defined in this type extension.', + [field], + ); + } + newFieldMap[fieldName] = astBuilder.buildField(field); + } + } + } + + return newFieldMap; + } + + function extendType(typeDef: T): T { + if (isListType(typeDef)) { + return (GraphQLList(extendType(typeDef.ofType)): any); + } + if (isNonNullType(typeDef)) { + return (GraphQLNonNull(extendType(typeDef.ofType)): any); + } + return extendNamedType(typeDef); + } +} + +function checkExtensionNode(type, node) { + switch (node.kind) { + case Kind.OBJECT_TYPE_EXTENSION: + if (!isObjectType(type)) { + throw new GraphQLError( + `Cannot extend non-object type "${type.name}".`, + [node], + ); + } + break; + case Kind.INTERFACE_TYPE_EXTENSION: + if (!isInterfaceType(type)) { + throw new GraphQLError( + `Cannot extend non-interface type "${type.name}".`, + [node], + ); + } + break; + case Kind.ENUM_TYPE_EXTENSION: + if (!isEnumType(type)) { + throw new GraphQLError(`Cannot extend non-enum type "${type.name}".`, [ + node, + ]); + } + break; + case Kind.UNION_TYPE_EXTENSION: + if (!isUnionType(type)) { + throw new GraphQLError(`Cannot extend non-union type "${type.name}".`, [ + node, + ]); + } + break; + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + if (!isInputObjectType(type)) { + throw new GraphQLError( + `Cannot extend non-input object type "${type.name}".`, + [node], + ); + } + break; + } +} diff --git a/node_modules/graphql/utilities/extendSchema.mjs b/node_modules/graphql/utilities/extendSchema.mjs new file mode 100644 index 00000000..c4a1d995 --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.mjs @@ -0,0 +1,780 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import keyMap from '../jsutils/keyMap'; +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { ASTDefinitionBuilder } from './buildASTSchema'; +import { assertValidSDLExtension } from '../validation/validate'; +import { GraphQLError } from '../error/GraphQLError'; +import { isSchema, GraphQLSchema } from '../type/schema'; +import { isIntrospectionType } from '../type/introspection'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isListType, isNonNullType, isEnumType, isInputObjectType, GraphQLList, GraphQLNonNull, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType } from '../type/definition'; +import { GraphQLDirective } from '../type/directives'; +import { Kind } from '../language/kinds'; +import { isTypeDefinitionNode, isTypeExtensionNode } from '../language/predicates'; + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * + * Accepts options as a third argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function extendSchema(schema, documentAST, options) { + !isSchema(schema) ? invariant(0, 'Must provide valid GraphQLSchema') : void 0; + !(documentAST && documentAST.kind === Kind.DOCUMENT) ? invariant(0, 'Must provide valid Document AST') : void 0; + + if (!options || !(options.assumeValid || options.assumeValidSDL)) { + assertValidSDLExtension(documentAST, schema); + } // Collect the type definitions and extensions found in the document. + + + var typeDefinitionMap = Object.create(null); + var typeExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + var directiveDefinitions = []; + var schemaDef; // Schema extensions are collected which may add additional operation types. + + var schemaExtensions = []; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var def = documentAST.definitions[i]; + + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if (isTypeDefinitionNode(def)) { + // Sanity check that none of the defined types conflict with the + // schema's existing types. + var typeName = def.name.value; + + if (schema.getType(typeName)) { + throw new GraphQLError("Type \"".concat(typeName, "\" already exists in the schema. It cannot also ") + 'be defined in this type definition.', [def]); + } + + typeDefinitionMap[typeName] = def; + } else if (isTypeExtensionNode(def)) { + // Sanity check that this type extension exists within the + // schema's existing types. + var extendedTypeName = def.name.value; + var existingType = schema.getType(extendedTypeName); + + if (!existingType) { + throw new GraphQLError("Cannot extend type \"".concat(extendedTypeName, "\" because it does not ") + 'exist in the existing schema.', [def]); + } + + checkExtensionNode(existingType, def); + var existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions ? existingTypeExtensions.concat([def]) : [def]; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + var directiveName = def.name.value; + var existingDirective = schema.getDirective(directiveName); + + if (existingDirective) { + throw new GraphQLError("Directive \"".concat(directiveName, "\" already exists in the schema. It ") + 'cannot be redefined.', [def]); + } + + directiveDefinitions.push(def); + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + + if (Object.keys(typeExtensionsMap).length === 0 && Object.keys(typeDefinitionMap).length === 0 && directiveDefinitions.length === 0 && schemaExtensions.length === 0 && !schemaDef) { + return schema; + } + + var astBuilder = new ASTDefinitionBuilder(typeDefinitionMap, options, function (typeRef) { + var typeName = typeRef.name.value; + var existingType = schema.getType(typeName); + + if (existingType) { + return extendNamedType(existingType); + } + + throw new GraphQLError("Unknown type: \"".concat(typeName, "\". Ensure that this type exists ") + 'either in the original schema, or is added in a type definition.', [typeRef]); + }); + var extendTypeCache = Object.create(null); // Get the extended root operation types. + + var operationTypes = { + query: extendMaybeNamedType(schema.getQueryType()), + mutation: extendMaybeNamedType(schema.getMutationType()), + subscription: extendMaybeNamedType(schema.getSubscriptionType()) + }; + + if (schemaDef) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schemaDef.operationTypes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var operation = _ref2.operation, + type = _ref2.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } // Then, incorporate schema definition and all schema extensions. + + + for (var _i = 0; _i < schemaExtensions.length; _i++) { + var schemaExtension = schemaExtensions[_i]; + + if (schemaExtension.operationTypes) { + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + for (var _iterator12 = schemaExtension.operationTypes[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + var _ref4 = _step12.value; + var operation = _ref4.operation, + type = _ref4.type; + + if (operationTypes[operation]) { + throw new Error("Must provide only one ".concat(operation, " type in schema.")); + } // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + + + operationTypes[operation] = astBuilder.buildType(type); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + } + + var schemaExtensionASTNodes = schemaExtensions ? schema.extensionASTNodes ? schema.extensionASTNodes.concat(schemaExtensions) : schemaExtensions : schema.extensionASTNodes; + var types = objectValues(schema.getTypeMap()).map(function (type) { + return extendNamedType(type); + }).concat(objectValues(typeDefinitionMap).map(function (type) { + return astBuilder.buildType(type); + })); // Support both original legacy names and extended legacy names. + + var allowedLegacyNames = schema.__allowedLegacyNames.concat(options && options.allowedLegacyNames || []); // Then produce and return a Schema with these types. + + + return new GraphQLSchema(_objectSpread({}, operationTypes, { + types: types, + directives: getMergedDirectives(), + astNode: schema.astNode, + extensionASTNodes: schemaExtensionASTNodes, + allowedLegacyNames: allowedLegacyNames + })); // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function getMergedDirectives() { + var existingDirectives = schema.getDirectives().map(extendDirective); + !existingDirectives ? invariant(0, 'schema must have default directives') : void 0; + return existingDirectives.concat(directiveDefinitions.map(function (node) { + return astBuilder.buildDirective(node); + })); + } + + function extendMaybeNamedType(type) { + return type ? extendNamedType(type) : null; + } + + function extendNamedType(type) { + if (isIntrospectionType(type) || isSpecifiedScalarType(type)) { + // Builtin types are not extended. + return type; + } + + var name = type.name; + + if (!extendTypeCache[name]) { + if (isScalarType(type)) { + extendTypeCache[name] = extendScalarType(type); + } else if (isObjectType(type)) { + extendTypeCache[name] = extendObjectType(type); + } else if (isInterfaceType(type)) { + extendTypeCache[name] = extendInterfaceType(type); + } else if (isUnionType(type)) { + extendTypeCache[name] = extendUnionType(type); + } else if (isEnumType(type)) { + extendTypeCache[name] = extendEnumType(type); + } else if (isInputObjectType(type)) { + extendTypeCache[name] = extendInputObjectType(type); + } + } + + return extendTypeCache[name]; + } + + function extendDirective(directive) { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: directive.locations, + args: extendArgs(directive.args), + astNode: directive.astNode + }); + } + + function extendInputObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLInputObjectType({ + name: name, + description: type.description, + fields: function fields() { + return extendInputFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendInputFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr = Object.keys(oldFieldMap); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var _fieldName = _arr[_i2]; + var _field = oldFieldMap[_fieldName]; + newFieldMap[_fieldName] = { + description: _field.description, + type: extendType(_field.type), + defaultValue: _field.defaultValue, + astNode: _field.astNode + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = extensions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var extension = _step2.value; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = extension.fields[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var field = _step3.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildInputField(field); + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + + return newFieldMap; + } + + function extendEnumType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLEnumType({ + name: name, + description: type.description, + values: extendValueMap(type), + astNode: type.astNode, + extensionASTNodes: extensionASTNodes + }); + } + + function extendValueMap(type) { + var newValueMap = Object.create(null); + var oldValueMap = keyMap(type.getValues(), function (value) { + return value.name; + }); + + var _arr2 = Object.keys(oldValueMap); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var _valueName = _arr2[_i3]; + var _value = oldValueMap[_valueName]; + newValueMap[_valueName] = { + name: _value.name, + description: _value.description, + value: _value.value, + deprecationReason: _value.deprecationReason, + astNode: _value.astNode + }; + } // If there are any extensions to the values, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = extensions[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var extension = _step4.value; + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = extension.values[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var value = _step5.value; + var valueName = value.name.value; + + if (oldValueMap[valueName]) { + throw new GraphQLError("Enum value \"".concat(type.name, ".").concat(valueName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [value]); + } + + newValueMap[valueName] = astBuilder.buildEnumValue(value); + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return newValueMap; + } + + function extendScalarType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLScalarType({ + name: name, + description: type.description, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + serialize: type.serialize, + parseValue: type.parseValue, + parseLiteral: type.parseLiteral + }); + } + + function extendObjectType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLObjectType({ + name: name, + description: type.description, + interfaces: function interfaces() { + return extendImplementedInterfaces(type); + }, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + isTypeOf: type.isTypeOf + }); + } + + function extendArgs(args) { + return keyValMap(args, function (arg) { + return arg.name; + }, function (arg) { + return { + type: extendType(arg.type), + defaultValue: arg.defaultValue, + description: arg.description, + astNode: arg.astNode + }; + }); + } + + function extendInterfaceType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLInterfaceType({ + name: type.name, + description: type.description, + fields: function fields() { + return extendFieldMap(type); + }, + astNode: type.astNode, + extensionASTNodes: extensionASTNodes, + resolveType: type.resolveType + }); + } + + function extendUnionType(type) { + var name = type.name; + var extensionASTNodes = typeExtensionsMap[name] ? type.extensionASTNodes ? type.extensionASTNodes.concat(typeExtensionsMap[name]) : typeExtensionsMap[name] : type.extensionASTNodes; + return new GraphQLUnionType({ + name: name, + description: type.description, + types: function types() { + return extendPossibleTypes(type); + }, + astNode: type.astNode, + resolveType: type.resolveType, + extensionASTNodes: extensionASTNodes + }); + } + + function extendPossibleTypes(type) { + var possibleTypes = type.getTypes().map(extendNamedType); // If there are any extensions to the union, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = extensions[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var extension = _step6.value; + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = extension.types[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var namedType = _step7.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + possibleTypes.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return possibleTypes; + } + + function extendImplementedInterfaces(type) { + var interfaces = type.getInterfaces().map(extendNamedType); // If there are any extensions to the interfaces, apply those here. + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = extensions[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var extension = _step8.value; + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = extension.interfaces[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var namedType = _step9.value; + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + interfaces.push(astBuilder.buildType(namedType)); + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return interfaces; + } + + function extendFieldMap(type) { + var newFieldMap = Object.create(null); + var oldFieldMap = type.getFields(); + + var _arr3 = Object.keys(oldFieldMap); + + for (var _i4 = 0; _i4 < _arr3.length; _i4++) { + var _fieldName2 = _arr3[_i4]; + var _field2 = oldFieldMap[_fieldName2]; + newFieldMap[_fieldName2] = { + description: _field2.description, + deprecationReason: _field2.deprecationReason, + type: extendType(_field2.type), + args: extendArgs(_field2.args), + astNode: _field2.astNode, + resolve: _field2.resolve + }; + } // If there are any extensions to the fields, apply those here. + + + var extensions = typeExtensionsMap[type.name]; + + if (extensions) { + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = extensions[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var extension = _step10.value; + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + for (var _iterator11 = extension.fields[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + var field = _step11.value; + var fieldName = field.name.value; + + if (oldFieldMap[fieldName]) { + throw new GraphQLError("Field \"".concat(type.name, ".").concat(fieldName, "\" already exists in the ") + 'schema. It cannot also be defined in this type extension.', [field]); + } + + newFieldMap[fieldName] = astBuilder.buildField(field); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return newFieldMap; + } + + function extendType(typeDef) { + if (isListType(typeDef)) { + return GraphQLList(extendType(typeDef.ofType)); + } + + if (isNonNullType(typeDef)) { + return GraphQLNonNull(extendType(typeDef.ofType)); + } + + return extendNamedType(typeDef); + } +} + +function checkExtensionNode(type, node) { + switch (node.kind) { + case Kind.OBJECT_TYPE_EXTENSION: + if (!isObjectType(type)) { + throw new GraphQLError("Cannot extend non-object type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.INTERFACE_TYPE_EXTENSION: + if (!isInterfaceType(type)) { + throw new GraphQLError("Cannot extend non-interface type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.ENUM_TYPE_EXTENSION: + if (!isEnumType(type)) { + throw new GraphQLError("Cannot extend non-enum type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.UNION_TYPE_EXTENSION: + if (!isUnionType(type)) { + throw new GraphQLError("Cannot extend non-union type \"".concat(type.name, "\"."), [node]); + } + + break; + + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + if (!isInputObjectType(type)) { + throw new GraphQLError("Cannot extend non-input object type \"".concat(type.name, "\"."), [node]); + } + + break; + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findBreakingChanges.js b/node_modules/graphql/utilities/findBreakingChanges.js new file mode 100644 index 00000000..94f08e4e --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.js @@ -0,0 +1,1245 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; +exports.findRemovedTypes = findRemovedTypes; +exports.findTypesThatChangedKind = findTypesThatChangedKind; +exports.findArgChanges = findArgChanges; +exports.findFieldsThatChangedTypeOnObjectOrInterfaceTypes = findFieldsThatChangedTypeOnObjectOrInterfaceTypes; +exports.findFieldsThatChangedTypeOnInputObjectTypes = findFieldsThatChangedTypeOnInputObjectTypes; +exports.findTypesRemovedFromUnions = findTypesRemovedFromUnions; +exports.findTypesAddedToUnions = findTypesAddedToUnions; +exports.findValuesRemovedFromEnums = findValuesRemovedFromEnums; +exports.findValuesAddedToEnums = findValuesAddedToEnums; +exports.findInterfacesRemovedFromObjectTypes = findInterfacesRemovedFromObjectTypes; +exports.findInterfacesAddedToObjectTypes = findInterfacesAddedToObjectTypes; +exports.findRemovedDirectives = findRemovedDirectives; +exports.findRemovedDirectiveArgs = findRemovedDirectiveArgs; +exports.findAddedNonNullDirectiveArgs = findAddedNonNullDirectiveArgs; +exports.findRemovedLocationsForDirective = findRemovedLocationsForDirective; +exports.findRemovedDirectiveLocations = findRemovedDirectiveLocations; +exports.DangerousChangeType = exports.BreakingChangeType = void 0; + +var _definition = require("../type/definition"); + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2016-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +var BreakingChangeType = { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + ARG_REMOVED: 'ARG_REMOVED', + ARG_CHANGED_KIND: 'ARG_CHANGED_KIND', + REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED', + REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT', + DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED', + DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED', + DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED', + REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED' +}; +exports.BreakingChangeType = BreakingChangeType; +var DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM', + INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT', + TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION', + OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED', + OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED' +}; +exports.DangerousChangeType = DangerousChangeType; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +function findBreakingChanges(oldSchema, newSchema) { + return findRemovedTypes(oldSchema, newSchema).concat(findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema)); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ + + +function findDangerousChanges(oldSchema, newSchema) { + return findArgChanges(oldSchema, newSchema).dangerousChanges.concat(findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges); +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + + +function findRemovedTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr = Object.keys(oldTypeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: "".concat(typeName, " was removed.") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + + +function findTypesThatChangedKind(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr2 = Object.keys(oldTypeMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var typeName = _arr2[_i2]; + + if (!newTypeMap[typeName]) { + continue; + } + + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (oldType.constructor !== newType.constructor) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: "".concat(typeName, " changed from ") + "".concat(typeKindName(oldType), " to ").concat(typeKindName(newType), ".") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ + + +function findArgChanges(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr3 = Object.keys(oldTypeMap); + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var typeName = _arr3[_i3]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFields = oldType.getFields(); + var newTypeFields = newType.getFields(); + + var _arr4 = Object.keys(oldTypeFields); + + for (var _i4 = 0; _i4 < _arr4.length; _i4++) { + var fieldName = _arr4[_i4]; + + if (!newTypeFields[fieldName]) { + continue; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + var _loop = function _loop() { + var oldArgDef = _step.value; + var newArgs = newTypeFields[fieldName].args; + var newArgDef = newArgs.find(function (arg) { + return arg.name === oldArgDef.name; + }); // Arg not present + + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " was removed") + }); + } else { + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type); + + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed type from ") + "".concat(oldArgDef.type.toString(), " to ").concat(newArgDef.type.toString()) + }); + } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed defaultValue") + }); + } + } + }; + + for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + _loop(); + } // Check if arg was added to the field + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + var _loop2 = function _loop2() { + var newArgDef = _step2.value; + var oldArgs = oldTypeFields[fieldName].args; + var oldArgDef = oldArgs.find(function (arg) { + return arg.name === newArgDef.name; + }); + + if (!oldArgDef) { + var argName = newArgDef.name; + + if ((0, _definition.isRequiredArgument)(newArgDef)) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: "A required arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: "An optional arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } + } + }; + + for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return 'a Scalar type'; + } + + if ((0, _definition.isObjectType)(type)) { + return 'an Object type'; + } + + if ((0, _definition.isInterfaceType)(type)) { + return 'an Interface type'; + } + + if ((0, _definition.isUnionType)(type)) { + return 'a Union type'; + } + + if ((0, _definition.isEnumType)(type)) { + return 'an Enum type'; + } + + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } + + throw new TypeError('Unknown type ' + type.constructor.name); +} + +function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr5 = Object.keys(oldTypeMap); + + for (var _i5 = 0; _i5 < _arr5.length; _i5++) { + var typeName = _arr5[_i5]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!((0, _definition.isObjectType)(oldType) || (0, _definition.isInterfaceType)(oldType)) || !((0, _definition.isObjectType)(newType) || (0, _definition.isInterfaceType)(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr6 = Object.keys(oldTypeFieldsDef); + + for (var _i6 = 0; _i6 < _arr6.length; _i6++) { + var fieldName = _arr6[_i6]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForObjectOrInterfaceField(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } + } + + return breakingChanges; +} + +function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr7 = Object.keys(oldTypeMap); + + for (var _i7 = 0; _i7 < _arr7.length; _i7++) { + var typeName = _arr7[_i7]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isInputObjectType)(oldType) || !(0, _definition.isInputObjectType)(newType)) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr8 = Object.keys(oldTypeFieldsDef); + + for (var _i8 = 0; _i8 < _arr8.length; _i8++) { + var fieldName = _arr8[_i8]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = (0, _definition.isNamedType)(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = (0, _definition.isNamedType)(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } // Check if a field was added to the input object type + + + var _arr9 = Object.keys(newTypeFieldsDef); + + for (var _i9 = 0; _i9 < _arr9.length; _i9++) { + var _fieldName = _arr9[_i9]; + + if (!(_fieldName in oldTypeFieldsDef)) { + if ((0, _definition.isRequiredInputField)(newTypeFieldsDef[_fieldName])) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: "A required field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: "An optional field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isNamedType)(oldType)) { + return (// if they're both named types, see if their names are equivalent + (0, _definition.isNamedType)(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if ((0, _definition.isListType)(oldType)) { + return (// if they're both lists, make sure the underlying types are compatible + (0, _definition.isListType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe + (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return (0, _definition.isNonNullType)(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + + return false; +} + +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isNamedType)(oldType)) { + // if they're both named types, see if their names are equivalent + return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; + } else if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return (0, _definition.isListType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } else if ((0, _definition.isNonNullType)(oldType)) { + return (// if they're both non-null, make sure the underlying types are + // compatible + (0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe + !(0, _definition.isNonNullType)(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) + ); + } + + return false; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + + +function findTypesRemovedFromUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesRemovedFromUnion = []; + + var _arr10 = Object.keys(oldTypeMap); + + for (var _i10 = 0; _i10 < _arr10.length; _i10++) { + var typeName = _arr10[_i10]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) { + continue; + } + + var typeNamesInNewUnion = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var type = _step3.value; + typeNamesInNewUnion[type.name] = true; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _type = _step4.value; + + if (!typeNamesInNewUnion[_type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: "".concat(_type.name, " was removed from union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return typesRemovedFromUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ + + +function findTypesAddedToUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesAddedToUnion = []; + + var _arr11 = Object.keys(newTypeMap); + + for (var _i11 = 0; _i11 < _arr11.length; _i11++) { + var typeName = _arr11[_i11]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isUnionType)(oldType) || !(0, _definition.isUnionType)(newType)) { + continue; + } + + var typeNamesInOldUnion = Object.create(null); + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var type = _step5.value; + typeNamesInOldUnion[type.name] = true; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _type2 = _step6.value; + + if (!typeNamesInOldUnion[_type2.name]) { + typesAddedToUnion.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: "".concat(_type2.name, " was added to union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return typesAddedToUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + + +function findValuesRemovedFromEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesRemovedFromEnums = []; + + var _arr12 = Object.keys(oldTypeMap); + + for (var _i12 = 0; _i12 < _arr12.length; _i12++) { + var typeName = _arr12[_i12]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) { + continue; + } + + var valuesInNewEnum = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var value = _step7.value; + valuesInNewEnum[value.name] = true; + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _value = _step8.value; + + if (!valuesInNewEnum[_value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: "".concat(_value.name, " was removed from enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return valuesRemovedFromEnums; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ + + +function findValuesAddedToEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesAddedToEnums = []; + + var _arr13 = Object.keys(oldTypeMap); + + for (var _i13 = 0; _i13 < _arr13.length; _i13++) { + var typeName = _arr13[_i13]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isEnumType)(oldType) || !(0, _definition.isEnumType)(newType)) { + continue; + } + + var valuesInOldEnum = Object.create(null); + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var value = _step9.value; + valuesInOldEnum[value.name] = true; + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var _value2 = _step10.value; + + if (!valuesInOldEnum[_value2.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: "".concat(_value2.name, " was added to enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return valuesAddedToEnums; +} + +function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr14 = Object.keys(oldTypeMap); + + for (var _i14 = 0; _i14 < _arr14.length; _i14++) { + var typeName = _arr14[_i14]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + var _loop3 = function _loop3() { + var oldInterface = _step11.value; + + if (!newInterfaces.some(function (int) { + return int.name === oldInterface.name; + })) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: "".concat(typeName, " no longer implements interface ") + "".concat(oldInterface.name, ".") + }); + } + }; + + for (var _iterator11 = oldInterfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + _loop3(); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + + return breakingChanges; +} + +function findInterfacesAddedToObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var interfacesAddedToObjectTypes = []; + + var _arr15 = Object.keys(newTypeMap); + + for (var _i15 = 0; _i15 < _arr15.length; _i15++) { + var typeName = _arr15[_i15]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(0, _definition.isObjectType)(oldType) || !(0, _definition.isObjectType)(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + var _loop4 = function _loop4() { + var newInterface = _step12.value; + + if (!oldInterfaces.some(function (int) { + return int.name === newInterface.name; + })) { + interfacesAddedToObjectTypes.push({ + type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT, + description: "".concat(newInterface.name, " added to interfaces implemented ") + "by ".concat(typeName, ".") + }); + } + }; + + for (var _iterator12 = newInterfaces[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + _loop4(); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + + return interfacesAddedToObjectTypes; +} + +function findRemovedDirectives(oldSchema, newSchema) { + var removedDirectives = []; + var newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema); + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = oldSchema.getDirectives()[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var directive = _step13.value; + + if (!newSchemaDirectiveMap[directive.name]) { + removedDirectives.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: "".concat(directive.name, " was removed") + }); + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return removedDirectives; +} + +function findRemovedArgsForDirective(oldDirective, newDirective) { + var removedArgs = []; + var newArgMap = getArgumentMapForDirective(newDirective); + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = oldDirective.args[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var arg = _step14.value; + + if (!newArgMap[arg.name]) { + removedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + + return removedArgs; +} + +function findRemovedDirectiveArgs(oldSchema, newSchema) { + var removedDirectiveArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion15 = true; + var _didIteratorError15 = false; + var _iteratorError15 = undefined; + + try { + for (var _iterator15 = newSchema.getDirectives()[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) { + var newDirective = _step15.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion16 = true; + var _didIteratorError16 = false; + var _iteratorError16 = undefined; + + try { + for (var _iterator16 = findRemovedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) { + var arg = _step16.value; + removedDirectiveArgs.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: "".concat(arg.name, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError16 = true; + _iteratorError16 = err; + } finally { + try { + if (!_iteratorNormalCompletion16 && _iterator16.return != null) { + _iterator16.return(); + } + } finally { + if (_didIteratorError16) { + throw _iteratorError16; + } + } + } + } + } catch (err) { + _didIteratorError15 = true; + _iteratorError15 = err; + } finally { + try { + if (!_iteratorNormalCompletion15 && _iterator15.return != null) { + _iterator15.return(); + } + } finally { + if (_didIteratorError15) { + throw _iteratorError15; + } + } + } + + return removedDirectiveArgs; +} + +function findAddedArgsForDirective(oldDirective, newDirective) { + var addedArgs = []; + var oldArgMap = getArgumentMapForDirective(oldDirective); + var _iteratorNormalCompletion17 = true; + var _didIteratorError17 = false; + var _iteratorError17 = undefined; + + try { + for (var _iterator17 = newDirective.args[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) { + var arg = _step17.value; + + if (!oldArgMap[arg.name]) { + addedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError17 = true; + _iteratorError17 = err; + } finally { + try { + if (!_iteratorNormalCompletion17 && _iterator17.return != null) { + _iterator17.return(); + } + } finally { + if (_didIteratorError17) { + throw _iteratorError17; + } + } + } + + return addedArgs; +} + +function findAddedNonNullDirectiveArgs(oldSchema, newSchema) { + var addedNonNullableArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion18 = true; + var _didIteratorError18 = false; + var _iteratorError18 = undefined; + + try { + for (var _iterator18 = newSchema.getDirectives()[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) { + var newDirective = _step18.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion19 = true; + var _didIteratorError19 = false; + var _iteratorError19 = undefined; + + try { + for (var _iterator19 = findAddedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) { + var arg = _step19.value; + + if ((0, _definition.isRequiredArgument)(arg)) { + addedNonNullableArgs.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: "A required arg ".concat(arg.name, " on directive ") + "".concat(newDirective.name, " was added") + }); + } + } + } catch (err) { + _didIteratorError19 = true; + _iteratorError19 = err; + } finally { + try { + if (!_iteratorNormalCompletion19 && _iterator19.return != null) { + _iterator19.return(); + } + } finally { + if (_didIteratorError19) { + throw _iteratorError19; + } + } + } + } + } catch (err) { + _didIteratorError18 = true; + _iteratorError18 = err; + } finally { + try { + if (!_iteratorNormalCompletion18 && _iterator18.return != null) { + _iterator18.return(); + } + } finally { + if (_didIteratorError18) { + throw _iteratorError18; + } + } + } + + return addedNonNullableArgs; +} + +function findRemovedLocationsForDirective(oldDirective, newDirective) { + var removedLocations = []; + var newLocationSet = new Set(newDirective.locations); + var _iteratorNormalCompletion20 = true; + var _didIteratorError20 = false; + var _iteratorError20 = undefined; + + try { + for (var _iterator20 = oldDirective.locations[Symbol.iterator](), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) { + var oldLocation = _step20.value; + + if (!newLocationSet.has(oldLocation)) { + removedLocations.push(oldLocation); + } + } + } catch (err) { + _didIteratorError20 = true; + _iteratorError20 = err; + } finally { + try { + if (!_iteratorNormalCompletion20 && _iterator20.return != null) { + _iterator20.return(); + } + } finally { + if (_didIteratorError20) { + throw _iteratorError20; + } + } + } + + return removedLocations; +} + +function findRemovedDirectiveLocations(oldSchema, newSchema) { + var removedLocations = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion21 = true; + var _didIteratorError21 = false; + var _iteratorError21 = undefined; + + try { + for (var _iterator21 = newSchema.getDirectives()[Symbol.iterator](), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) { + var newDirective = _step21.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion22 = true; + var _didIteratorError22 = false; + var _iteratorError22 = undefined; + + try { + for (var _iterator22 = findRemovedLocationsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) { + var location = _step22.value; + removedLocations.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: "".concat(location, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError22 = true; + _iteratorError22 = err; + } finally { + try { + if (!_iteratorNormalCompletion22 && _iterator22.return != null) { + _iterator22.return(); + } + } finally { + if (_didIteratorError22) { + throw _iteratorError22; + } + } + } + } + } catch (err) { + _didIteratorError21 = true; + _iteratorError21 = err; + } finally { + try { + if (!_iteratorNormalCompletion21 && _iterator21.return != null) { + _iterator21.return(); + } + } finally { + if (_didIteratorError21) { + throw _iteratorError21; + } + } + } + + return removedLocations; +} + +function getDirectiveMapForSchema(schema) { + return (0, _keyMap.default)(schema.getDirectives(), function (dir) { + return dir.name; + }); +} + +function getArgumentMapForDirective(directive) { + return (0, _keyMap.default)(directive.args, function (arg) { + return arg.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findBreakingChanges.js.flow b/node_modules/graphql/utilities/findBreakingChanges.js.flow new file mode 100644 index 00000000..9f796213 --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.js.flow @@ -0,0 +1,853 @@ +/** + * Copyright (c) 2016-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isNonNullType, + isListType, + isNamedType, + isRequiredArgument, + isRequiredInputField, +} from '../type/definition'; + +import type { + GraphQLNamedType, + GraphQLFieldMap, + GraphQLType, + GraphQLArgument, +} from '../type/definition'; + +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +import keyMap from '../jsutils/keyMap'; + +import type { ObjMap } from '../jsutils/ObjMap'; +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +export const BreakingChangeType = { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + ARG_REMOVED: 'ARG_REMOVED', + ARG_CHANGED_KIND: 'ARG_CHANGED_KIND', + REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED', + REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT', + DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED', + DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED', + DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED', + REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED', +}; + +export const DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM', + INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT', + TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION', + OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED', + OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED', +}; + +export type BreakingChange = { + type: $Keys, + description: string, +}; + +export type DangerousChange = { + type: $Keys, + description: string, +}; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +export function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + return [ + ...findRemovedTypes(oldSchema, newSchema), + ...findTypesThatChangedKind(oldSchema, newSchema), + ...findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), + ...findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) + .breakingChanges, + ...findTypesRemovedFromUnions(oldSchema, newSchema), + ...findValuesRemovedFromEnums(oldSchema, newSchema), + ...findArgChanges(oldSchema, newSchema).breakingChanges, + ...findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), + ...findRemovedDirectives(oldSchema, newSchema), + ...findRemovedDirectiveArgs(oldSchema, newSchema), + ...findAddedNonNullDirectiveArgs(oldSchema, newSchema), + ...findRemovedDirectiveLocations(oldSchema, newSchema), + ]; +} + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ +export function findDangerousChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + return [ + ...findArgChanges(oldSchema, newSchema).dangerousChanges, + ...findValuesAddedToEnums(oldSchema, newSchema), + ...findInterfacesAddedToObjectTypes(oldSchema, newSchema), + ...findTypesAddedToUnions(oldSchema, newSchema), + ...findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) + .dangerousChanges, + ]; +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ +export function findRemovedTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: `${typeName} was removed.`, + }); + } + } + return breakingChanges; +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ +export function findTypesThatChangedKind( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + if (!newTypeMap[typeName]) { + continue; + } + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (oldType.constructor !== newType.constructor) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: + `${typeName} changed from ` + + `${typeKindName(oldType)} to ${typeKindName(newType)}.`, + }); + } + } + return breakingChanges; +} + +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ +export function findArgChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): { + breakingChanges: Array, + dangerousChanges: Array, +} { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + const dangerousChanges = []; + + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if ( + !(isObjectType(oldType) || isInterfaceType(oldType)) || + !(isObjectType(newType) || isInterfaceType(newType)) || + newType.constructor !== oldType.constructor + ) { + continue; + } + + const oldTypeFields: GraphQLFieldMap<*, *> = oldType.getFields(); + const newTypeFields: GraphQLFieldMap<*, *> = newType.getFields(); + + for (const fieldName of Object.keys(oldTypeFields)) { + if (!newTypeFields[fieldName]) { + continue; + } + + for (const oldArgDef of oldTypeFields[fieldName].args) { + const newArgs = newTypeFields[fieldName].args; + const newArgDef = newArgs.find(arg => arg.name === oldArgDef.name); + + // Arg not present + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: + `${oldType.name}.${fieldName} arg ` + + `${oldArgDef.name} was removed`, + }); + } else { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldArgDef.type, + newArgDef.type, + ); + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: + `${oldType.name}.${fieldName} arg ` + + `${oldArgDef.name} has changed type from ` + + `${oldArgDef.type.toString()} to ${newArgDef.type.toString()}`, + }); + } else if ( + oldArgDef.defaultValue !== undefined && + oldArgDef.defaultValue !== newArgDef.defaultValue + ) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: + `${oldType.name}.${fieldName} arg ` + + `${oldArgDef.name} has changed defaultValue`, + }); + } + } + } + // Check if arg was added to the field + for (const newArgDef of newTypeFields[fieldName].args) { + const oldArgs = oldTypeFields[fieldName].args; + const oldArgDef = oldArgs.find(arg => arg.name === newArgDef.name); + if (!oldArgDef) { + const argName = newArgDef.name; + if (isRequiredArgument(newArgDef)) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: + `A required arg ${argName} on ` + + `${typeName}.${fieldName} was added`, + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: + `An optional arg ${argName} on ` + + `${typeName}.${fieldName} was added`, + }); + } + } + } + } + } + + return { + breakingChanges, + dangerousChanges, + }; +} + +function typeKindName(type: GraphQLNamedType): string { + if (isScalarType(type)) { + return 'a Scalar type'; + } + if (isObjectType(type)) { + return 'an Object type'; + } + if (isInterfaceType(type)) { + return 'an Interface type'; + } + if (isUnionType(type)) { + return 'a Union type'; + } + if (isEnumType(type)) { + return 'an Enum type'; + } + if (isInputObjectType(type)) { + return 'an Input type'; + } + throw new TypeError('Unknown type ' + type.constructor.name); +} + +export function findFieldsThatChangedTypeOnObjectOrInterfaceTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if ( + !(isObjectType(oldType) || isInterfaceType(oldType)) || + !(isObjectType(newType) || isInterfaceType(newType)) || + newType.constructor !== oldType.constructor + ) { + continue; + } + + const oldTypeFieldsDef = oldType.getFields(); + const newTypeFieldsDef = newType.getFields(); + for (const fieldName of Object.keys(oldTypeFieldsDef)) { + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${typeName}.${fieldName} was removed.`, + }); + } else { + const oldFieldType = oldTypeFieldsDef[fieldName].type; + const newFieldType = newTypeFieldsDef[fieldName].type; + const isSafe = isChangeSafeForObjectOrInterfaceField( + oldFieldType, + newFieldType, + ); + if (!isSafe) { + const oldFieldTypeString = isNamedType(oldFieldType) + ? oldFieldType.name + : oldFieldType.toString(); + const newFieldTypeString = isNamedType(newFieldType) + ? newFieldType.name + : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${typeName}.${fieldName} changed type from ` + + `${oldFieldTypeString} to ${newFieldTypeString}.`, + }); + } + } + } + } + return breakingChanges; +} + +export function findFieldsThatChangedTypeOnInputObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): { + breakingChanges: Array, + dangerousChanges: Array, +} { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const breakingChanges = []; + const dangerousChanges = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isInputObjectType(oldType) || !isInputObjectType(newType)) { + continue; + } + + const oldTypeFieldsDef = oldType.getFields(); + const newTypeFieldsDef = newType.getFields(); + for (const fieldName of Object.keys(oldTypeFieldsDef)) { + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${typeName}.${fieldName} was removed.`, + }); + } else { + const oldFieldType = oldTypeFieldsDef[fieldName].type; + const newFieldType = newTypeFieldsDef[fieldName].type; + + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldFieldType, + newFieldType, + ); + if (!isSafe) { + const oldFieldTypeString = isNamedType(oldFieldType) + ? oldFieldType.name + : oldFieldType.toString(); + const newFieldTypeString = isNamedType(newFieldType) + ? newFieldType.name + : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${typeName}.${fieldName} changed type from ` + + `${oldFieldTypeString} to ${newFieldTypeString}.`, + }); + } + } + } + // Check if a field was added to the input object type + for (const fieldName of Object.keys(newTypeFieldsDef)) { + if (!(fieldName in oldTypeFieldsDef)) { + if (isRequiredInputField(newTypeFieldsDef[fieldName])) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: + `A required field ${fieldName} on ` + + `input type ${typeName} was added.`, + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: + `An optional field ${fieldName} on ` + + `input type ${typeName} was added.`, + }); + } + } + } + } + return { + breakingChanges, + dangerousChanges, + }; +} + +function isChangeSafeForObjectOrInterfaceField( + oldType: GraphQLType, + newType: GraphQLType, +): boolean { + if (isNamedType(oldType)) { + return ( + // if they're both named types, see if their names are equivalent + (isNamedType(newType) && oldType.name === newType.name) || + // moving from nullable to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } else if (isListType(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + (isListType(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType, + )) || + // moving from nullable to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } else if (isNonNullType(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return ( + isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) + ); + } + return false; +} + +function isChangeSafeForInputObjectFieldOrFieldArg( + oldType: GraphQLType, + newType: GraphQLType, +): boolean { + if (isNamedType(oldType)) { + // if they're both named types, see if their names are equivalent + return isNamedType(newType) && oldType.name === newType.name; + } else if (isListType(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return ( + isListType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) + ); + } else if (isNonNullType(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + (isNonNullType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType, + )) || + // moving from non-null to nullable of the same underlying type is safe + (!isNonNullType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)) + ); + } + return false; +} + +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ +export function findTypesRemovedFromUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const typesRemovedFromUnion = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + const typeNamesInNewUnion = Object.create(null); + for (const type of newType.getTypes()) { + typeNamesInNewUnion[type.name] = true; + } + for (const type of oldType.getTypes()) { + if (!typeNamesInNewUnion[type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${type.name} was removed from union type ${typeName}.`, + }); + } + } + } + return typesRemovedFromUnion; +} + +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ +export function findTypesAddedToUnions( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const typesAddedToUnion = []; + for (const typeName of Object.keys(newTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + const typeNamesInOldUnion = Object.create(null); + for (const type of oldType.getTypes()) { + typeNamesInOldUnion[type.name] = true; + } + for (const type of newType.getTypes()) { + if (!typeNamesInOldUnion[type.name]) { + typesAddedToUnion.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${type.name} was added to union type ${typeName}.`, + }); + } + } + } + return typesAddedToUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ +export function findValuesRemovedFromEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const valuesRemovedFromEnums = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + const valuesInNewEnum = Object.create(null); + for (const value of newType.getValues()) { + valuesInNewEnum[value.name] = true; + } + for (const value of oldType.getValues()) { + if (!valuesInNewEnum[value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${value.name} was removed from enum type ${typeName}.`, + }); + } + } + } + return valuesRemovedFromEnums; +} + +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ +export function findValuesAddedToEnums( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + + const valuesAddedToEnums = []; + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + + const valuesInOldEnum = Object.create(null); + for (const value of oldType.getValues()) { + valuesInOldEnum[value.name] = true; + } + for (const value of newType.getValues()) { + if (!valuesInOldEnum[value.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${value.name} was added to enum type ${typeName}.`, + }); + } + } + } + return valuesAddedToEnums; +} + +export function findInterfacesRemovedFromObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + const breakingChanges = []; + + for (const typeName of Object.keys(oldTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + const oldInterfaces = oldType.getInterfaces(); + const newInterfaces = newType.getInterfaces(); + for (const oldInterface of oldInterfaces) { + if (!newInterfaces.some(int => int.name === oldInterface.name)) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: + `${typeName} no longer implements interface ` + + `${oldInterface.name}.`, + }); + } + } + } + return breakingChanges; +} + +export function findInterfacesAddedToObjectTypes( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const oldTypeMap = oldSchema.getTypeMap(); + const newTypeMap = newSchema.getTypeMap(); + const interfacesAddedToObjectTypes = []; + + for (const typeName of Object.keys(newTypeMap)) { + const oldType = oldTypeMap[typeName]; + const newType = newTypeMap[typeName]; + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + const oldInterfaces = oldType.getInterfaces(); + const newInterfaces = newType.getInterfaces(); + for (const newInterface of newInterfaces) { + if (!oldInterfaces.some(int => int.name === newInterface.name)) { + interfacesAddedToObjectTypes.push({ + type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT, + description: + `${newInterface.name} added to interfaces implemented ` + + `by ${typeName}.`, + }); + } + } + } + return interfacesAddedToObjectTypes; +} + +export function findRemovedDirectives( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const removedDirectives = []; + + const newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema); + for (const directive of oldSchema.getDirectives()) { + if (!newSchemaDirectiveMap[directive.name]) { + removedDirectives.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${directive.name} was removed`, + }); + } + } + + return removedDirectives; +} + +function findRemovedArgsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective, +): Array { + const removedArgs = []; + const newArgMap = getArgumentMapForDirective(newDirective); + + for (const arg of oldDirective.args) { + if (!newArgMap[arg.name]) { + removedArgs.push(arg); + } + } + + return removedArgs; +} + +export function findRemovedDirectiveArgs( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const removedDirectiveArgs = []; + const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + + for (const newDirective of newSchema.getDirectives()) { + const oldDirective = oldSchemaDirectiveMap[newDirective.name]; + if (!oldDirective) { + continue; + } + + for (const arg of findRemovedArgsForDirective(oldDirective, newDirective)) { + removedDirectiveArgs.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${arg.name} was removed from ${newDirective.name}`, + }); + } + } + + return removedDirectiveArgs; +} + +function findAddedArgsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective, +): Array { + const addedArgs = []; + const oldArgMap = getArgumentMapForDirective(oldDirective); + + for (const arg of newDirective.args) { + if (!oldArgMap[arg.name]) { + addedArgs.push(arg); + } + } + + return addedArgs; +} + +export function findAddedNonNullDirectiveArgs( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const addedNonNullableArgs = []; + const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + + for (const newDirective of newSchema.getDirectives()) { + const oldDirective = oldSchemaDirectiveMap[newDirective.name]; + if (!oldDirective) { + continue; + } + + for (const arg of findAddedArgsForDirective(oldDirective, newDirective)) { + if (isRequiredArgument(arg)) { + addedNonNullableArgs.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: + `A required arg ${arg.name} on directive ` + + `${newDirective.name} was added`, + }); + } + } + } + + return addedNonNullableArgs; +} + +export function findRemovedLocationsForDirective( + oldDirective: GraphQLDirective, + newDirective: GraphQLDirective, +): Array { + const removedLocations = []; + const newLocationSet = new Set(newDirective.locations); + + for (const oldLocation of oldDirective.locations) { + if (!newLocationSet.has(oldLocation)) { + removedLocations.push(oldLocation); + } + } + + return removedLocations; +} + +export function findRemovedDirectiveLocations( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array { + const removedLocations = []; + const oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + + for (const newDirective of newSchema.getDirectives()) { + const oldDirective = oldSchemaDirectiveMap[newDirective.name]; + if (!oldDirective) { + continue; + } + + for (const location of findRemovedLocationsForDirective( + oldDirective, + newDirective, + )) { + removedLocations.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${newDirective.name}`, + }); + } + } + + return removedLocations; +} + +function getDirectiveMapForSchema( + schema: GraphQLSchema, +): ObjMap { + return keyMap(schema.getDirectives(), dir => dir.name); +} + +function getArgumentMapForDirective( + directive: GraphQLDirective, +): ObjMap { + return keyMap(directive.args, arg => arg.name); +} diff --git a/node_modules/graphql/utilities/findBreakingChanges.mjs b/node_modules/graphql/utilities/findBreakingChanges.mjs new file mode 100644 index 00000000..bec653f2 --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.mjs @@ -0,0 +1,1201 @@ +/** + * Copyright (c) 2016-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, isNonNullType, isListType, isNamedType, isRequiredArgument, isRequiredInputField } from '../type/definition'; +import keyMap from '../jsutils/keyMap'; +export var BreakingChangeType = { + FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', + FIELD_REMOVED: 'FIELD_REMOVED', + TYPE_CHANGED_KIND: 'TYPE_CHANGED_KIND', + TYPE_REMOVED: 'TYPE_REMOVED', + TYPE_REMOVED_FROM_UNION: 'TYPE_REMOVED_FROM_UNION', + VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', + ARG_REMOVED: 'ARG_REMOVED', + ARG_CHANGED_KIND: 'ARG_CHANGED_KIND', + REQUIRED_ARG_ADDED: 'REQUIRED_ARG_ADDED', + REQUIRED_INPUT_FIELD_ADDED: 'REQUIRED_INPUT_FIELD_ADDED', + INTERFACE_REMOVED_FROM_OBJECT: 'INTERFACE_REMOVED_FROM_OBJECT', + DIRECTIVE_REMOVED: 'DIRECTIVE_REMOVED', + DIRECTIVE_ARG_REMOVED: 'DIRECTIVE_ARG_REMOVED', + DIRECTIVE_LOCATION_REMOVED: 'DIRECTIVE_LOCATION_REMOVED', + REQUIRED_DIRECTIVE_ARG_ADDED: 'REQUIRED_DIRECTIVE_ARG_ADDED' +}; +export var DangerousChangeType = { + ARG_DEFAULT_VALUE_CHANGE: 'ARG_DEFAULT_VALUE_CHANGE', + VALUE_ADDED_TO_ENUM: 'VALUE_ADDED_TO_ENUM', + INTERFACE_ADDED_TO_OBJECT: 'INTERFACE_ADDED_TO_OBJECT', + TYPE_ADDED_TO_UNION: 'TYPE_ADDED_TO_UNION', + OPTIONAL_INPUT_FIELD_ADDED: 'OPTIONAL_INPUT_FIELD_ADDED', + OPTIONAL_ARG_ADDED: 'OPTIONAL_ARG_ADDED' +}; + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + */ +export function findBreakingChanges(oldSchema, newSchema) { + return findRemovedTypes(oldSchema, newSchema).concat(findTypesThatChangedKind(oldSchema, newSchema), findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).breakingChanges, findTypesRemovedFromUnions(oldSchema, newSchema), findValuesRemovedFromEnums(oldSchema, newSchema), findArgChanges(oldSchema, newSchema).breakingChanges, findInterfacesRemovedFromObjectTypes(oldSchema, newSchema), findRemovedDirectives(oldSchema, newSchema), findRemovedDirectiveArgs(oldSchema, newSchema), findAddedNonNullDirectiveArgs(oldSchema, newSchema), findRemovedDirectiveLocations(oldSchema, newSchema)); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + */ + +export function findDangerousChanges(oldSchema, newSchema) { + return findArgChanges(oldSchema, newSchema).dangerousChanges.concat(findValuesAddedToEnums(oldSchema, newSchema), findInterfacesAddedToObjectTypes(oldSchema, newSchema), findTypesAddedToUnions(oldSchema, newSchema), findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema).dangerousChanges); +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing an entire type. + */ + +export function findRemovedTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr = Object.keys(oldTypeMap); + + for (var _i = 0; _i < _arr.length; _i++) { + var typeName = _arr[_i]; + + if (!newTypeMap[typeName]) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: "".concat(typeName, " was removed.") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to changing the type of a type. + */ + +export function findTypesThatChangedKind(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr2 = Object.keys(oldTypeMap); + + for (var _i2 = 0; _i2 < _arr2.length; _i2++) { + var typeName = _arr2[_i2]; + + if (!newTypeMap[typeName]) { + continue; + } + + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (oldType.constructor !== newType.constructor) { + breakingChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: "".concat(typeName, " changed from ") + "".concat(typeKindName(oldType), " to ").concat(typeKindName(newType), ".") + }); + } + } + + return breakingChanges; +} +/** + * Given two schemas, returns an Array containing descriptions of any + * breaking or dangerous changes in the newSchema related to arguments + * (such as removal or change of type of an argument, or a change in an + * argument's default value). + */ + +export function findArgChanges(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr3 = Object.keys(oldTypeMap); + + for (var _i3 = 0; _i3 < _arr3.length; _i3++) { + var typeName = _arr3[_i3]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(isObjectType(oldType) || isInterfaceType(oldType)) || !(isObjectType(newType) || isInterfaceType(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFields = oldType.getFields(); + var newTypeFields = newType.getFields(); + + var _arr4 = Object.keys(oldTypeFields); + + for (var _i4 = 0; _i4 < _arr4.length; _i4++) { + var fieldName = _arr4[_i4]; + + if (!newTypeFields[fieldName]) { + continue; + } + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + var _loop = function _loop() { + var oldArgDef = _step.value; + var newArgs = newTypeFields[fieldName].args; + var newArgDef = newArgs.find(function (arg) { + return arg.name === oldArgDef.name; + }); // Arg not present + + if (!newArgDef) { + breakingChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " was removed") + }); + } else { + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldArgDef.type, newArgDef.type); + + if (!isSafe) { + breakingChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed type from ") + "".concat(oldArgDef.type.toString(), " to ").concat(newArgDef.type.toString()) + }); + } else if (oldArgDef.defaultValue !== undefined && oldArgDef.defaultValue !== newArgDef.defaultValue) { + dangerousChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: "".concat(oldType.name, ".").concat(fieldName, " arg ") + "".concat(oldArgDef.name, " has changed defaultValue") + }); + } + } + }; + + for (var _iterator = oldTypeFields[fieldName].args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + _loop(); + } // Check if arg was added to the field + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + var _loop2 = function _loop2() { + var newArgDef = _step2.value; + var oldArgs = oldTypeFields[fieldName].args; + var oldArgDef = oldArgs.find(function (arg) { + return arg.name === newArgDef.name; + }); + + if (!oldArgDef) { + var argName = newArgDef.name; + + if (isRequiredArgument(newArgDef)) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: "A required arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: "An optional arg ".concat(argName, " on ") + "".concat(typeName, ".").concat(fieldName, " was added") + }); + } + } + }; + + for (var _iterator2 = newTypeFields[fieldName].args[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + _loop2(); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function typeKindName(type) { + if (isScalarType(type)) { + return 'a Scalar type'; + } + + if (isObjectType(type)) { + return 'an Object type'; + } + + if (isInterfaceType(type)) { + return 'an Interface type'; + } + + if (isUnionType(type)) { + return 'a Union type'; + } + + if (isEnumType(type)) { + return 'an Enum type'; + } + + if (isInputObjectType(type)) { + return 'an Input type'; + } + + throw new TypeError('Unknown type ' + type.constructor.name); +} + +export function findFieldsThatChangedTypeOnObjectOrInterfaceTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr5 = Object.keys(oldTypeMap); + + for (var _i5 = 0; _i5 < _arr5.length; _i5++) { + var typeName = _arr5[_i5]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!(isObjectType(oldType) || isInterfaceType(oldType)) || !(isObjectType(newType) || isInterfaceType(newType)) || newType.constructor !== oldType.constructor) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr6 = Object.keys(oldTypeFieldsDef); + + for (var _i6 = 0; _i6 < _arr6.length; _i6++) { + var fieldName = _arr6[_i6]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForObjectOrInterfaceField(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = isNamedType(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = isNamedType(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } + } + + return breakingChanges; +} +export function findFieldsThatChangedTypeOnInputObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + var dangerousChanges = []; + + var _arr7 = Object.keys(oldTypeMap); + + for (var _i7 = 0; _i7 < _arr7.length; _i7++) { + var typeName = _arr7[_i7]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isInputObjectType(oldType) || !isInputObjectType(newType)) { + continue; + } + + var oldTypeFieldsDef = oldType.getFields(); + var newTypeFieldsDef = newType.getFields(); + + var _arr8 = Object.keys(oldTypeFieldsDef); + + for (var _i8 = 0; _i8 < _arr8.length; _i8++) { + var fieldName = _arr8[_i8]; + + // Check if the field is missing on the type in the new schema. + if (!(fieldName in newTypeFieldsDef)) { + breakingChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: "".concat(typeName, ".").concat(fieldName, " was removed.") + }); + } else { + var oldFieldType = oldTypeFieldsDef[fieldName].type; + var newFieldType = newTypeFieldsDef[fieldName].type; + var isSafe = isChangeSafeForInputObjectFieldOrFieldArg(oldFieldType, newFieldType); + + if (!isSafe) { + var oldFieldTypeString = isNamedType(oldFieldType) ? oldFieldType.name : oldFieldType.toString(); + var newFieldTypeString = isNamedType(newFieldType) ? newFieldType.name : newFieldType.toString(); + breakingChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: "".concat(typeName, ".").concat(fieldName, " changed type from ") + "".concat(oldFieldTypeString, " to ").concat(newFieldTypeString, ".") + }); + } + } + } // Check if a field was added to the input object type + + + var _arr9 = Object.keys(newTypeFieldsDef); + + for (var _i9 = 0; _i9 < _arr9.length; _i9++) { + var _fieldName = _arr9[_i9]; + + if (!(_fieldName in oldTypeFieldsDef)) { + if (isRequiredInputField(newTypeFieldsDef[_fieldName])) { + breakingChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: "A required field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } else { + dangerousChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: "An optional field ".concat(_fieldName, " on ") + "input type ".concat(typeName, " was added.") + }); + } + } + } + } + + return { + breakingChanges: breakingChanges, + dangerousChanges: dangerousChanges + }; +} + +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if (isNamedType(oldType)) { + return (// if they're both named types, see if their names are equivalent + isNamedType(newType) && oldType.name === newType.name || // moving from nullable to non-null of the same underlying type is safe + isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if (isListType(oldType)) { + return (// if they're both lists, make sure the underlying types are compatible + isListType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) || // moving from nullable to non-null of the same underlying type is safe + isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType) + ); + } else if (isNonNullType(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return isNonNullType(newType) && isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType); + } + + return false; +} + +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if (isNamedType(oldType)) { + // if they're both named types, see if their names are equivalent + return isNamedType(newType) && oldType.name === newType.name; + } else if (isListType(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return isListType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType); + } else if (isNonNullType(oldType)) { + return (// if they're both non-null, make sure the underlying types are + // compatible + isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) || // moving from non-null to nullable of the same underlying type is safe + !isNonNullType(newType) && isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType) + ); + } + + return false; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing types from a union type. + */ + + +export function findTypesRemovedFromUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesRemovedFromUnion = []; + + var _arr10 = Object.keys(oldTypeMap); + + for (var _i10 = 0; _i10 < _arr10.length; _i10++) { + var typeName = _arr10[_i10]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + + var typeNamesInNewUnion = Object.create(null); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = newType.getTypes()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var type = _step3.value; + typeNamesInNewUnion[type.name] = true; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = oldType.getTypes()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var _type = _step4.value; + + if (!typeNamesInNewUnion[_type.name]) { + typesRemovedFromUnion.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: "".concat(_type.name, " was removed from union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + } + + return typesRemovedFromUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding types to a union type. + */ + +export function findTypesAddedToUnions(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var typesAddedToUnion = []; + + var _arr11 = Object.keys(newTypeMap); + + for (var _i11 = 0; _i11 < _arr11.length; _i11++) { + var typeName = _arr11[_i11]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isUnionType(oldType) || !isUnionType(newType)) { + continue; + } + + var typeNamesInOldUnion = Object.create(null); + var _iteratorNormalCompletion5 = true; + var _didIteratorError5 = false; + var _iteratorError5 = undefined; + + try { + for (var _iterator5 = oldType.getTypes()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { + var type = _step5.value; + typeNamesInOldUnion[type.name] = true; + } + } catch (err) { + _didIteratorError5 = true; + _iteratorError5 = err; + } finally { + try { + if (!_iteratorNormalCompletion5 && _iterator5.return != null) { + _iterator5.return(); + } + } finally { + if (_didIteratorError5) { + throw _iteratorError5; + } + } + } + + var _iteratorNormalCompletion6 = true; + var _didIteratorError6 = false; + var _iteratorError6 = undefined; + + try { + for (var _iterator6 = newType.getTypes()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { + var _type2 = _step6.value; + + if (!typeNamesInOldUnion[_type2.name]) { + typesAddedToUnion.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: "".concat(_type2.name, " was added to union type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError6 = true; + _iteratorError6 = err; + } finally { + try { + if (!_iteratorNormalCompletion6 && _iterator6.return != null) { + _iterator6.return(); + } + } finally { + if (_didIteratorError6) { + throw _iteratorError6; + } + } + } + } + + return typesAddedToUnion; +} +/** + * Given two schemas, returns an Array containing descriptions of any breaking + * changes in the newSchema related to removing values from an enum type. + */ + +export function findValuesRemovedFromEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesRemovedFromEnums = []; + + var _arr12 = Object.keys(oldTypeMap); + + for (var _i12 = 0; _i12 < _arr12.length; _i12++) { + var typeName = _arr12[_i12]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + + var valuesInNewEnum = Object.create(null); + var _iteratorNormalCompletion7 = true; + var _didIteratorError7 = false; + var _iteratorError7 = undefined; + + try { + for (var _iterator7 = newType.getValues()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { + var value = _step7.value; + valuesInNewEnum[value.name] = true; + } + } catch (err) { + _didIteratorError7 = true; + _iteratorError7 = err; + } finally { + try { + if (!_iteratorNormalCompletion7 && _iterator7.return != null) { + _iterator7.return(); + } + } finally { + if (_didIteratorError7) { + throw _iteratorError7; + } + } + } + + var _iteratorNormalCompletion8 = true; + var _didIteratorError8 = false; + var _iteratorError8 = undefined; + + try { + for (var _iterator8 = oldType.getValues()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { + var _value = _step8.value; + + if (!valuesInNewEnum[_value.name]) { + valuesRemovedFromEnums.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: "".concat(_value.name, " was removed from enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError8 = true; + _iteratorError8 = err; + } finally { + try { + if (!_iteratorNormalCompletion8 && _iterator8.return != null) { + _iterator8.return(); + } + } finally { + if (_didIteratorError8) { + throw _iteratorError8; + } + } + } + } + + return valuesRemovedFromEnums; +} +/** + * Given two schemas, returns an Array containing descriptions of any dangerous + * changes in the newSchema related to adding values to an enum type. + */ + +export function findValuesAddedToEnums(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var valuesAddedToEnums = []; + + var _arr13 = Object.keys(oldTypeMap); + + for (var _i13 = 0; _i13 < _arr13.length; _i13++) { + var typeName = _arr13[_i13]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isEnumType(oldType) || !isEnumType(newType)) { + continue; + } + + var valuesInOldEnum = Object.create(null); + var _iteratorNormalCompletion9 = true; + var _didIteratorError9 = false; + var _iteratorError9 = undefined; + + try { + for (var _iterator9 = oldType.getValues()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { + var value = _step9.value; + valuesInOldEnum[value.name] = true; + } + } catch (err) { + _didIteratorError9 = true; + _iteratorError9 = err; + } finally { + try { + if (!_iteratorNormalCompletion9 && _iterator9.return != null) { + _iterator9.return(); + } + } finally { + if (_didIteratorError9) { + throw _iteratorError9; + } + } + } + + var _iteratorNormalCompletion10 = true; + var _didIteratorError10 = false; + var _iteratorError10 = undefined; + + try { + for (var _iterator10 = newType.getValues()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { + var _value2 = _step10.value; + + if (!valuesInOldEnum[_value2.name]) { + valuesAddedToEnums.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: "".concat(_value2.name, " was added to enum type ").concat(typeName, ".") + }); + } + } + } catch (err) { + _didIteratorError10 = true; + _iteratorError10 = err; + } finally { + try { + if (!_iteratorNormalCompletion10 && _iterator10.return != null) { + _iterator10.return(); + } + } finally { + if (_didIteratorError10) { + throw _iteratorError10; + } + } + } + } + + return valuesAddedToEnums; +} +export function findInterfacesRemovedFromObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var breakingChanges = []; + + var _arr14 = Object.keys(oldTypeMap); + + for (var _i14 = 0; _i14 < _arr14.length; _i14++) { + var typeName = _arr14[_i14]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion11 = true; + var _didIteratorError11 = false; + var _iteratorError11 = undefined; + + try { + var _loop3 = function _loop3() { + var oldInterface = _step11.value; + + if (!newInterfaces.some(function (int) { + return int.name === oldInterface.name; + })) { + breakingChanges.push({ + type: BreakingChangeType.INTERFACE_REMOVED_FROM_OBJECT, + description: "".concat(typeName, " no longer implements interface ") + "".concat(oldInterface.name, ".") + }); + } + }; + + for (var _iterator11 = oldInterfaces[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) { + _loop3(); + } + } catch (err) { + _didIteratorError11 = true; + _iteratorError11 = err; + } finally { + try { + if (!_iteratorNormalCompletion11 && _iterator11.return != null) { + _iterator11.return(); + } + } finally { + if (_didIteratorError11) { + throw _iteratorError11; + } + } + } + } + + return breakingChanges; +} +export function findInterfacesAddedToObjectTypes(oldSchema, newSchema) { + var oldTypeMap = oldSchema.getTypeMap(); + var newTypeMap = newSchema.getTypeMap(); + var interfacesAddedToObjectTypes = []; + + var _arr15 = Object.keys(newTypeMap); + + for (var _i15 = 0; _i15 < _arr15.length; _i15++) { + var typeName = _arr15[_i15]; + var oldType = oldTypeMap[typeName]; + var newType = newTypeMap[typeName]; + + if (!isObjectType(oldType) || !isObjectType(newType)) { + continue; + } + + var oldInterfaces = oldType.getInterfaces(); + var newInterfaces = newType.getInterfaces(); + var _iteratorNormalCompletion12 = true; + var _didIteratorError12 = false; + var _iteratorError12 = undefined; + + try { + var _loop4 = function _loop4() { + var newInterface = _step12.value; + + if (!oldInterfaces.some(function (int) { + return int.name === newInterface.name; + })) { + interfacesAddedToObjectTypes.push({ + type: DangerousChangeType.INTERFACE_ADDED_TO_OBJECT, + description: "".concat(newInterface.name, " added to interfaces implemented ") + "by ".concat(typeName, ".") + }); + } + }; + + for (var _iterator12 = newInterfaces[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) { + _loop4(); + } + } catch (err) { + _didIteratorError12 = true; + _iteratorError12 = err; + } finally { + try { + if (!_iteratorNormalCompletion12 && _iterator12.return != null) { + _iterator12.return(); + } + } finally { + if (_didIteratorError12) { + throw _iteratorError12; + } + } + } + } + + return interfacesAddedToObjectTypes; +} +export function findRemovedDirectives(oldSchema, newSchema) { + var removedDirectives = []; + var newSchemaDirectiveMap = getDirectiveMapForSchema(newSchema); + var _iteratorNormalCompletion13 = true; + var _didIteratorError13 = false; + var _iteratorError13 = undefined; + + try { + for (var _iterator13 = oldSchema.getDirectives()[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) { + var directive = _step13.value; + + if (!newSchemaDirectiveMap[directive.name]) { + removedDirectives.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: "".concat(directive.name, " was removed") + }); + } + } + } catch (err) { + _didIteratorError13 = true; + _iteratorError13 = err; + } finally { + try { + if (!_iteratorNormalCompletion13 && _iterator13.return != null) { + _iterator13.return(); + } + } finally { + if (_didIteratorError13) { + throw _iteratorError13; + } + } + } + + return removedDirectives; +} + +function findRemovedArgsForDirective(oldDirective, newDirective) { + var removedArgs = []; + var newArgMap = getArgumentMapForDirective(newDirective); + var _iteratorNormalCompletion14 = true; + var _didIteratorError14 = false; + var _iteratorError14 = undefined; + + try { + for (var _iterator14 = oldDirective.args[Symbol.iterator](), _step14; !(_iteratorNormalCompletion14 = (_step14 = _iterator14.next()).done); _iteratorNormalCompletion14 = true) { + var arg = _step14.value; + + if (!newArgMap[arg.name]) { + removedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError14 = true; + _iteratorError14 = err; + } finally { + try { + if (!_iteratorNormalCompletion14 && _iterator14.return != null) { + _iterator14.return(); + } + } finally { + if (_didIteratorError14) { + throw _iteratorError14; + } + } + } + + return removedArgs; +} + +export function findRemovedDirectiveArgs(oldSchema, newSchema) { + var removedDirectiveArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion15 = true; + var _didIteratorError15 = false; + var _iteratorError15 = undefined; + + try { + for (var _iterator15 = newSchema.getDirectives()[Symbol.iterator](), _step15; !(_iteratorNormalCompletion15 = (_step15 = _iterator15.next()).done); _iteratorNormalCompletion15 = true) { + var newDirective = _step15.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion16 = true; + var _didIteratorError16 = false; + var _iteratorError16 = undefined; + + try { + for (var _iterator16 = findRemovedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step16; !(_iteratorNormalCompletion16 = (_step16 = _iterator16.next()).done); _iteratorNormalCompletion16 = true) { + var arg = _step16.value; + removedDirectiveArgs.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: "".concat(arg.name, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError16 = true; + _iteratorError16 = err; + } finally { + try { + if (!_iteratorNormalCompletion16 && _iterator16.return != null) { + _iterator16.return(); + } + } finally { + if (_didIteratorError16) { + throw _iteratorError16; + } + } + } + } + } catch (err) { + _didIteratorError15 = true; + _iteratorError15 = err; + } finally { + try { + if (!_iteratorNormalCompletion15 && _iterator15.return != null) { + _iterator15.return(); + } + } finally { + if (_didIteratorError15) { + throw _iteratorError15; + } + } + } + + return removedDirectiveArgs; +} + +function findAddedArgsForDirective(oldDirective, newDirective) { + var addedArgs = []; + var oldArgMap = getArgumentMapForDirective(oldDirective); + var _iteratorNormalCompletion17 = true; + var _didIteratorError17 = false; + var _iteratorError17 = undefined; + + try { + for (var _iterator17 = newDirective.args[Symbol.iterator](), _step17; !(_iteratorNormalCompletion17 = (_step17 = _iterator17.next()).done); _iteratorNormalCompletion17 = true) { + var arg = _step17.value; + + if (!oldArgMap[arg.name]) { + addedArgs.push(arg); + } + } + } catch (err) { + _didIteratorError17 = true; + _iteratorError17 = err; + } finally { + try { + if (!_iteratorNormalCompletion17 && _iterator17.return != null) { + _iterator17.return(); + } + } finally { + if (_didIteratorError17) { + throw _iteratorError17; + } + } + } + + return addedArgs; +} + +export function findAddedNonNullDirectiveArgs(oldSchema, newSchema) { + var addedNonNullableArgs = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion18 = true; + var _didIteratorError18 = false; + var _iteratorError18 = undefined; + + try { + for (var _iterator18 = newSchema.getDirectives()[Symbol.iterator](), _step18; !(_iteratorNormalCompletion18 = (_step18 = _iterator18.next()).done); _iteratorNormalCompletion18 = true) { + var newDirective = _step18.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion19 = true; + var _didIteratorError19 = false; + var _iteratorError19 = undefined; + + try { + for (var _iterator19 = findAddedArgsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step19; !(_iteratorNormalCompletion19 = (_step19 = _iterator19.next()).done); _iteratorNormalCompletion19 = true) { + var arg = _step19.value; + + if (isRequiredArgument(arg)) { + addedNonNullableArgs.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: "A required arg ".concat(arg.name, " on directive ") + "".concat(newDirective.name, " was added") + }); + } + } + } catch (err) { + _didIteratorError19 = true; + _iteratorError19 = err; + } finally { + try { + if (!_iteratorNormalCompletion19 && _iterator19.return != null) { + _iterator19.return(); + } + } finally { + if (_didIteratorError19) { + throw _iteratorError19; + } + } + } + } + } catch (err) { + _didIteratorError18 = true; + _iteratorError18 = err; + } finally { + try { + if (!_iteratorNormalCompletion18 && _iterator18.return != null) { + _iterator18.return(); + } + } finally { + if (_didIteratorError18) { + throw _iteratorError18; + } + } + } + + return addedNonNullableArgs; +} +export function findRemovedLocationsForDirective(oldDirective, newDirective) { + var removedLocations = []; + var newLocationSet = new Set(newDirective.locations); + var _iteratorNormalCompletion20 = true; + var _didIteratorError20 = false; + var _iteratorError20 = undefined; + + try { + for (var _iterator20 = oldDirective.locations[Symbol.iterator](), _step20; !(_iteratorNormalCompletion20 = (_step20 = _iterator20.next()).done); _iteratorNormalCompletion20 = true) { + var oldLocation = _step20.value; + + if (!newLocationSet.has(oldLocation)) { + removedLocations.push(oldLocation); + } + } + } catch (err) { + _didIteratorError20 = true; + _iteratorError20 = err; + } finally { + try { + if (!_iteratorNormalCompletion20 && _iterator20.return != null) { + _iterator20.return(); + } + } finally { + if (_didIteratorError20) { + throw _iteratorError20; + } + } + } + + return removedLocations; +} +export function findRemovedDirectiveLocations(oldSchema, newSchema) { + var removedLocations = []; + var oldSchemaDirectiveMap = getDirectiveMapForSchema(oldSchema); + var _iteratorNormalCompletion21 = true; + var _didIteratorError21 = false; + var _iteratorError21 = undefined; + + try { + for (var _iterator21 = newSchema.getDirectives()[Symbol.iterator](), _step21; !(_iteratorNormalCompletion21 = (_step21 = _iterator21.next()).done); _iteratorNormalCompletion21 = true) { + var newDirective = _step21.value; + var oldDirective = oldSchemaDirectiveMap[newDirective.name]; + + if (!oldDirective) { + continue; + } + + var _iteratorNormalCompletion22 = true; + var _didIteratorError22 = false; + var _iteratorError22 = undefined; + + try { + for (var _iterator22 = findRemovedLocationsForDirective(oldDirective, newDirective)[Symbol.iterator](), _step22; !(_iteratorNormalCompletion22 = (_step22 = _iterator22.next()).done); _iteratorNormalCompletion22 = true) { + var location = _step22.value; + removedLocations.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: "".concat(location, " was removed from ").concat(newDirective.name) + }); + } + } catch (err) { + _didIteratorError22 = true; + _iteratorError22 = err; + } finally { + try { + if (!_iteratorNormalCompletion22 && _iterator22.return != null) { + _iterator22.return(); + } + } finally { + if (_didIteratorError22) { + throw _iteratorError22; + } + } + } + } + } catch (err) { + _didIteratorError21 = true; + _iteratorError21 = err; + } finally { + try { + if (!_iteratorNormalCompletion21 && _iterator21.return != null) { + _iterator21.return(); + } + } finally { + if (_didIteratorError21) { + throw _iteratorError21; + } + } + } + + return removedLocations; +} + +function getDirectiveMapForSchema(schema) { + return keyMap(schema.getDirectives(), function (dir) { + return dir.name; + }); +} + +function getArgumentMapForDirective(directive) { + return keyMap(directive.args, function (arg) { + return arg.name; + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findDeprecatedUsages.js b/node_modules/graphql/utilities/findDeprecatedUsages.js new file mode 100644 index 00000000..4906b580 --- /dev/null +++ b/node_modules/graphql/utilities/findDeprecatedUsages.js @@ -0,0 +1,60 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findDeprecatedUsages = findDeprecatedUsages; + +var _GraphQLError = require("../error/GraphQLError"); + +var _visitor = require("../language/visitor"); + +var _definition = require("../type/definition"); + +var _TypeInfo = require("./TypeInfo"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ +function findDeprecatedUsages(schema, ast) { + var errors = []; + var typeInfo = new _TypeInfo.TypeInfo(schema); + (0, _visitor.visit)(ast, (0, _visitor.visitWithTypeInfo)(typeInfo, { + Field: function Field(node) { + var fieldDef = typeInfo.getFieldDef(); + + if (fieldDef && fieldDef.isDeprecated) { + var parentType = typeInfo.getParentType(); + + if (parentType) { + var reason = fieldDef.deprecationReason; + errors.push(new _GraphQLError.GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + }, + EnumValue: function EnumValue(node) { + var enumVal = typeInfo.getEnumValue(); + + if (enumVal && enumVal.isDeprecated) { + var type = (0, _definition.getNamedType)(typeInfo.getInputType()); + + if (type) { + var reason = enumVal.deprecationReason; + errors.push(new _GraphQLError.GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + } + })); + return errors; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/findDeprecatedUsages.js.flow b/node_modules/graphql/utilities/findDeprecatedUsages.js.flow new file mode 100644 index 00000000..d2ad48e3 --- /dev/null +++ b/node_modules/graphql/utilities/findDeprecatedUsages.js.flow @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import type { DocumentNode } from '../language/ast'; +import { getNamedType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +import { TypeInfo } from './TypeInfo'; + +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ +export function findDeprecatedUsages( + schema: GraphQLSchema, + ast: DocumentNode, +): Array { + const errors = []; + const typeInfo = new TypeInfo(schema); + + visit( + ast, + visitWithTypeInfo(typeInfo, { + Field(node) { + const fieldDef = typeInfo.getFieldDef(); + if (fieldDef && fieldDef.isDeprecated) { + const parentType = typeInfo.getParentType(); + if (parentType) { + const reason = fieldDef.deprecationReason; + errors.push( + new GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated.` + + (reason ? ' ' + reason : ''), + [node], + ), + ); + } + } + }, + EnumValue(node) { + const enumVal = typeInfo.getEnumValue(); + if (enumVal && enumVal.isDeprecated) { + const type = getNamedType(typeInfo.getInputType()); + if (type) { + const reason = enumVal.deprecationReason; + errors.push( + new GraphQLError( + `The enum value ${type.name}.${enumVal.name} is deprecated.` + + (reason ? ' ' + reason : ''), + [node], + ), + ); + } + } + }, + }), + ); + + return errors; +} diff --git a/node_modules/graphql/utilities/findDeprecatedUsages.mjs b/node_modules/graphql/utilities/findDeprecatedUsages.mjs new file mode 100644 index 00000000..9330d0d1 --- /dev/null +++ b/node_modules/graphql/utilities/findDeprecatedUsages.mjs @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { getNamedType } from '../type/definition'; +import { TypeInfo } from './TypeInfo'; +/** + * A validation rule which reports deprecated usages. + * + * Returns a list of GraphQLError instances describing each deprecated use. + */ + +export function findDeprecatedUsages(schema, ast) { + var errors = []; + var typeInfo = new TypeInfo(schema); + visit(ast, visitWithTypeInfo(typeInfo, { + Field: function Field(node) { + var fieldDef = typeInfo.getFieldDef(); + + if (fieldDef && fieldDef.isDeprecated) { + var parentType = typeInfo.getParentType(); + + if (parentType) { + var reason = fieldDef.deprecationReason; + errors.push(new GraphQLError("The field ".concat(parentType.name, ".").concat(fieldDef.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + }, + EnumValue: function EnumValue(node) { + var enumVal = typeInfo.getEnumValue(); + + if (enumVal && enumVal.isDeprecated) { + var type = getNamedType(typeInfo.getInputType()); + + if (type) { + var reason = enumVal.deprecationReason; + errors.push(new GraphQLError("The enum value ".concat(type.name, ".").concat(enumVal.name, " is deprecated.") + (reason ? ' ' + reason : ''), [node])); + } + } + } + })); + return errors; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationAST.js b/node_modules/graphql/utilities/getOperationAST.js new file mode 100644 index 00000000..c3f1c494 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getOperationAST = getOperationAST; + +var _kinds = require("../language/kinds"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +function getOperationAST(documentAST, operationName) { + var operation = null; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var definition = documentAST.definitions[i]; + + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + if (!operationName) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if (definition.name && definition.name.value === operationName) { + return definition; + } + } + } + + return operation; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationAST.js.flow b/node_modules/graphql/utilities/getOperationAST.js.flow new file mode 100644 index 00000000..b4e491a7 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.js.flow @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { Kind } from '../language/kinds'; +import type { DocumentNode, OperationDefinitionNode } from '../language/ast'; + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +export function getOperationAST( + documentAST: DocumentNode, + operationName: ?string, +): ?OperationDefinitionNode { + let operation = null; + for (let i = 0; i < documentAST.definitions.length; i++) { + const definition = documentAST.definitions[i]; + if (definition.kind === Kind.OPERATION_DEFINITION) { + if (!operationName) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + operation = definition; + } else if (definition.name && definition.name.value === operationName) { + return definition; + } + } + } + return operation; +} diff --git a/node_modules/graphql/utilities/getOperationAST.mjs b/node_modules/graphql/utilities/getOperationAST.mjs new file mode 100644 index 00000000..d26da103 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.mjs @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from '../language/kinds'; + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + */ +export function getOperationAST(documentAST, operationName) { + var operation = null; + + for (var i = 0; i < documentAST.definitions.length; i++) { + var definition = documentAST.definitions[i]; + + if (definition.kind === Kind.OPERATION_DEFINITION) { + if (!operationName) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if (definition.name && definition.name.value === operationName) { + return definition; + } + } + } + + return operation; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationRootType.js b/node_modules/graphql/utilities/getOperationRootType.js new file mode 100644 index 00000000..dc37be76 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.js @@ -0,0 +1,54 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getOperationRootType = getOperationRootType; + +var _GraphQLError = require("../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Extracts the root type of the operation from the schema. + */ +function getOperationRootType(schema, operation) { + switch (operation.operation) { + case 'query': + var queryType = schema.getQueryType(); + + if (!queryType) { + throw new _GraphQLError.GraphQLError('Schema does not define the required query root type.', [operation]); + } + + return queryType; + + case 'mutation': + var mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for mutations.', [operation]); + } + + return mutationType; + + case 'subscription': + var subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError('Schema is not configured for subscriptions.', [operation]); + } + + return subscriptionType; + + default: + throw new _GraphQLError.GraphQLError('Can only have query, mutation and subscription operations.', [operation]); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/getOperationRootType.js.flow b/node_modules/graphql/utilities/getOperationRootType.js.flow new file mode 100644 index 00000000..ddc6e99e --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.js.flow @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { GraphQLError } from '../error/GraphQLError'; +import type { + OperationDefinitionNode, + OperationTypeDefinitionNode, +} from '../language/ast'; +import type { GraphQLSchema } from '../type/schema'; +import type { GraphQLObjectType } from '../type/definition'; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode, +): GraphQLObjectType { + switch (operation.operation) { + case 'query': + const queryType = schema.getQueryType(); + if (!queryType) { + throw new GraphQLError( + 'Schema does not define the required query root type.', + [operation], + ); + } + return queryType; + case 'mutation': + const mutationType = schema.getMutationType(); + if (!mutationType) { + throw new GraphQLError('Schema is not configured for mutations.', [ + operation, + ]); + } + return mutationType; + case 'subscription': + const subscriptionType = schema.getSubscriptionType(); + if (!subscriptionType) { + throw new GraphQLError('Schema is not configured for subscriptions.', [ + operation, + ]); + } + return subscriptionType; + default: + throw new GraphQLError( + 'Can only have query, mutation and subscription operations.', + [operation], + ); + } +} diff --git a/node_modules/graphql/utilities/getOperationRootType.mjs b/node_modules/graphql/utilities/getOperationRootType.mjs new file mode 100644 index 00000000..69a9fe3c --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.mjs @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../error/GraphQLError'; + +/** + * Extracts the root type of the operation from the schema. + */ +export function getOperationRootType(schema, operation) { + switch (operation.operation) { + case 'query': + var queryType = schema.getQueryType(); + + if (!queryType) { + throw new GraphQLError('Schema does not define the required query root type.', [operation]); + } + + return queryType; + + case 'mutation': + var mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new GraphQLError('Schema is not configured for mutations.', [operation]); + } + + return mutationType; + + case 'subscription': + var subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new GraphQLError('Schema is not configured for subscriptions.', [operation]); + } + + return subscriptionType; + + default: + throw new GraphQLError('Can only have query, mutation and subscription operations.', [operation]); + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/index.js b/node_modules/graphql/utilities/index.js new file mode 100644 index 00000000..938e66ea --- /dev/null +++ b/node_modules/graphql/utilities/index.js @@ -0,0 +1,255 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "getIntrospectionQuery", { + enumerable: true, + get: function get() { + return _introspectionQuery.getIntrospectionQuery; + } +}); +Object.defineProperty(exports, "introspectionQuery", { + enumerable: true, + get: function get() { + return _introspectionQuery.introspectionQuery; + } +}); +Object.defineProperty(exports, "getOperationAST", { + enumerable: true, + get: function get() { + return _getOperationAST.getOperationAST; + } +}); +Object.defineProperty(exports, "getOperationRootType", { + enumerable: true, + get: function get() { + return _getOperationRootType.getOperationRootType; + } +}); +Object.defineProperty(exports, "introspectionFromSchema", { + enumerable: true, + get: function get() { + return _introspectionFromSchema.introspectionFromSchema; + } +}); +Object.defineProperty(exports, "buildClientSchema", { + enumerable: true, + get: function get() { + return _buildClientSchema.buildClientSchema; + } +}); +Object.defineProperty(exports, "buildASTSchema", { + enumerable: true, + get: function get() { + return _buildASTSchema.buildASTSchema; + } +}); +Object.defineProperty(exports, "buildSchema", { + enumerable: true, + get: function get() { + return _buildASTSchema.buildSchema; + } +}); +Object.defineProperty(exports, "getDescription", { + enumerable: true, + get: function get() { + return _buildASTSchema.getDescription; + } +}); +Object.defineProperty(exports, "extendSchema", { + enumerable: true, + get: function get() { + return _extendSchema.extendSchema; + } +}); +Object.defineProperty(exports, "lexicographicSortSchema", { + enumerable: true, + get: function get() { + return _lexicographicSortSchema.lexicographicSortSchema; + } +}); +Object.defineProperty(exports, "printSchema", { + enumerable: true, + get: function get() { + return _schemaPrinter.printSchema; + } +}); +Object.defineProperty(exports, "printType", { + enumerable: true, + get: function get() { + return _schemaPrinter.printType; + } +}); +Object.defineProperty(exports, "printIntrospectionSchema", { + enumerable: true, + get: function get() { + return _schemaPrinter.printIntrospectionSchema; + } +}); +Object.defineProperty(exports, "typeFromAST", { + enumerable: true, + get: function get() { + return _typeFromAST.typeFromAST; + } +}); +Object.defineProperty(exports, "valueFromAST", { + enumerable: true, + get: function get() { + return _valueFromAST.valueFromAST; + } +}); +Object.defineProperty(exports, "valueFromASTUntyped", { + enumerable: true, + get: function get() { + return _valueFromASTUntyped.valueFromASTUntyped; + } +}); +Object.defineProperty(exports, "astFromValue", { + enumerable: true, + get: function get() { + return _astFromValue.astFromValue; + } +}); +Object.defineProperty(exports, "TypeInfo", { + enumerable: true, + get: function get() { + return _TypeInfo.TypeInfo; + } +}); +Object.defineProperty(exports, "coerceValue", { + enumerable: true, + get: function get() { + return _coerceValue.coerceValue; + } +}); +Object.defineProperty(exports, "isValidJSValue", { + enumerable: true, + get: function get() { + return _isValidJSValue.isValidJSValue; + } +}); +Object.defineProperty(exports, "isValidLiteralValue", { + enumerable: true, + get: function get() { + return _isValidLiteralValue.isValidLiteralValue; + } +}); +Object.defineProperty(exports, "concatAST", { + enumerable: true, + get: function get() { + return _concatAST.concatAST; + } +}); +Object.defineProperty(exports, "separateOperations", { + enumerable: true, + get: function get() { + return _separateOperations.separateOperations; + } +}); +Object.defineProperty(exports, "isEqualType", { + enumerable: true, + get: function get() { + return _typeComparators.isEqualType; + } +}); +Object.defineProperty(exports, "isTypeSubTypeOf", { + enumerable: true, + get: function get() { + return _typeComparators.isTypeSubTypeOf; + } +}); +Object.defineProperty(exports, "doTypesOverlap", { + enumerable: true, + get: function get() { + return _typeComparators.doTypesOverlap; + } +}); +Object.defineProperty(exports, "assertValidName", { + enumerable: true, + get: function get() { + return _assertValidName.assertValidName; + } +}); +Object.defineProperty(exports, "isValidNameError", { + enumerable: true, + get: function get() { + return _assertValidName.isValidNameError; + } +}); +Object.defineProperty(exports, "BreakingChangeType", { + enumerable: true, + get: function get() { + return _findBreakingChanges.BreakingChangeType; + } +}); +Object.defineProperty(exports, "DangerousChangeType", { + enumerable: true, + get: function get() { + return _findBreakingChanges.DangerousChangeType; + } +}); +Object.defineProperty(exports, "findBreakingChanges", { + enumerable: true, + get: function get() { + return _findBreakingChanges.findBreakingChanges; + } +}); +Object.defineProperty(exports, "findDangerousChanges", { + enumerable: true, + get: function get() { + return _findBreakingChanges.findDangerousChanges; + } +}); +Object.defineProperty(exports, "findDeprecatedUsages", { + enumerable: true, + get: function get() { + return _findDeprecatedUsages.findDeprecatedUsages; + } +}); + +var _introspectionQuery = require("./introspectionQuery"); + +var _getOperationAST = require("./getOperationAST"); + +var _getOperationRootType = require("./getOperationRootType"); + +var _introspectionFromSchema = require("./introspectionFromSchema"); + +var _buildClientSchema = require("./buildClientSchema"); + +var _buildASTSchema = require("./buildASTSchema"); + +var _extendSchema = require("./extendSchema"); + +var _lexicographicSortSchema = require("./lexicographicSortSchema"); + +var _schemaPrinter = require("./schemaPrinter"); + +var _typeFromAST = require("./typeFromAST"); + +var _valueFromAST = require("./valueFromAST"); + +var _valueFromASTUntyped = require("./valueFromASTUntyped"); + +var _astFromValue = require("./astFromValue"); + +var _TypeInfo = require("./TypeInfo"); + +var _coerceValue = require("./coerceValue"); + +var _isValidJSValue = require("./isValidJSValue"); + +var _isValidLiteralValue = require("./isValidLiteralValue"); + +var _concatAST = require("./concatAST"); + +var _separateOperations = require("./separateOperations"); + +var _typeComparators = require("./typeComparators"); + +var _assertValidName = require("./assertValidName"); + +var _findBreakingChanges = require("./findBreakingChanges"); + +var _findDeprecatedUsages = require("./findDeprecatedUsages"); \ No newline at end of file diff --git a/node_modules/graphql/utilities/index.js.flow b/node_modules/graphql/utilities/index.js.flow new file mode 100644 index 00000000..cf14c719 --- /dev/null +++ b/node_modules/graphql/utilities/index.js.flow @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +// The GraphQL query recommended for a full schema introspection. +export { + getIntrospectionQuery, + // @deprecated, use getIntrospectionQuery() - will be removed in v15 + introspectionQuery, +} from './introspectionQuery'; +export type { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, +} from './introspectionQuery'; + +// Gets the target Operation from a Document +export { getOperationAST } from './getOperationAST'; + +// Gets the Type for the target Operation AST. +export { getOperationRootType } from './getOperationRootType'; + +// Convert a GraphQLSchema to an IntrospectionQuery +export { introspectionFromSchema } from './introspectionFromSchema'; + +// Build a GraphQLSchema from an introspection result. +export { buildClientSchema } from './buildClientSchema'; + +// Build a GraphQLSchema from GraphQL Schema language. +export { + buildASTSchema, + buildSchema, + // @deprecated: Get the description from a schema AST node and supports legacy + // syntax for specifying descriptions - will be removed in v16 + getDescription, +} from './buildASTSchema'; +export type { BuildSchemaOptions } from './buildASTSchema'; + +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { extendSchema } from './extendSchema'; + +// Sort a GraphQLSchema. +export { lexicographicSortSchema } from './lexicographicSortSchema'; + +// Print a GraphQLSchema to GraphQL Schema language. +export { + printSchema, + printType, + printIntrospectionSchema, +} from './schemaPrinter'; + +// Create a GraphQLType from a GraphQL language AST. +export { typeFromAST } from './typeFromAST'; + +// Create a JavaScript value from a GraphQL language AST with a type. +export { valueFromAST } from './valueFromAST'; + +// Create a JavaScript value from a GraphQL language AST without a type. +export { valueFromASTUntyped } from './valueFromASTUntyped'; + +// Create a GraphQL language AST from a JavaScript value. +export { astFromValue } from './astFromValue'; + +// A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. +export { TypeInfo } from './TypeInfo'; + +// Coerces a JavaScript value to a GraphQL type, or produces errors. +export { coerceValue } from './coerceValue'; + +// @deprecated use coerceValue - will be removed in v15 +export { isValidJSValue } from './isValidJSValue'; + +// @deprecated use validation - will be removed in v15 +export { isValidLiteralValue } from './isValidLiteralValue'; + +// Concatenates multiple AST together. +export { concatAST } from './concatAST'; + +// Separates an AST into an AST per Operation. +export { separateOperations } from './separateOperations'; + +// Comparators for types +export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, +} from './typeComparators'; + +// Asserts that a string is a valid GraphQL name +export { assertValidName, isValidNameError } from './assertValidName'; + +// Compares two GraphQLSchemas and detects breaking changes. +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, +} from './findBreakingChanges'; +export type { BreakingChange, DangerousChange } from './findBreakingChanges'; + +// Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from './findDeprecatedUsages'; diff --git a/node_modules/graphql/utilities/index.mjs b/node_modules/graphql/utilities/index.mjs new file mode 100644 index 00000000..4ba97331 --- /dev/null +++ b/node_modules/graphql/utilities/index.mjs @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// The GraphQL query recommended for a full schema introspection. +export { getIntrospectionQuery, // @deprecated, use getIntrospectionQuery() - will be removed in v15 +introspectionQuery } from './introspectionQuery'; +// Gets the target Operation from a Document +export { getOperationAST } from './getOperationAST'; // Gets the Type for the target Operation AST. + +export { getOperationRootType } from './getOperationRootType'; // Convert a GraphQLSchema to an IntrospectionQuery + +export { introspectionFromSchema } from './introspectionFromSchema'; // Build a GraphQLSchema from an introspection result. + +export { buildClientSchema } from './buildClientSchema'; // Build a GraphQLSchema from GraphQL Schema language. + +export { buildASTSchema, buildSchema, // @deprecated: Get the description from a schema AST node and supports legacy +// syntax for specifying descriptions - will be removed in v16 +getDescription } from './buildASTSchema'; +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { extendSchema } from './extendSchema'; // Sort a GraphQLSchema. + +export { lexicographicSortSchema } from './lexicographicSortSchema'; // Print a GraphQLSchema to GraphQL Schema language. + +export { printSchema, printType, printIntrospectionSchema } from './schemaPrinter'; // Create a GraphQLType from a GraphQL language AST. + +export { typeFromAST } from './typeFromAST'; // Create a JavaScript value from a GraphQL language AST with a type. + +export { valueFromAST } from './valueFromAST'; // Create a JavaScript value from a GraphQL language AST without a type. + +export { valueFromASTUntyped } from './valueFromASTUntyped'; // Create a GraphQL language AST from a JavaScript value. + +export { astFromValue } from './astFromValue'; // A helper to use within recursive-descent visitors which need to be aware of +// the GraphQL type system. + +export { TypeInfo } from './TypeInfo'; // Coerces a JavaScript value to a GraphQL type, or produces errors. + +export { coerceValue } from './coerceValue'; // @deprecated use coerceValue - will be removed in v15 + +export { isValidJSValue } from './isValidJSValue'; // @deprecated use validation - will be removed in v15 + +export { isValidLiteralValue } from './isValidLiteralValue'; // Concatenates multiple AST together. + +export { concatAST } from './concatAST'; // Separates an AST into an AST per Operation. + +export { separateOperations } from './separateOperations'; // Comparators for types + +export { isEqualType, isTypeSubTypeOf, doTypesOverlap } from './typeComparators'; // Asserts that a string is a valid GraphQL name + +export { assertValidName, isValidNameError } from './assertValidName'; // Compares two GraphQLSchemas and detects breaking changes. + +export { BreakingChangeType, DangerousChangeType, findBreakingChanges, findDangerousChanges } from './findBreakingChanges'; +// Report all deprecated usage within a GraphQL document. +export { findDeprecatedUsages } from './findDeprecatedUsages'; \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionFromSchema.js b/node_modules/graphql/utilities/introspectionFromSchema.js new file mode 100644 index 00000000..5d8fd69d --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.introspectionFromSchema = introspectionFromSchema; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _introspectionQuery = require("./introspectionQuery"); + +var _execute = require("../execution/execute"); + +var _parser = require("../language/parser"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +function introspectionFromSchema(schema, options) { + var queryAST = (0, _parser.parse)((0, _introspectionQuery.getIntrospectionQuery)(options)); + var result = (0, _execute.execute)(schema, queryAST); + !(!result.then && !result.errors && result.data) ? (0, _invariant.default)(0) : void 0; + return result.data; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionFromSchema.js.flow b/node_modules/graphql/utilities/introspectionFromSchema.js.flow new file mode 100644 index 00000000..c2690b6f --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.js.flow @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import { getIntrospectionQuery } from './introspectionQuery'; +import type { GraphQLSchema } from '../type/schema'; +import { execute } from '../execution/execute'; +import { parse } from '../language/parser'; +import type { + IntrospectionQuery, + IntrospectionOptions, +} from './introspectionQuery'; + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +export function introspectionFromSchema( + schema: GraphQLSchema, + options?: IntrospectionOptions, +): IntrospectionQuery { + const queryAST = parse(getIntrospectionQuery(options)); + const result = execute(schema, queryAST); + invariant(!result.then && !result.errors && result.data); + return (result.data: any); +} diff --git a/node_modules/graphql/utilities/introspectionFromSchema.mjs b/node_modules/graphql/utilities/introspectionFromSchema.mjs new file mode 100644 index 00000000..88a0bffc --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.mjs @@ -0,0 +1,28 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import { getIntrospectionQuery } from './introspectionQuery'; +import { execute } from '../execution/execute'; +import { parse } from '../language/parser'; + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + */ +export function introspectionFromSchema(schema, options) { + var queryAST = parse(getIntrospectionQuery(options)); + var result = execute(schema, queryAST); + !(!result.then && !result.errors && result.data) ? invariant(0) : void 0; + return result.data; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionQuery.js b/node_modules/graphql/utilities/introspectionQuery.js new file mode 100644 index 00000000..b0179d35 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionQuery.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getIntrospectionQuery = getIntrospectionQuery; +exports.introspectionQuery = void 0; + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function getIntrospectionQuery(options) { + var descriptions = !(options && options.descriptions === false); + return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "); +} +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ + + +var introspectionQuery = getIntrospectionQuery(); +exports.introspectionQuery = introspectionQuery; \ No newline at end of file diff --git a/node_modules/graphql/utilities/introspectionQuery.js.flow b/node_modules/graphql/utilities/introspectionQuery.js.flow new file mode 100644 index 00000000..b6ebe584 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionQuery.js.flow @@ -0,0 +1,276 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { DirectiveLocationEnum } from '../language/directiveLocation'; + +export type IntrospectionOptions = {| + // Whether to include descriptions in the introspection result. + // Default: true + descriptions: boolean, +|}; + +export function getIntrospectionQuery(options?: IntrospectionOptions): string { + const descriptions = !(options && options.descriptions === false); + return ` + query IntrospectionQuery { + __schema { + queryType { name } + mutationType { name } + subscriptionType { name } + types { + ...FullType + } + directives { + name + ${descriptions ? 'description' : ''} + locations + args { + ...InputValue + } + } + } + } + + fragment FullType on __Type { + kind + name + ${descriptions ? 'description' : ''} + fields(includeDeprecated: true) { + name + ${descriptions ? 'description' : ''} + args { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions ? 'description' : ''} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions ? 'description' : ''} + type { ...TypeRef } + defaultValue + } + + fragment TypeRef on __Type { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + ofType { + kind + name + } + } + } + } + } + } + } + } + `; +} + +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ +export const introspectionQuery = getIntrospectionQuery(); + +export type IntrospectionQuery = {| + +__schema: IntrospectionSchema, +|}; + +export type IntrospectionSchema = {| + +queryType: IntrospectionNamedTypeRef, + +mutationType: ?IntrospectionNamedTypeRef, + +subscriptionType: ?IntrospectionNamedTypeRef, + +types: $ReadOnlyArray, + +directives: $ReadOnlyArray, +|}; + +export type IntrospectionType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionOutputType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType; + +export type IntrospectionInputType = + | IntrospectionScalarType + | IntrospectionEnumType + | IntrospectionInputObjectType; + +export type IntrospectionScalarType = { + +kind: 'SCALAR', + +name: string, + +description?: ?string, +}; + +export type IntrospectionObjectType = { + +kind: 'OBJECT', + +name: string, + +description?: ?string, + +fields: $ReadOnlyArray, + +interfaces: $ReadOnlyArray< + IntrospectionNamedTypeRef, + >, +}; + +export type IntrospectionInterfaceType = { + +kind: 'INTERFACE', + +name: string, + +description?: ?string, + +fields: $ReadOnlyArray, + +possibleTypes: $ReadOnlyArray< + IntrospectionNamedTypeRef, + >, +}; + +export type IntrospectionUnionType = { + +kind: 'UNION', + +name: string, + +description?: ?string, + +possibleTypes: $ReadOnlyArray< + IntrospectionNamedTypeRef, + >, +}; + +export type IntrospectionEnumType = { + +kind: 'ENUM', + +name: string, + +description?: ?string, + +enumValues: $ReadOnlyArray, +}; + +export type IntrospectionInputObjectType = { + +kind: 'INPUT_OBJECT', + +name: string, + +description?: ?string, + +inputFields: $ReadOnlyArray, +}; + +export type IntrospectionListTypeRef< + T: IntrospectionTypeRef = IntrospectionTypeRef, +> = { + +kind: 'LIST', + +ofType: T, +}; + +export type IntrospectionNonNullTypeRef< + T: IntrospectionTypeRef = IntrospectionTypeRef, +> = { + +kind: 'NON_NULL', + +ofType: T, +}; + +export type IntrospectionTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef, + >; + +export type IntrospectionOutputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef, + >; + +export type IntrospectionInputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef, + >; + +export type IntrospectionNamedTypeRef< + T: IntrospectionType = IntrospectionType, +> = { + +kind: $PropertyType, + +name: string, +}; + +export type IntrospectionField = {| + +name: string, + +description?: ?string, + +args: $ReadOnlyArray, + +type: IntrospectionOutputTypeRef, + +isDeprecated: boolean, + +deprecationReason: ?string, +|}; + +export type IntrospectionInputValue = {| + +name: string, + +description?: ?string, + +type: IntrospectionInputTypeRef, + +defaultValue: ?string, +|}; + +export type IntrospectionEnumValue = {| + +name: string, + +description?: ?string, + +isDeprecated: boolean, + +deprecationReason: ?string, +|}; + +export type IntrospectionDirective = {| + +name: string, + +description?: ?string, + +locations: $ReadOnlyArray, + +args: $ReadOnlyArray, +|}; diff --git a/node_modules/graphql/utilities/introspectionQuery.mjs b/node_modules/graphql/utilities/introspectionQuery.mjs new file mode 100644 index 00000000..8eec21d9 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionQuery.mjs @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export function getIntrospectionQuery(options) { + var descriptions = !(options && options.descriptions === false); + return "\n query IntrospectionQuery {\n __schema {\n queryType { name }\n mutationType { name }\n subscriptionType { name }\n types {\n ...FullType\n }\n directives {\n name\n ".concat(descriptions ? 'description' : '', "\n locations\n args {\n ...InputValue\n }\n }\n }\n }\n\n fragment FullType on __Type {\n kind\n name\n ").concat(descriptions ? 'description' : '', "\n fields(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n args {\n ...InputValue\n }\n type {\n ...TypeRef\n }\n isDeprecated\n deprecationReason\n }\n inputFields {\n ...InputValue\n }\n interfaces {\n ...TypeRef\n }\n enumValues(includeDeprecated: true) {\n name\n ").concat(descriptions ? 'description' : '', "\n isDeprecated\n deprecationReason\n }\n possibleTypes {\n ...TypeRef\n }\n }\n\n fragment InputValue on __InputValue {\n name\n ").concat(descriptions ? 'description' : '', "\n type { ...TypeRef }\n defaultValue\n }\n\n fragment TypeRef on __Type {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n ofType {\n kind\n name\n }\n }\n }\n }\n }\n }\n }\n }\n "); +} +/** + * Deprecated, call getIntrospectionQuery directly. + * + * This function will be removed in v15 + */ + +export var introspectionQuery = getIntrospectionQuery(); \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidJSValue.js b/node_modules/graphql/utilities/isValidJSValue.js new file mode 100644 index 00000000..d1fa12fa --- /dev/null +++ b/node_modules/graphql/utilities/isValidJSValue.js @@ -0,0 +1,29 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidJSValue = isValidJSValue; + +var _coerceValue = require("./coerceValue"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +function isValidJSValue(value, type) { + var errors = (0, _coerceValue.coerceValue)(value, type).errors; + return errors ? errors.map(function (error) { + return error.message; + }) : []; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidJSValue.js.flow b/node_modules/graphql/utilities/isValidJSValue.js.flow new file mode 100644 index 00000000..815476be --- /dev/null +++ b/node_modules/graphql/utilities/isValidJSValue.js.flow @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { coerceValue } from './coerceValue'; +import type { GraphQLInputType } from '../type/definition'; + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +export function isValidJSValue( + value: mixed, + type: GraphQLInputType, +): Array { + const errors = coerceValue(value, type).errors; + return errors ? errors.map(error => error.message) : []; +} diff --git a/node_modules/graphql/utilities/isValidJSValue.mjs b/node_modules/graphql/utilities/isValidJSValue.mjs new file mode 100644 index 00000000..59c38fa8 --- /dev/null +++ b/node_modules/graphql/utilities/isValidJSValue.mjs @@ -0,0 +1,21 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { coerceValue } from './coerceValue'; + +/** + * Deprecated. Use coerceValue() directly for richer information. + * + * This function will be removed in v15 + */ +export function isValidJSValue(value, type) { + var errors = coerceValue(value, type).errors; + return errors ? errors.map(function (error) { + return error.message; + }) : []; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidLiteralValue.js b/node_modules/graphql/utilities/isValidLiteralValue.js new file mode 100644 index 00000000..c518c0ef --- /dev/null +++ b/node_modules/graphql/utilities/isValidLiteralValue.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidLiteralValue = isValidLiteralValue; + +var _TypeInfo = require("./TypeInfo"); + +var _kinds = require("../language/kinds"); + +var _visitor = require("../language/visitor"); + +var _schema = require("../type/schema"); + +var _ValuesOfCorrectType = require("../validation/rules/ValuesOfCorrectType"); + +var _ValidationContext = require("../validation/ValidationContext"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ +function isValidLiteralValue(type, valueNode) { + var emptySchema = new _schema.GraphQLSchema({}); + var emptyDoc = { + kind: _kinds.Kind.DOCUMENT, + definitions: [] + }; + var typeInfo = new _TypeInfo.TypeInfo(emptySchema, undefined, type); + var context = new _ValidationContext.ValidationContext(emptySchema, emptyDoc, typeInfo); + var visitor = (0, _ValuesOfCorrectType.ValuesOfCorrectType)(context); + (0, _visitor.visit)(valueNode, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor)); + return context.getErrors(); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/isValidLiteralValue.js.flow b/node_modules/graphql/utilities/isValidLiteralValue.js.flow new file mode 100644 index 00000000..1b7806cf --- /dev/null +++ b/node_modules/graphql/utilities/isValidLiteralValue.js.flow @@ -0,0 +1,38 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { TypeInfo } from './TypeInfo'; +import type { GraphQLError } from '../error/GraphQLError'; +import type { ValueNode } from '../language/ast'; +import { Kind } from '../language/kinds'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import type { GraphQLInputType } from '../type/definition'; +import { GraphQLSchema } from '../type/schema'; +import { ValuesOfCorrectType } from '../validation/rules/ValuesOfCorrectType'; +import { ValidationContext } from '../validation/ValidationContext'; + +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ +export function isValidLiteralValue( + type: GraphQLInputType, + valueNode: ValueNode, +): $ReadOnlyArray { + const emptySchema = new GraphQLSchema({}); + const emptyDoc = { kind: Kind.DOCUMENT, definitions: [] }; + const typeInfo = new TypeInfo(emptySchema, undefined, type); + const context = new ValidationContext(emptySchema, emptyDoc, typeInfo); + const visitor = ValuesOfCorrectType(context); + visit(valueNode, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} diff --git a/node_modules/graphql/utilities/isValidLiteralValue.mjs b/node_modules/graphql/utilities/isValidLiteralValue.mjs new file mode 100644 index 00000000..103c20c0 --- /dev/null +++ b/node_modules/graphql/utilities/isValidLiteralValue.mjs @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { TypeInfo } from './TypeInfo'; +import { Kind } from '../language/kinds'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { GraphQLSchema } from '../type/schema'; +import { ValuesOfCorrectType } from '../validation/rules/ValuesOfCorrectType'; +import { ValidationContext } from '../validation/ValidationContext'; +/** + * Utility which determines if a value literal node is valid for an input type. + * + * Deprecated. Rely on validation for documents containing literal values. + * + * This function will be removed in v15 + */ + +export function isValidLiteralValue(type, valueNode) { + var emptySchema = new GraphQLSchema({}); + var emptyDoc = { + kind: Kind.DOCUMENT, + definitions: [] + }; + var typeInfo = new TypeInfo(emptySchema, undefined, type); + var context = new ValidationContext(emptySchema, emptyDoc, typeInfo); + var visitor = ValuesOfCorrectType(context); + visit(valueNode, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.js b/node_modules/graphql/utilities/lexicographicSortSchema.js new file mode 100644 index 00000000..09f56d74 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.js @@ -0,0 +1,219 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.lexicographicSortSchema = lexicographicSortSchema; + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _schema = require("../type/schema"); + +var _directives = require("../type/directives"); + +var _definition = require("../type/definition"); + +var _scalars = require("../type/scalars"); + +var _introspection = require("../type/introspection"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Sort GraphQLSchema. + */ +function lexicographicSortSchema(schema) { + var cache = Object.create(null); + + var sortMaybeType = function sortMaybeType(maybeType) { + return maybeType && sortNamedType(maybeType); + }; + + return new _schema.GraphQLSchema({ + types: sortTypes((0, _objectValues.default)(schema.getTypeMap())), + directives: sortByName(schema.getDirectives()).map(sortDirective), + query: sortMaybeType(schema.getQueryType()), + mutation: sortMaybeType(schema.getMutationType()), + subscription: sortMaybeType(schema.getSubscriptionType()), + astNode: schema.astNode + }); + + function sortDirective(directive) { + return new _directives.GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: sortBy(directive.locations, function (x) { + return x; + }), + args: sortArgs(directive.args), + astNode: directive.astNode + }); + } + + function sortArgs(args) { + return (0, _keyValMap.default)(sortByName(args), function (arg) { + return arg.name; + }, function (arg) { + return _objectSpread({}, arg, { + type: sortType(arg.type) + }); + }); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + args: sortArgs(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + defaultValue: field.defaultValue, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortType(type) { + if ((0, _definition.isListType)(type)) { + return new _definition.GraphQLList(sortType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + return new _definition.GraphQLNonNull(sortType(type.ofType)); + } + + return sortNamedType(type); + } + + function sortTypes(arr) { + return sortByName(arr).map(sortNamedType); + } + + function sortNamedType(type) { + if ((0, _scalars.isSpecifiedScalarType)(type) || (0, _introspection.isIntrospectionType)(type)) { + return type; + } + + var sortedType = cache[type.name]; + + if (!sortedType) { + sortedType = sortNamedTypeImpl(type); + cache[type.name] = sortedType; + } + + return sortedType; + } + + function sortNamedTypeImpl(type) { + if ((0, _definition.isScalarType)(type)) { + return type; + } else if ((0, _definition.isObjectType)(type)) { + return new _definition.GraphQLObjectType({ + name: type.name, + interfaces: function interfaces() { + return sortTypes(type.getInterfaces()); + }, + fields: function fields() { + return sortFields(type.getFields()); + }, + isTypeOf: type.isTypeOf, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if ((0, _definition.isInterfaceType)(type)) { + return new _definition.GraphQLInterfaceType({ + name: type.name, + fields: function fields() { + return sortFields(type.getFields()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if ((0, _definition.isUnionType)(type)) { + return new _definition.GraphQLUnionType({ + name: type.name, + types: function types() { + return sortTypes(type.getTypes()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode + }); + } else if ((0, _definition.isEnumType)(type)) { + return new _definition.GraphQLEnumType({ + name: type.name, + values: (0, _keyValMap.default)(sortByName(type.getValues()), function (val) { + return val.name; + }, function (val) { + return { + value: val.value, + deprecationReason: val.deprecationReason, + description: val.description, + astNode: val.astNode + }; + }), + description: type.description, + astNode: type.astNode + }); + } else if ((0, _definition.isInputObjectType)(type)) { + return new _definition.GraphQLInputObjectType({ + name: type.name, + fields: function fields() { + return sortInputFields(type.getFields()); + }, + description: type.description, + astNode: type.astNode + }); + } + + throw new Error("Unknown type: \"".concat(type, "\"")); + } +} + +function sortObjMap(map, sortValueFn) { + var sortedMap = Object.create(null); + var sortedKeys = sortBy(Object.keys(map), function (x) { + return x; + }); + + for (var _i = 0; _i < sortedKeys.length; _i++) { + var key = sortedKeys[_i]; + var value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, function (obj) { + return obj.name; + }); +} + +function sortBy(array, mapToKey) { + return array.slice().sort(function (obj1, obj2) { + var key1 = mapToKey(obj1); + var key2 = mapToKey(obj2); + return key1.localeCompare(key2); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.js.flow b/node_modules/graphql/utilities/lexicographicSortSchema.js.flow new file mode 100644 index 00000000..570d3e45 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.js.flow @@ -0,0 +1,198 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from '../jsutils/ObjMap'; +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import type { GraphQLNamedType } from '../type/definition'; +import { + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + isListType, + isNonNullType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../type/definition'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { isIntrospectionType } from '../type/introspection'; + +/** + * Sort GraphQLSchema. + */ +export function lexicographicSortSchema(schema: GraphQLSchema): GraphQLSchema { + const cache = Object.create(null); + + const sortMaybeType = maybeType => maybeType && sortNamedType(maybeType); + return new GraphQLSchema({ + types: sortTypes(objectValues(schema.getTypeMap())), + directives: sortByName(schema.getDirectives()).map(sortDirective), + query: sortMaybeType(schema.getQueryType()), + mutation: sortMaybeType(schema.getMutationType()), + subscription: sortMaybeType(schema.getSubscriptionType()), + astNode: schema.astNode, + }); + + function sortDirective(directive) { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: sortBy(directive.locations, x => x), + args: sortArgs(directive.args), + astNode: directive.astNode, + }); + } + + function sortArgs(args) { + return keyValMap( + sortByName(args), + arg => arg.name, + arg => ({ + ...arg, + type: sortType(arg.type), + }), + ); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + type: sortType(field.type), + args: sortArgs(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + description: field.description, + astNode: field.astNode, + })); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, field => ({ + type: sortType(field.type), + defaultValue: field.defaultValue, + description: field.description, + astNode: field.astNode, + })); + } + + function sortType(type) { + if (isListType(type)) { + return new GraphQLList(sortType(type.ofType)); + } else if (isNonNullType(type)) { + return new GraphQLNonNull(sortType(type.ofType)); + } + return sortNamedType(type); + } + + function sortTypes(arr: Array): Array { + return sortByName(arr).map(sortNamedType); + } + + function sortNamedType(type: T): T { + if (isSpecifiedScalarType(type) || isIntrospectionType(type)) { + return type; + } + + let sortedType = cache[type.name]; + if (!sortedType) { + sortedType = sortNamedTypeImpl(type); + cache[type.name] = sortedType; + } + return ((sortedType: any): T); + } + + function sortNamedTypeImpl(type) { + if (isScalarType(type)) { + return type; + } else if (isObjectType(type)) { + return new GraphQLObjectType({ + name: type.name, + interfaces: () => sortTypes(type.getInterfaces()), + fields: () => sortFields(type.getFields()), + isTypeOf: type.isTypeOf, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes, + }); + } else if (isInterfaceType(type)) { + return new GraphQLInterfaceType({ + name: type.name, + fields: () => sortFields(type.getFields()), + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes, + }); + } else if (isUnionType(type)) { + return new GraphQLUnionType({ + name: type.name, + types: () => sortTypes(type.getTypes()), + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + }); + } else if (isEnumType(type)) { + return new GraphQLEnumType({ + name: type.name, + values: keyValMap( + sortByName(type.getValues()), + val => val.name, + val => ({ + value: val.value, + deprecationReason: val.deprecationReason, + description: val.description, + astNode: val.astNode, + }), + ), + description: type.description, + astNode: type.astNode, + }); + } else if (isInputObjectType(type)) { + return new GraphQLInputObjectType({ + name: type.name, + fields: () => sortInputFields(type.getFields()), + description: type.description, + astNode: type.astNode, + }); + } + throw new Error(`Unknown type: "${type}"`); + } +} + +function sortObjMap(map: ObjMap, sortValueFn?: T => R): ObjMap { + const sortedMap = Object.create(null); + const sortedKeys = sortBy(Object.keys(map), x => x); + for (const key of sortedKeys) { + const value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + return sortedMap; +} + +function sortByName(array: $ReadOnlyArray): Array { + return sortBy(array, obj => obj.name); +} + +function sortBy(array: $ReadOnlyArray, mapToKey: T => string): Array { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return key1.localeCompare(key2); + }); +} diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.mjs b/node_modules/graphql/utilities/lexicographicSortSchema.mjs new file mode 100644 index 00000000..fc0841a5 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.mjs @@ -0,0 +1,212 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import keyValMap from '../jsutils/keyValMap'; +import objectValues from '../jsutils/objectValues'; +import { GraphQLSchema } from '../type/schema'; +import { GraphQLDirective } from '../type/directives'; +import { GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLList, GraphQLNonNull, isListType, isNonNullType, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../type/definition'; +import { isSpecifiedScalarType } from '../type/scalars'; +import { isIntrospectionType } from '../type/introspection'; +/** + * Sort GraphQLSchema. + */ + +export function lexicographicSortSchema(schema) { + var cache = Object.create(null); + + var sortMaybeType = function sortMaybeType(maybeType) { + return maybeType && sortNamedType(maybeType); + }; + + return new GraphQLSchema({ + types: sortTypes(objectValues(schema.getTypeMap())), + directives: sortByName(schema.getDirectives()).map(sortDirective), + query: sortMaybeType(schema.getQueryType()), + mutation: sortMaybeType(schema.getMutationType()), + subscription: sortMaybeType(schema.getSubscriptionType()), + astNode: schema.astNode + }); + + function sortDirective(directive) { + return new GraphQLDirective({ + name: directive.name, + description: directive.description, + locations: sortBy(directive.locations, function (x) { + return x; + }), + args: sortArgs(directive.args), + astNode: directive.astNode + }); + } + + function sortArgs(args) { + return keyValMap(sortByName(args), function (arg) { + return arg.name; + }, function (arg) { + return _objectSpread({}, arg, { + type: sortType(arg.type) + }); + }); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + args: sortArgs(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, function (field) { + return { + type: sortType(field.type), + defaultValue: field.defaultValue, + description: field.description, + astNode: field.astNode + }; + }); + } + + function sortType(type) { + if (isListType(type)) { + return new GraphQLList(sortType(type.ofType)); + } else if (isNonNullType(type)) { + return new GraphQLNonNull(sortType(type.ofType)); + } + + return sortNamedType(type); + } + + function sortTypes(arr) { + return sortByName(arr).map(sortNamedType); + } + + function sortNamedType(type) { + if (isSpecifiedScalarType(type) || isIntrospectionType(type)) { + return type; + } + + var sortedType = cache[type.name]; + + if (!sortedType) { + sortedType = sortNamedTypeImpl(type); + cache[type.name] = sortedType; + } + + return sortedType; + } + + function sortNamedTypeImpl(type) { + if (isScalarType(type)) { + return type; + } else if (isObjectType(type)) { + return new GraphQLObjectType({ + name: type.name, + interfaces: function interfaces() { + return sortTypes(type.getInterfaces()); + }, + fields: function fields() { + return sortFields(type.getFields()); + }, + isTypeOf: type.isTypeOf, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if (isInterfaceType(type)) { + return new GraphQLInterfaceType({ + name: type.name, + fields: function fields() { + return sortFields(type.getFields()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode, + extensionASTNodes: type.extensionASTNodes + }); + } else if (isUnionType(type)) { + return new GraphQLUnionType({ + name: type.name, + types: function types() { + return sortTypes(type.getTypes()); + }, + resolveType: type.resolveType, + description: type.description, + astNode: type.astNode + }); + } else if (isEnumType(type)) { + return new GraphQLEnumType({ + name: type.name, + values: keyValMap(sortByName(type.getValues()), function (val) { + return val.name; + }, function (val) { + return { + value: val.value, + deprecationReason: val.deprecationReason, + description: val.description, + astNode: val.astNode + }; + }), + description: type.description, + astNode: type.astNode + }); + } else if (isInputObjectType(type)) { + return new GraphQLInputObjectType({ + name: type.name, + fields: function fields() { + return sortInputFields(type.getFields()); + }, + description: type.description, + astNode: type.astNode + }); + } + + throw new Error("Unknown type: \"".concat(type, "\"")); + } +} + +function sortObjMap(map, sortValueFn) { + var sortedMap = Object.create(null); + var sortedKeys = sortBy(Object.keys(map), function (x) { + return x; + }); + + for (var _i = 0; _i < sortedKeys.length; _i++) { + var key = sortedKeys[_i]; + var value = map[key]; + sortedMap[key] = sortValueFn ? sortValueFn(value) : value; + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, function (obj) { + return obj.name; + }); +} + +function sortBy(array, mapToKey) { + return array.slice().sort(function (obj1, obj2) { + var key1 = mapToKey(obj1); + var key2 = mapToKey(obj2); + return key1.localeCompare(key2); + }); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/schemaPrinter.js b/node_modules/graphql/utilities/schemaPrinter.js new file mode 100644 index 00000000..3355b22f --- /dev/null +++ b/node_modules/graphql/utilities/schemaPrinter.js @@ -0,0 +1,342 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.printSchema = printSchema; +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printType = printType; + +var _isNullish = _interopRequireDefault(require("../jsutils/isNullish")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _astFromValue = require("../utilities/astFromValue"); + +var _printer = require("../language/printer"); + +var _definition = require("../type/definition"); + +var _scalars = require("../type/scalars"); + +var _directives = require("../type/directives"); + +var _introspection = require("../type/introspection"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +function printSchema(schema, options) { + return printFilteredSchema(schema, function (n) { + return !(0, _directives.isSpecifiedDirective)(n); + }, isDefinedType, options); +} + +function printIntrospectionSchema(schema, options) { + return printFilteredSchema(schema, _directives.isSpecifiedDirective, _introspection.isIntrospectionType, options); +} + +function isDefinedType(type) { + return !(0, _scalars.isSpecifiedScalarType)(type) && !(0, _introspection.isIntrospectionType)(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter, options) { + var directives = schema.getDirectives().filter(directiveFilter); + var typeMap = schema.getTypeMap(); + var types = (0, _objectValues.default)(typeMap).sort(function (type1, type2) { + return type1.name.localeCompare(type2.name); + }).filter(typeFilter); + return [printSchemaDefinition(schema)].concat(directives.map(function (directive) { + return printDirective(directive, options); + }), types.map(function (type) { + return printType(type, options); + })).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + var queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(" query: ".concat(queryType.name)); + } + + var mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(" mutation: ".concat(mutationType.name)); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(" subscription: ".concat(subscriptionType.name)); + } + + return "schema {\n".concat(operationTypes.join('\n'), "\n}"); +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ + + +function isSchemaOfCommonNames(schema) { + var queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + var mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +function printType(type, options) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type, options); + } else if ((0, _definition.isObjectType)(type)) { + return printObject(type, options); + } else if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type, options); + } else if ((0, _definition.isUnionType)(type)) { + return printUnion(type, options); + } else if ((0, _definition.isEnumType)(type)) { + return printEnum(type, options); + } else if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type, options); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} + +function printScalar(type, options) { + return printDescription(options, type) + "scalar ".concat(type.name); +} + +function printObject(type, options) { + var interfaces = type.getInterfaces(); + var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(' & ') : ''; + return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printInterface(type, options) { + return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printUnion(type, options) { + return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | ')); +} + +function printEnum(type, options) { + return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}'; +} + +function printEnumValues(values, options) { + return values.map(function (value, i) { + return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value); + }).join('\n'); +} + +function printInputObject(type, options) { + var fields = (0, _objectValues.default)(type.getFields()); + return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f); + }).join('\n') + '\n' + '}'; +} + +function printFields(options, type) { + var fields = (0, _objectValues.default)(type.getFields()); + return fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f); + }).join('\n'); +} + +function printArgs(options, args) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + + if (args.every(function (arg) { + return !arg.description; + })) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return '(\n' + args.map(function (arg, i) { + return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var argDecl = arg.name + ': ' + String(arg.type); + + if (!(0, _isInvalid.default)(arg.defaultValue)) { + argDecl += " = ".concat((0, _printer.print)((0, _astFromValue.astFromValue)(arg.defaultValue, arg.type))); + } + + return argDecl; +} + +function printDirective(directive, options) { + return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(fieldOrEnumVal) { + if (!fieldOrEnumVal.isDeprecated) { + return ''; + } + + var reason = fieldOrEnumVal.deprecationReason; + + if ((0, _isNullish.default)(reason) || reason === '' || reason === _directives.DEFAULT_DEPRECATION_REASON) { + return ' @deprecated'; + } + + return ' @deprecated(reason: ' + (0, _printer.print)((0, _astFromValue.astFromValue)(reason, _scalars.GraphQLString)) + ')'; +} + +function printDescription(options, def) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + + if (!def.description) { + return ''; + } + + var lines = descriptionLines(def.description, 120 - indentation.length); + + if (options && options.commentDescriptions) { + return printDescriptionWithComments(lines, indentation, firstInBlock); + } + + var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description. + + if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') { + return description + escapeQuote(lines[0]) + '"""\n'; + } // Format a multi-line block quote to account for leading space. + + + var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t'; + + if (!hasLeadingSpace) { + description += '\n'; + } + + for (var i = 0; i < lines.length; i++) { + if (i !== 0 || !hasLeadingSpace) { + description += indentation; + } + + description += escapeQuote(lines[i]) + '\n'; + } + + description += indentation + '"""\n'; + return description; +} + +function escapeQuote(line) { + return line.replace(/"""/g, '\\"""'); +} + +function printDescriptionWithComments(lines, indentation, firstInBlock) { + var description = indentation && !firstInBlock ? '\n' : ''; + + for (var i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + description += indentation + '# ' + lines[i] + '\n'; + } + } + + return description; +} + +function descriptionLines(description, maxLen) { + var lines = []; + var rawLines = description.split('\n'); + + for (var i = 0; i < rawLines.length; i++) { + if (rawLines[i] === '') { + lines.push(rawLines[i]); + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + var sublines = breakLine(rawLines[i], maxLen); + + for (var j = 0; j < sublines.length; j++) { + lines.push(sublines[j]); + } + } + } + + return lines; +} + +function breakLine(line, maxLen) { + if (line.length < maxLen + 5) { + return [line]; + } + + var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))"))); + + if (parts.length < 4) { + return [line]; + } + + var sublines = [parts[0] + parts[1] + parts[2]]; + + for (var i = 3; i < parts.length; i += 2) { + sublines.push(parts[i].slice(1) + parts[i + 1]); + } + + return sublines; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/schemaPrinter.js.flow b/node_modules/graphql/utilities/schemaPrinter.js.flow new file mode 100644 index 00000000..aa9b01c0 --- /dev/null +++ b/node_modules/graphql/utilities/schemaPrinter.js.flow @@ -0,0 +1,425 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import type { GraphQLSchema } from '../type/schema'; +import { + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, +} from '../type/definition'; +import type { + GraphQLNamedType, + GraphQLScalarType, + GraphQLEnumType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLInputObjectType, +} from '../type/definition'; +import { GraphQLString, isSpecifiedScalarType } from '../type/scalars'; +import { + GraphQLDirective, + DEFAULT_DEPRECATION_REASON, + isSpecifiedDirective, +} from '../type/directives'; +import { isIntrospectionType } from '../type/introspection'; + +type Options = {| + /** + * Descriptions are defined as preceding string literals, however an older + * experimental version of the SDL supported preceding comments as + * descriptions. Set to true to enable this deprecated behavior. + * This option is provided to ease adoption and will be removed in v16. + * + * Default: false + */ + commentDescriptions?: boolean, +|}; + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema: GraphQLSchema, options?: Options): string { + return printFilteredSchema( + schema, + n => !isSpecifiedDirective(n), + isDefinedType, + options, + ); +} + +export function printIntrospectionSchema( + schema: GraphQLSchema, + options?: Options, +): string { + return printFilteredSchema( + schema, + isSpecifiedDirective, + isIntrospectionType, + options, + ); +} + +function isDefinedType(type: GraphQLNamedType): boolean { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema( + schema: GraphQLSchema, + directiveFilter: (type: GraphQLDirective) => boolean, + typeFilter: (type: GraphQLNamedType) => boolean, + options, +): string { + const directives = schema.getDirectives().filter(directiveFilter); + const typeMap = schema.getTypeMap(); + const types = objectValues(typeMap) + .sort((type1, type2) => type1.name.localeCompare(type2.name)) + .filter(typeFilter); + + return ( + [printSchemaDefinition(schema)] + .concat( + directives.map(directive => printDirective(directive, options)), + types.map(type => printType(type, options)), + ) + .filter(Boolean) + .join('\n\n') + '\n' + ); +} + +function printSchemaDefinition(schema: GraphQLSchema): ?string { + if (isSchemaOfCommonNames(schema)) { + return; + } + + const operationTypes = []; + + const queryType = schema.getQueryType(); + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + + const mutationType = schema.getMutationType(); + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + + return `schema {\n${operationTypes.join('\n')}\n}`; +} + +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ +function isSchemaOfCommonNames(schema: GraphQLSchema): boolean { + const queryType = schema.getQueryType(); + if (queryType && queryType.name !== 'Query') { + return false; + } + + const mutationType = schema.getMutationType(); + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + const subscriptionType = schema.getSubscriptionType(); + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +export function printType(type: GraphQLNamedType, options?: Options): string { + if (isScalarType(type)) { + return printScalar(type, options); + } else if (isObjectType(type)) { + return printObject(type, options); + } else if (isInterfaceType(type)) { + return printInterface(type, options); + } else if (isUnionType(type)) { + return printUnion(type, options); + } else if (isEnumType(type)) { + return printEnum(type, options); + } else if (isInputObjectType(type)) { + return printInputObject(type, options); + } + /* istanbul ignore next */ + throw new Error(`Unknown type: ${(type: empty)}.`); +} + +function printScalar(type: GraphQLScalarType, options): string { + return printDescription(options, type) + `scalar ${type.name}`; +} + +function printObject(type: GraphQLObjectType, options): string { + const interfaces = type.getInterfaces(); + const implementedInterfaces = interfaces.length + ? ' implements ' + interfaces.map(i => i.name).join(' & ') + : ''; + return ( + printDescription(options, type) + + `type ${type.name}${implementedInterfaces} {\n` + + printFields(options, type) + + '\n' + + '}' + ); +} + +function printInterface(type: GraphQLInterfaceType, options): string { + return ( + printDescription(options, type) + + `interface ${type.name} {\n` + + printFields(options, type) + + '\n' + + '}' + ); +} + +function printUnion(type: GraphQLUnionType, options): string { + return ( + printDescription(options, type) + + `union ${type.name} = ${type.getTypes().join(' | ')}` + ); +} + +function printEnum(type: GraphQLEnumType, options): string { + return ( + printDescription(options, type) + + `enum ${type.name} {\n` + + printEnumValues(type.getValues(), options) + + '\n' + + '}' + ); +} + +function printEnumValues(values, options): string { + return values + .map( + (value, i) => + printDescription(options, value, ' ', !i) + + ' ' + + value.name + + printDeprecated(value), + ) + .join('\n'); +} + +function printInputObject(type: GraphQLInputObjectType, options): string { + const fields = objectValues(type.getFields()); + return ( + printDescription(options, type) + + `input ${type.name} {\n` + + fields + .map( + (f, i) => + printDescription(options, f, ' ', !i) + ' ' + printInputValue(f), + ) + .join('\n') + + '\n' + + '}' + ); +} + +function printFields(options, type) { + const fields = objectValues(type.getFields()); + return fields + .map( + (f, i) => + printDescription(options, f, ' ', !i) + + ' ' + + f.name + + printArgs(options, f.args, ' ') + + ': ' + + String(f.type) + + printDeprecated(f), + ) + .join('\n'); +} + +function printArgs(options, args, indentation = '') { + if (args.length === 0) { + return ''; + } + + // If every arg does not have a description, print them on one line. + if (args.every(arg => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return ( + '(\n' + + args + .map( + (arg, i) => + printDescription(options, arg, ' ' + indentation, !i) + + ' ' + + indentation + + printInputValue(arg), + ) + .join('\n') + + '\n' + + indentation + + ')' + ); +} + +function printInputValue(arg) { + let argDecl = arg.name + ': ' + String(arg.type); + if (!isInvalid(arg.defaultValue)) { + argDecl += ` = ${print(astFromValue(arg.defaultValue, arg.type))}`; + } + return argDecl; +} + +function printDirective(directive, options) { + return ( + printDescription(options, directive) + + 'directive @' + + directive.name + + printArgs(options, directive.args) + + ' on ' + + directive.locations.join(' | ') + ); +} + +function printDeprecated(fieldOrEnumVal) { + if (!fieldOrEnumVal.isDeprecated) { + return ''; + } + const reason = fieldOrEnumVal.deprecationReason; + if ( + isNullish(reason) || + reason === '' || + reason === DEFAULT_DEPRECATION_REASON + ) { + return ' @deprecated'; + } + return ( + ' @deprecated(reason: ' + print(astFromValue(reason, GraphQLString)) + ')' + ); +} + +function printDescription( + options, + def, + indentation = '', + firstInBlock = true, +): string { + if (!def.description) { + return ''; + } + + const lines = descriptionLines(def.description, 120 - indentation.length); + if (options && options.commentDescriptions) { + return printDescriptionWithComments(lines, indentation, firstInBlock); + } + + let description = + indentation && !firstInBlock + ? '\n' + indentation + '"""' + : indentation + '"""'; + + // In some circumstances, a single line can be used for the description. + if ( + lines.length === 1 && + lines[0].length < 70 && + lines[0][lines[0].length - 1] !== '"' + ) { + return description + escapeQuote(lines[0]) + '"""\n'; + } + + // Format a multi-line block quote to account for leading space. + const hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t'; + if (!hasLeadingSpace) { + description += '\n'; + } + for (let i = 0; i < lines.length; i++) { + if (i !== 0 || !hasLeadingSpace) { + description += indentation; + } + description += escapeQuote(lines[i]) + '\n'; + } + description += indentation + '"""\n'; + return description; +} + +function escapeQuote(line) { + return line.replace(/"""/g, '\\"""'); +} + +function printDescriptionWithComments(lines, indentation, firstInBlock) { + let description = indentation && !firstInBlock ? '\n' : ''; + for (let i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + description += indentation + '# ' + lines[i] + '\n'; + } + } + return description; +} + +function descriptionLines(description: string, maxLen: number): Array { + const lines = []; + const rawLines = description.split('\n'); + for (let i = 0; i < rawLines.length; i++) { + if (rawLines[i] === '') { + lines.push(rawLines[i]); + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + const sublines = breakLine(rawLines[i], maxLen); + for (let j = 0; j < sublines.length; j++) { + lines.push(sublines[j]); + } + } + } + return lines; +} + +function breakLine(line: string, maxLen: number): Array { + if (line.length < maxLen + 5) { + return [line]; + } + const parts = line.split(new RegExp(`((?: |^).{15,${maxLen - 40}}(?= |$))`)); + if (parts.length < 4) { + return [line]; + } + const sublines = [parts[0] + parts[1] + parts[2]]; + for (let i = 3; i < parts.length; i += 2) { + sublines.push(parts[i].slice(1) + parts[i + 1]); + } + return sublines; +} diff --git a/node_modules/graphql/utilities/schemaPrinter.mjs b/node_modules/graphql/utilities/schemaPrinter.mjs new file mode 100644 index 00000000..cfc27d32 --- /dev/null +++ b/node_modules/graphql/utilities/schemaPrinter.mjs @@ -0,0 +1,321 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import isNullish from '../jsutils/isNullish'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { astFromValue } from '../utilities/astFromValue'; +import { print } from '../language/printer'; +import { isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType } from '../type/definition'; +import { GraphQLString, isSpecifiedScalarType } from '../type/scalars'; +import { GraphQLDirective, DEFAULT_DEPRECATION_REASON, isSpecifiedDirective } from '../type/directives'; +import { isIntrospectionType } from '../type/introspection'; + +/** + * Accepts options as a second argument: + * + * - commentDescriptions: + * Provide true to use preceding comments as the description. + * + */ +export function printSchema(schema, options) { + return printFilteredSchema(schema, function (n) { + return !isSpecifiedDirective(n); + }, isDefinedType, options); +} +export function printIntrospectionSchema(schema, options) { + return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType, options); +} + +function isDefinedType(type) { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter, options) { + var directives = schema.getDirectives().filter(directiveFilter); + var typeMap = schema.getTypeMap(); + var types = objectValues(typeMap).sort(function (type1, type2) { + return type1.name.localeCompare(type2.name); + }).filter(typeFilter); + return [printSchemaDefinition(schema)].concat(directives.map(function (directive) { + return printDirective(directive, options); + }), types.map(function (type) { + return printType(type, options); + })).filter(Boolean).join('\n\n') + '\n'; +} + +function printSchemaDefinition(schema) { + if (isSchemaOfCommonNames(schema)) { + return; + } + + var operationTypes = []; + var queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(" query: ".concat(queryType.name)); + } + + var mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(" mutation: ".concat(mutationType.name)); + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(" subscription: ".concat(subscriptionType.name)); + } + + return "schema {\n".concat(operationTypes.join('\n'), "\n}"); +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * schema { + * query: Query + * mutation: Mutation + * } + * + * When using this naming convention, the schema description can be omitted. + */ + + +function isSchemaOfCommonNames(schema) { + var queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + var mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + var subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} + +export function printType(type, options) { + if (isScalarType(type)) { + return printScalar(type, options); + } else if (isObjectType(type)) { + return printObject(type, options); + } else if (isInterfaceType(type)) { + return printInterface(type, options); + } else if (isUnionType(type)) { + return printUnion(type, options); + } else if (isEnumType(type)) { + return printEnum(type, options); + } else if (isInputObjectType(type)) { + return printInputObject(type, options); + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} + +function printScalar(type, options) { + return printDescription(options, type) + "scalar ".concat(type.name); +} + +function printObject(type, options) { + var interfaces = type.getInterfaces(); + var implementedInterfaces = interfaces.length ? ' implements ' + interfaces.map(function (i) { + return i.name; + }).join(' & ') : ''; + return printDescription(options, type) + "type ".concat(type.name).concat(implementedInterfaces, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printInterface(type, options) { + return printDescription(options, type) + "interface ".concat(type.name, " {\n") + printFields(options, type) + '\n' + '}'; +} + +function printUnion(type, options) { + return printDescription(options, type) + "union ".concat(type.name, " = ").concat(type.getTypes().join(' | ')); +} + +function printEnum(type, options) { + return printDescription(options, type) + "enum ".concat(type.name, " {\n") + printEnumValues(type.getValues(), options) + '\n' + '}'; +} + +function printEnumValues(values, options) { + return values.map(function (value, i) { + return printDescription(options, value, ' ', !i) + ' ' + value.name + printDeprecated(value); + }).join('\n'); +} + +function printInputObject(type, options) { + var fields = objectValues(type.getFields()); + return printDescription(options, type) + "input ".concat(type.name, " {\n") + fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + printInputValue(f); + }).join('\n') + '\n' + '}'; +} + +function printFields(options, type) { + var fields = objectValues(type.getFields()); + return fields.map(function (f, i) { + return printDescription(options, f, ' ', !i) + ' ' + f.name + printArgs(options, f.args, ' ') + ': ' + String(f.type) + printDeprecated(f); + }).join('\n'); +} + +function printArgs(options, args) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + + if (args.every(function (arg) { + return !arg.description; + })) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return '(\n' + args.map(function (arg, i) { + return printDescription(options, arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg); + }).join('\n') + '\n' + indentation + ')'; +} + +function printInputValue(arg) { + var argDecl = arg.name + ': ' + String(arg.type); + + if (!isInvalid(arg.defaultValue)) { + argDecl += " = ".concat(print(astFromValue(arg.defaultValue, arg.type))); + } + + return argDecl; +} + +function printDirective(directive, options) { + return printDescription(options, directive) + 'directive @' + directive.name + printArgs(options, directive.args) + ' on ' + directive.locations.join(' | '); +} + +function printDeprecated(fieldOrEnumVal) { + if (!fieldOrEnumVal.isDeprecated) { + return ''; + } + + var reason = fieldOrEnumVal.deprecationReason; + + if (isNullish(reason) || reason === '' || reason === DEFAULT_DEPRECATION_REASON) { + return ' @deprecated'; + } + + return ' @deprecated(reason: ' + print(astFromValue(reason, GraphQLString)) + ')'; +} + +function printDescription(options, def) { + var indentation = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; + var firstInBlock = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; + + if (!def.description) { + return ''; + } + + var lines = descriptionLines(def.description, 120 - indentation.length); + + if (options && options.commentDescriptions) { + return printDescriptionWithComments(lines, indentation, firstInBlock); + } + + var description = indentation && !firstInBlock ? '\n' + indentation + '"""' : indentation + '"""'; // In some circumstances, a single line can be used for the description. + + if (lines.length === 1 && lines[0].length < 70 && lines[0][lines[0].length - 1] !== '"') { + return description + escapeQuote(lines[0]) + '"""\n'; + } // Format a multi-line block quote to account for leading space. + + + var hasLeadingSpace = lines[0][0] === ' ' || lines[0][0] === '\t'; + + if (!hasLeadingSpace) { + description += '\n'; + } + + for (var i = 0; i < lines.length; i++) { + if (i !== 0 || !hasLeadingSpace) { + description += indentation; + } + + description += escapeQuote(lines[i]) + '\n'; + } + + description += indentation + '"""\n'; + return description; +} + +function escapeQuote(line) { + return line.replace(/"""/g, '\\"""'); +} + +function printDescriptionWithComments(lines, indentation, firstInBlock) { + var description = indentation && !firstInBlock ? '\n' : ''; + + for (var i = 0; i < lines.length; i++) { + if (lines[i] === '') { + description += indentation + '#\n'; + } else { + description += indentation + '# ' + lines[i] + '\n'; + } + } + + return description; +} + +function descriptionLines(description, maxLen) { + var lines = []; + var rawLines = description.split('\n'); + + for (var i = 0; i < rawLines.length; i++) { + if (rawLines[i] === '') { + lines.push(rawLines[i]); + } else { + // For > 120 character long lines, cut at space boundaries into sublines + // of ~80 chars. + var sublines = breakLine(rawLines[i], maxLen); + + for (var j = 0; j < sublines.length; j++) { + lines.push(sublines[j]); + } + } + } + + return lines; +} + +function breakLine(line, maxLen) { + if (line.length < maxLen + 5) { + return [line]; + } + + var parts = line.split(new RegExp("((?: |^).{15,".concat(maxLen - 40, "}(?= |$))"))); + + if (parts.length < 4) { + return [line]; + } + + var sublines = [parts[0] + parts[1] + parts[2]]; + + for (var i = 3; i < parts.length; i += 2) { + sublines.push(parts[i].slice(1) + parts[i + 1]); + } + + return sublines; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/separateOperations.js b/node_modules/graphql/utilities/separateOperations.js new file mode 100644 index 00000000..6e129c88 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.js @@ -0,0 +1,103 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.separateOperations = separateOperations; + +var _visitor = require("../language/visitor"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +function separateOperations(documentAST) { + var operations = []; + var fragments = Object.create(null); + var positions = new Map(); + var depGraph = Object.create(null); + var fromName; + var idx = 0; // Populate metadata and build a dependency graph. + + (0, _visitor.visit)(documentAST, { + OperationDefinition: function OperationDefinition(node) { + fromName = opName(node); + operations.push(node); + positions.set(node, idx++); + }, + FragmentDefinition: function FragmentDefinition(node) { + fromName = node.name.value; + fragments[fromName] = node; + positions.set(node, idx++); + }, + FragmentSpread: function FragmentSpread(node) { + var toName = node.name.value; + (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true; + } + }); // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + var separatedDocumentASTs = Object.create(null); + + for (var _i = 0; _i < operations.length; _i++) { + var operation = operations[_i]; + var operationName = opName(operation); + var dependencies = Object.create(null); + collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + var definitions = [operation]; + + var _arr = Object.keys(dependencies); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var name = _arr[_i2]; + definitions.push(fragments[name]); + } + + definitions.sort(function (n1, n2) { + return (positions.get(n1) || 0) - (positions.get(n2) || 0); + }); + separatedDocumentASTs[operationName] = { + kind: 'Document', + definitions: definitions + }; + } + + return separatedDocumentASTs; +} + +// Provides the empty string for anonymous operations. +function opName(operation) { + return operation.name ? operation.name.value : ''; +} // From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. + + +function collectTransitiveDependencies(collected, depGraph, fromName) { + var immediateDeps = depGraph[fromName]; + + if (immediateDeps) { + var _arr2 = Object.keys(immediateDeps); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var toName = _arr2[_i3]; + + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/separateOperations.js.flow b/node_modules/graphql/utilities/separateOperations.js.flow new file mode 100644 index 00000000..0fe8f5b8 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.js.flow @@ -0,0 +1,100 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { visit } from '../language/visitor'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { DocumentNode, OperationDefinitionNode } from '../language/ast'; + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +export function separateOperations( + documentAST: DocumentNode, +): ObjMap { + const operations = []; + const fragments = Object.create(null); + const positions = new Map(); + const depGraph: DepGraph = Object.create(null); + let fromName; + let idx = 0; + + // Populate metadata and build a dependency graph. + visit(documentAST, { + OperationDefinition(node) { + fromName = opName(node); + operations.push(node); + positions.set(node, idx++); + }, + FragmentDefinition(node) { + fromName = node.name.value; + fragments[fromName] = node; + positions.set(node, idx++); + }, + FragmentSpread(node) { + const toName = node.name.value; + (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[ + toName + ] = true; + }, + }); + + // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + const separatedDocumentASTs = Object.create(null); + for (const operation of operations) { + const operationName = opName(operation); + const dependencies = Object.create(null); + collectTransitiveDependencies(dependencies, depGraph, operationName); + + // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + const definitions = [operation]; + for (const name of Object.keys(dependencies)) { + definitions.push(fragments[name]); + } + definitions.sort( + (n1, n2) => (positions.get(n1) || 0) - (positions.get(n2) || 0), + ); + + separatedDocumentASTs[operationName] = { + kind: 'Document', + definitions, + }; + } + + return separatedDocumentASTs; +} + +type DepGraph = ObjMap>; + +// Provides the empty string for anonymous operations. +function opName(operation: OperationDefinitionNode): string { + return operation.name ? operation.name.value : ''; +} + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies( + collected: ObjMap, + depGraph: DepGraph, + fromName: string, +): void { + const immediateDeps = depGraph[fromName]; + if (immediateDeps) { + for (const toName of Object.keys(immediateDeps)) { + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} diff --git a/node_modules/graphql/utilities/separateOperations.mjs b/node_modules/graphql/utilities/separateOperations.mjs new file mode 100644 index 00000000..0de68354 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.mjs @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { visit } from '../language/visitor'; + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + */ +export function separateOperations(documentAST) { + var operations = []; + var fragments = Object.create(null); + var positions = new Map(); + var depGraph = Object.create(null); + var fromName; + var idx = 0; // Populate metadata and build a dependency graph. + + visit(documentAST, { + OperationDefinition: function OperationDefinition(node) { + fromName = opName(node); + operations.push(node); + positions.set(node, idx++); + }, + FragmentDefinition: function FragmentDefinition(node) { + fromName = node.name.value; + fragments[fromName] = node; + positions.set(node, idx++); + }, + FragmentSpread: function FragmentSpread(node) { + var toName = node.name.value; + (depGraph[fromName] || (depGraph[fromName] = Object.create(null)))[toName] = true; + } + }); // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + var separatedDocumentASTs = Object.create(null); + + for (var _i = 0; _i < operations.length; _i++) { + var operation = operations[_i]; + var operationName = opName(operation); + var dependencies = Object.create(null); + collectTransitiveDependencies(dependencies, depGraph, operationName); // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + var definitions = [operation]; + + var _arr = Object.keys(dependencies); + + for (var _i2 = 0; _i2 < _arr.length; _i2++) { + var name = _arr[_i2]; + definitions.push(fragments[name]); + } + + definitions.sort(function (n1, n2) { + return (positions.get(n1) || 0) - (positions.get(n2) || 0); + }); + separatedDocumentASTs[operationName] = { + kind: 'Document', + definitions: definitions + }; + } + + return separatedDocumentASTs; +} + +// Provides the empty string for anonymous operations. +function opName(operation) { + return operation.name ? operation.name.value : ''; +} // From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. + + +function collectTransitiveDependencies(collected, depGraph, fromName) { + var immediateDeps = depGraph[fromName]; + + if (immediateDeps) { + var _arr2 = Object.keys(immediateDeps); + + for (var _i3 = 0; _i3 < _arr2.length; _i3++) { + var toName = _arr2[_i3]; + + if (!collected[toName]) { + collected[toName] = true; + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeComparators.js b/node_modules/graphql/utilities/typeComparators.js new file mode 100644 index 00000000..3a9e9d66 --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.js @@ -0,0 +1,129 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isEqualType = isEqualType; +exports.isTypeSubTypeOf = isTypeSubTypeOf; +exports.doTypesOverlap = doTypesOverlap; + +var _definition = require("../type/definition"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Provided two types, return true if the types are equal (invariant). + */ +function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + + if ((0, _definition.isNonNullType)(typeA) && (0, _definition.isNonNullType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + + if ((0, _definition.isListType)(typeA) && (0, _definition.isListType)(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + + +function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, maybeSubType type may be a currently + // possible object type. + + + if ((0, _definition.isAbstractType)(superType) && (0, _definition.isObjectType)(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) { + return true; + } // Otherwise, the child type is not a valid subtype of the parent type. + + + return false; +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + + +function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema.getPossibleTypes(typeA).some(function (type) { + return schema.isPossibleType(typeB, type); + }); + } // Determine if the latter type is a possible concrete type of the former. + + + return schema.isPossibleType(typeA, typeB); + } + + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isPossibleType(typeB, typeA); + } // Otherwise the types do not overlap. + + + return false; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeComparators.js.flow b/node_modules/graphql/utilities/typeComparators.js.flow new file mode 100644 index 00000000..b903ff4f --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.js.flow @@ -0,0 +1,132 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { + isObjectType, + isListType, + isNonNullType, + isAbstractType, +} from '../type/definition'; +import type { GraphQLType, GraphQLCompositeType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export function isEqualType(typeA: GraphQLType, typeB: GraphQLType): boolean { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } + + // If either type is non-null, the other must also be non-null. + if (isNonNullType(typeA) && isNonNullType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + + // If either type is a list, the other must also be a list. + if (isListType(typeA) && isListType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } + + // Otherwise the types are not equal. + return false; +} + +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ +export function isTypeSubTypeOf( + schema: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType, +): boolean { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } + + // If superType is non-null, maybeSubType must also be non-null. + if (isNonNullType(superType)) { + if (isNonNullType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if (isNonNullType(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } + + // If superType type is a list, maybeSubType type must also be a list. + if (isListType(superType)) { + if (isListType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + return false; + } + if (isListType(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } + + // If superType type is an abstract type, maybeSubType type may be a currently + // possible object type. + if ( + isAbstractType(superType) && + isObjectType(maybeSubType) && + schema.isPossibleType(superType, maybeSubType) + ) { + return true; + } + + // Otherwise, the child type is not a valid subtype of the parent type. + return false; +} + +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ +export function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType, +): boolean { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if (isAbstractType(typeA)) { + if (isAbstractType(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema + .getPossibleTypes(typeA) + .some(type => schema.isPossibleType(typeB, type)); + } + // Determine if the latter type is a possible concrete type of the former. + return schema.isPossibleType(typeA, typeB); + } + + if (isAbstractType(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isPossibleType(typeB, typeA); + } + + // Otherwise the types do not overlap. + return false; +} diff --git a/node_modules/graphql/utilities/typeComparators.mjs b/node_modules/graphql/utilities/typeComparators.mjs new file mode 100644 index 00000000..31a8ac2b --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.mjs @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { isObjectType, isListType, isNonNullType, isAbstractType } from '../type/definition'; + +/** + * Provided two types, return true if the types are equal (invariant). + */ +export function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + + if (isNonNullType(typeA) && isNonNullType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + + if (isListType(typeA) && isListType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + */ + +export function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + + if (isNonNullType(superType)) { + if (isNonNullType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if (isNonNullType(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + + if (isListType(superType)) { + if (isListType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if (isListType(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, maybeSubType type may be a currently + // possible object type. + + + if (isAbstractType(superType) && isObjectType(maybeSubType) && schema.isPossibleType(superType, maybeSubType)) { + return true; + } // Otherwise, the child type is not a valid subtype of the parent type. + + + return false; +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + */ + +export function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if (isAbstractType(typeA)) { + if (isAbstractType(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema.getPossibleTypes(typeA).some(function (type) { + return schema.isPossibleType(typeB, type); + }); + } // Determine if the latter type is a possible concrete type of the former. + + + return schema.isPossibleType(typeA, typeB); + } + + if (isAbstractType(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isPossibleType(typeB, typeA); + } // Otherwise the types do not overlap. + + + return false; +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeFromAST.js b/node_modules/graphql/utilities/typeFromAST.js new file mode 100644 index 00000000..a6201ac1 --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeFromAST = typeFromAST; + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType; + + if (typeNode.kind === _kinds.Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && (0, _definition.GraphQLList)(innerType); + } + + if (typeNode.kind === _kinds.Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && (0, _definition.GraphQLNonNull)(innerType); + } + + if (typeNode.kind === _kinds.Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type kind: ".concat(typeNode.kind, ".")); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/typeFromAST.js.flow b/node_modules/graphql/utilities/typeFromAST.js.flow new file mode 100644 index 00000000..596e16f9 --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.js.flow @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import { Kind } from '../language/kinds'; +import type { + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, +} from '../language/ast'; +import { GraphQLList, GraphQLNonNull } from '../type/definition'; +import type { GraphQLNamedType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; + +/** + * Given a Schema and an AST node describing a type, return a GraphQLType + * definition which applies to that type. For example, if provided the parsed + * AST node for `[User]`, a GraphQLList instance will be returned, containing + * the type called "User" found in the schema. If a type called "User" is not + * found in the schema, then undefined will be returned. + */ +/* eslint-disable no-redeclare */ +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NamedTypeNode, +): GraphQLNamedType | void; +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: ListTypeNode, +): GraphQLList | void; +declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NonNullTypeNode, +): GraphQLNonNull | void; +export function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + let innerType; + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLList(innerType); + } + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLNonNull(innerType); + } + if (typeNode.kind === Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + /* istanbul ignore next */ + throw new Error(`Unexpected type kind: ${(typeNode.kind: empty)}.`); +} diff --git a/node_modules/graphql/utilities/typeFromAST.mjs b/node_modules/graphql/utilities/typeFromAST.mjs new file mode 100644 index 00000000..e1dee0d2 --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.mjs @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { Kind } from '../language/kinds'; +import { GraphQLList, GraphQLNonNull } from '../type/definition'; +export function typeFromAST(schema, typeNode) { + /* eslint-enable no-redeclare */ + var innerType; + + if (typeNode.kind === Kind.LIST_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLList(innerType); + } + + if (typeNode.kind === Kind.NON_NULL_TYPE) { + innerType = typeFromAST(schema, typeNode.type); + return innerType && GraphQLNonNull(innerType); + } + + if (typeNode.kind === Kind.NAMED_TYPE) { + return schema.getType(typeNode.name.value); + } + /* istanbul ignore next */ + + + throw new Error("Unexpected type kind: ".concat(typeNode.kind, ".")); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromAST.js b/node_modules/graphql/utilities/valueFromAST.js new file mode 100644 index 00000000..420999e8 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.js @@ -0,0 +1,207 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromAST = valueFromAST; + +var _keyMap = _interopRequireDefault(require("../jsutils/keyMap")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _objectValues = _interopRequireDefault(require("../jsutils/objectValues")); + +var _kinds = require("../language/kinds"); + +var _definition = require("../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. + } + + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === _kinds.Kind.VARIABLE) { + var variableName = valueNode.name.value; + + if (!variables || (0, _isInvalid.default)(variables[variableName])) { + // No valid return value. + return; + } + + var variableValue = variables[variableName]; + + if (variableValue === null && (0, _definition.isNonNullType)(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + + return variableValue; + } + + if ((0, _definition.isListType)(type)) { + var itemType = type.ofType; + + if (valueNode.kind === _kinds.Kind.LIST) { + var coercedValues = []; + var itemNodes = valueNode.values; + + for (var i = 0; i < itemNodes.length; i++) { + if (isMissingVariable(itemNodes[i], variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + var itemValue = valueFromAST(itemNodes[i], itemType, variables); + + if ((0, _isInvalid.default)(itemValue)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + var coercedValue = valueFromAST(valueNode, itemType, variables); + + if ((0, _isInvalid.default)(coercedValue)) { + return; // Invalid: intentionally return no value. + } + + return [coercedValue]; + } + + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + + var coercedObj = Object.create(null); + var fieldNodes = (0, _keyMap.default)(valueNode.fields, function (field) { + return field.name.value; + }); + var fields = (0, _objectValues.default)(type.getFields()); + + for (var _i = 0; _i < fields.length; _i++) { + var field = fields[_i]; + var fieldNode = fieldNodes[field.name]; + + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } + + continue; + } + + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if ((0, _isInvalid.default)(fieldValue)) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + return coercedObj; + } + + if ((0, _definition.isEnumType)(type)) { + if (valueNode.kind !== _kinds.Kind.ENUM) { + return; // Invalid: intentionally return no value. + } + + var enumValue = type.getValue(valueNode.value); + + if (!enumValue) { + return; // Invalid: intentionally return no value. + } + + return enumValue.value; + } + + if ((0, _definition.isScalarType)(type)) { + // Scalars fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + var result; + + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + + if ((0, _isInvalid.default)(result)) { + return; // Invalid: intentionally return no value. + } + + return result; + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + + +function isMissingVariable(valueNode, variables) { + return valueNode.kind === _kinds.Kind.VARIABLE && (!variables || (0, _isInvalid.default)(variables[valueNode.name.value])); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromAST.js.flow b/node_modules/graphql/utilities/valueFromAST.js.flow new file mode 100644 index 00000000..f198d1fc --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.js.flow @@ -0,0 +1,179 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import keyMap from '../jsutils/keyMap'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { Kind } from '../language/kinds'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, +} from '../type/definition'; +import type { GraphQLInputType } from '../type/definition'; +import type { ValueNode } from '../language/ast'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST( + valueNode: ?ValueNode, + type: GraphQLInputType, + variables?: ?ObjMap, +): mixed | void { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if (isNonNullType(type)) { + if (valueNode.kind === Kind.NULL) { + return; // Invalid: intentionally return no value. + } + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === Kind.VARIABLE) { + const variableName = valueNode.name.value; + if (!variables || isInvalid(variables[variableName])) { + // No valid return value. + return; + } + const variableValue = variables[variableName]; + if (variableValue === null && isNonNullType(type)) { + return; // Invalid: intentionally return no value. + } + // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + return variableValue; + } + + if (isListType(type)) { + const itemType = type.ofType; + if (valueNode.kind === Kind.LIST) { + const coercedValues = []; + const itemNodes = valueNode.values; + for (let i = 0; i < itemNodes.length; i++) { + if (isMissingVariable(itemNodes[i], variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if (isNonNullType(itemType)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNodes[i], itemType, variables); + if (isInvalid(itemValue)) { + return; // Invalid: intentionally return no value. + } + coercedValues.push(itemValue); + } + } + return coercedValues; + } + const coercedValue = valueFromAST(valueNode, itemType, variables); + if (isInvalid(coercedValue)) { + return; // Invalid: intentionally return no value. + } + return [coercedValue]; + } + + if (isInputObjectType(type)) { + if (valueNode.kind !== Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + const coercedObj = Object.create(null); + const fieldNodes = keyMap(valueNode.fields, field => field.name.value); + const fields = objectValues(type.getFields()); + for (let i = 0; i < fields.length; i++) { + const field = fields[i]; + const fieldNode = fieldNodes[field.name]; + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + return; // Invalid: intentionally return no value. + } + continue; + } + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + if (isInvalid(fieldValue)) { + return; // Invalid: intentionally return no value. + } + coercedObj[field.name] = fieldValue; + } + return coercedObj; + } + + if (isEnumType(type)) { + if (valueNode.kind !== Kind.ENUM) { + return; // Invalid: intentionally return no value. + } + const enumValue = type.getValue(valueNode.value); + if (!enumValue) { + return; // Invalid: intentionally return no value. + } + return enumValue.value; + } + + if (isScalarType(type)) { + // Scalars fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + if (isInvalid(result)) { + return; // Invalid: intentionally return no value. + } + return result; + } + + /* istanbul ignore next */ + throw new Error(`Unknown type: ${(type: empty)}.`); +} + +// Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. +function isMissingVariable(valueNode, variables) { + return ( + valueNode.kind === Kind.VARIABLE && + (!variables || isInvalid(variables[valueNode.name.value])) + ); +} diff --git a/node_modules/graphql/utilities/valueFromAST.mjs b/node_modules/graphql/utilities/valueFromAST.mjs new file mode 100644 index 00000000..5ac56952 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.mjs @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import keyMap from '../jsutils/keyMap'; +import isInvalid from '../jsutils/isInvalid'; +import objectValues from '../jsutils/objectValues'; +import { Kind } from '../language/kinds'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType } from '../type/definition'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Mixed | + * | NullValue | null | + * + */ +export function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if (isNonNullType(type)) { + if (valueNode.kind === Kind.NULL) { + return; // Invalid: intentionally return no value. + } + + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (valueNode.kind === Kind.VARIABLE) { + var variableName = valueNode.name.value; + + if (!variables || isInvalid(variables[variableName])) { + // No valid return value. + return; + } + + var variableValue = variables[variableName]; + + if (variableValue === null && isNonNullType(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + + return variableValue; + } + + if (isListType(type)) { + var itemType = type.ofType; + + if (valueNode.kind === Kind.LIST) { + var coercedValues = []; + var itemNodes = valueNode.values; + + for (var i = 0; i < itemNodes.length; i++) { + if (isMissingVariable(itemNodes[i], variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if (isNonNullType(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + var itemValue = valueFromAST(itemNodes[i], itemType, variables); + + if (isInvalid(itemValue)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + var coercedValue = valueFromAST(valueNode, itemType, variables); + + if (isInvalid(coercedValue)) { + return; // Invalid: intentionally return no value. + } + + return [coercedValue]; + } + + if (isInputObjectType(type)) { + if (valueNode.kind !== Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + + var coercedObj = Object.create(null); + var fieldNodes = keyMap(valueNode.fields, function (field) { + return field.name.value; + }); + var fields = objectValues(type.getFields()); + + for (var _i = 0; _i < fields.length; _i++) { + var field = fields[_i]; + var fieldNode = fieldNodes[field.name]; + + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + return; // Invalid: intentionally return no value. + } + + continue; + } + + var fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if (isInvalid(fieldValue)) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + return coercedObj; + } + + if (isEnumType(type)) { + if (valueNode.kind !== Kind.ENUM) { + return; // Invalid: intentionally return no value. + } + + var enumValue = type.getValue(valueNode.value); + + if (!enumValue) { + return; // Invalid: intentionally return no value. + } + + return enumValue.value; + } + + if (isScalarType(type)) { + // Scalars fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + var result; + + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + + if (isInvalid(result)) { + return; // Invalid: intentionally return no value. + } + + return result; + } + /* istanbul ignore next */ + + + throw new Error("Unknown type: ".concat(type, ".")); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + +function isMissingVariable(valueNode, variables) { + return valueNode.kind === Kind.VARIABLE && (!variables || isInvalid(variables[valueNode.name.value])); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.js b/node_modules/graphql/utilities/valueFromASTUntyped.js new file mode 100644 index 00000000..8c289b56 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.js @@ -0,0 +1,77 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.valueFromASTUntyped = valueFromASTUntyped; + +var _keyValMap = _interopRequireDefault(require("../jsutils/keyValMap")); + +var _isInvalid = _interopRequireDefault(require("../jsutils/isInvalid")); + +var _kinds = require("../language/kinds"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; + + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); + + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); + + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; + + case _kinds.Kind.LIST: + return valueNode.values.map(function (node) { + return valueFromASTUntyped(node, variables); + }); + + case _kinds.Kind.OBJECT: + return (0, _keyValMap.default)(valueNode.fields, function (field) { + return field.name.value; + }, function (field) { + return valueFromASTUntyped(field.value, variables); + }); + + case _kinds.Kind.VARIABLE: + var variableName = valueNode.name.value; + return variables && !(0, _isInvalid.default)(variables[variableName]) ? variables[variableName] : undefined; + } + /* istanbul ignore next */ + + + throw new Error('Unexpected value kind: ' + valueNode.kind); +} \ No newline at end of file diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.js.flow b/node_modules/graphql/utilities/valueFromASTUntyped.js.flow new file mode 100644 index 00000000..3ed6558d --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.js.flow @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import keyValMap from '../jsutils/keyValMap'; +import isInvalid from '../jsutils/isInvalid'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { Kind } from '../language/kinds'; +import type { ValueNode } from '../language/ast'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +export function valueFromASTUntyped( + valueNode: ValueNode, + variables?: ?ObjMap, +): mixed { + switch (valueNode.kind) { + case Kind.NULL: + return null; + case Kind.INT: + return parseInt(valueNode.value, 10); + case Kind.FLOAT: + return parseFloat(valueNode.value); + case Kind.STRING: + case Kind.ENUM: + case Kind.BOOLEAN: + return valueNode.value; + case Kind.LIST: + return valueNode.values.map(node => valueFromASTUntyped(node, variables)); + case Kind.OBJECT: + return keyValMap( + valueNode.fields, + field => field.name.value, + field => valueFromASTUntyped(field.value, variables), + ); + case Kind.VARIABLE: + const variableName = valueNode.name.value; + return variables && !isInvalid(variables[variableName]) + ? variables[variableName] + : undefined; + } + /* istanbul ignore next */ + throw new Error('Unexpected value kind: ' + (valueNode.kind: empty)); +} diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.mjs b/node_modules/graphql/utilities/valueFromASTUntyped.mjs new file mode 100644 index 00000000..2f56d73e --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.mjs @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import keyValMap from '../jsutils/keyValMap'; +import isInvalid from '../jsutils/isInvalid'; +import { Kind } from '../language/kinds'; + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Unlike `valueFromAST()`, no type is provided. The resulting JavaScript value + * will reflect the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * + */ +export function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case Kind.NULL: + return null; + + case Kind.INT: + return parseInt(valueNode.value, 10); + + case Kind.FLOAT: + return parseFloat(valueNode.value); + + case Kind.STRING: + case Kind.ENUM: + case Kind.BOOLEAN: + return valueNode.value; + + case Kind.LIST: + return valueNode.values.map(function (node) { + return valueFromASTUntyped(node, variables); + }); + + case Kind.OBJECT: + return keyValMap(valueNode.fields, function (field) { + return field.name.value; + }, function (field) { + return valueFromASTUntyped(field.value, variables); + }); + + case Kind.VARIABLE: + var variableName = valueNode.name.value; + return variables && !isInvalid(variables[variableName]) ? variables[variableName] : undefined; + } + /* istanbul ignore next */ + + + throw new Error('Unexpected value kind: ' + valueNode.kind); +} \ No newline at end of file diff --git a/node_modules/graphql/validation/ValidationContext.js b/node_modules/graphql/validation/ValidationContext.js new file mode 100644 index 00000000..d69974f5 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.js @@ -0,0 +1,272 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ValidationContext = exports.SDLValidationContext = exports.ASTValidationContext = void 0; + +var _visitor = require("../language/visitor"); + +var _kinds = require("../language/kinds"); + +var _TypeInfo = require("../utilities/TypeInfo"); + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +var ASTValidationContext = +/*#__PURE__*/ +function () { + function ASTValidationContext(ast) { + _defineProperty(this, "_ast", void 0); + + _defineProperty(this, "_errors", void 0); + + this._ast = ast; + this._errors = []; + } + + var _proto = ASTValidationContext.prototype; + + _proto.reportError = function reportError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + _proto.getDocument = function getDocument() { + return this._ast; + }; + + return ASTValidationContext; +}(); + +exports.ASTValidationContext = ASTValidationContext; + +var SDLValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext) { + _inheritsLoose(SDLValidationContext, _ASTValidationContext); + + function SDLValidationContext(ast, schema) { + var _this; + + _this = _ASTValidationContext.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_schema", void 0); + + _this._schema = schema; + return _this; + } + + var _proto2 = SDLValidationContext.prototype; + + _proto2.getSchema = function getSchema() { + return this._schema; + }; + + return SDLValidationContext; +}(ASTValidationContext); + +exports.SDLValidationContext = SDLValidationContext; + +var ValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext2) { + _inheritsLoose(ValidationContext, _ASTValidationContext2); + + function ValidationContext(schema, ast, typeInfo) { + var _this2; + + _this2 = _ASTValidationContext2.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_schema", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_typeInfo", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragmentSpreads", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursivelyReferencedFragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_variableUsages", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursiveVariableUsages", void 0); + + _this2._schema = schema; + _this2._typeInfo = typeInfo; + _this2._fragmentSpreads = new Map(); + _this2._recursivelyReferencedFragments = new Map(); + _this2._variableUsages = new Map(); + _this2._recursiveVariableUsages = new Map(); + return _this2; + } + + var _proto3 = ValidationContext.prototype; + + _proto3.getSchema = function getSchema() { + return this._schema; + }; + + _proto3.getFragment = function getFragment(name) { + var fragments = this._fragments; + + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + + return frags; + }, Object.create(null)); + } + + return fragments[name]; + }; + + _proto3.getFragmentSpreads = function getFragmentSpreads(node) { + var spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + var setsToVisit = [node]; + + while (setsToVisit.length !== 0) { + var set = setsToVisit.pop(); + + for (var i = 0; i < set.selections.length; i++) { + var selection = set.selections[i]; + + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + }; + + _proto3.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) { + var fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + var collectedNames = Object.create(null); + var nodesToVisit = [operation.selectionSet]; + + while (nodesToVisit.length !== 0) { + var node = nodesToVisit.pop(); + var spreads = this.getFragmentSpreads(node); + + for (var i = 0; i < spreads.length; i++) { + var fragName = spreads[i].name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + var fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + }; + + _proto3.getVariableUsages = function getVariableUsages(node) { + var usages = this._variableUsages.get(node); + + if (!usages) { + var newUsages = []; + var typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)(node, (0, _visitor.visitWithTypeInfo)(typeInfo, { + VariableDefinition: function VariableDefinition() { + return false; + }, + Variable: function Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + }; + + _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) { + var usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + var fragments = this.getRecursivelyReferencedFragments(operation); + + for (var i = 0; i < fragments.length; i++) { + Array.prototype.push.apply(usages, this.getVariableUsages(fragments[i])); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + }; + + _proto3.getType = function getType() { + return this._typeInfo.getType(); + }; + + _proto3.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + _proto3.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + _proto3.getParentInputType = function getParentInputType() { + return this._typeInfo.getParentInputType(); + }; + + _proto3.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + _proto3.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + _proto3.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + return ValidationContext; +}(ASTValidationContext); + +exports.ValidationContext = ValidationContext; \ No newline at end of file diff --git a/node_modules/graphql/validation/ValidationContext.js.flow b/node_modules/graphql/validation/ValidationContext.js.flow new file mode 100644 index 00000000..27b52439 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.js.flow @@ -0,0 +1,254 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ObjMap } from '../jsutils/ObjMap'; +import type { GraphQLError } from '../error'; +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { Kind } from '../language/kinds'; +import type { + DocumentNode, + OperationDefinitionNode, + VariableNode, + SelectionSetNode, + FragmentSpreadNode, + FragmentDefinitionNode, +} from '../language/ast'; +import type { ASTVisitor } from '../language/visitor'; +import type { GraphQLSchema } from '../type/schema'; +import type { + GraphQLInputType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, + GraphQLArgument, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import { TypeInfo } from '../utilities/TypeInfo'; + +type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; +type VariableUsage = {| + +node: VariableNode, + +type: ?GraphQLInputType, + +defaultValue: ?mixed, +|}; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export class ASTValidationContext { + _ast: DocumentNode; + _errors: Array; + + constructor(ast: DocumentNode): void { + this._ast = ast; + this._errors = []; + } + + reportError(error: GraphQLError): void { + this._errors.push(error); + } + + getErrors(): $ReadOnlyArray { + return this._errors; + } + + getDocument(): DocumentNode { + return this._ast; + } +} + +export class SDLValidationContext extends ASTValidationContext { + _schema: ?GraphQLSchema; + + constructor(ast: DocumentNode, schema?: ?GraphQLSchema): void { + super(ast); + this._schema = schema; + } + + getSchema(): ?GraphQLSchema { + return this._schema; + } +} + +export type SDLValidationRule = SDLValidationContext => ASTVisitor; + +export class ValidationContext extends ASTValidationContext { + _schema: GraphQLSchema; + _typeInfo: TypeInfo; + _fragments: ObjMap; + _fragmentSpreads: Map>; + _recursivelyReferencedFragments: Map< + OperationDefinitionNode, + $ReadOnlyArray, + >; + _variableUsages: Map>; + _recursiveVariableUsages: Map< + OperationDefinitionNode, + $ReadOnlyArray, + >; + + constructor( + schema: GraphQLSchema, + ast: DocumentNode, + typeInfo: TypeInfo, + ): void { + super(ast); + this._schema = schema; + this._typeInfo = typeInfo; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + + getSchema(): GraphQLSchema { + return this._schema; + } + + getFragment(name: string): ?FragmentDefinitionNode { + let fragments = this._fragments; + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce( + (frags, statement) => { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + return frags; + }, + Object.create(null), + ); + } + return fragments[name]; + } + + getFragmentSpreads( + node: SelectionSetNode, + ): $ReadOnlyArray { + let spreads = this._fragmentSpreads.get(node); + if (!spreads) { + spreads = []; + const setsToVisit: Array = [node]; + while (setsToVisit.length !== 0) { + const set = setsToVisit.pop(); + for (let i = 0; i < set.selections.length; i++) { + const selection = set.selections[i]; + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + this._fragmentSpreads.set(node, spreads); + } + return spreads; + } + + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): $ReadOnlyArray { + let fragments = this._recursivelyReferencedFragments.get(operation); + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit: Array = [operation.selectionSet]; + while (nodesToVisit.length !== 0) { + const node = nodesToVisit.pop(); + const spreads = this.getFragmentSpreads(node); + for (let i = 0; i < spreads.length; i++) { + const fragName = spreads[i].name.value; + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + this._recursivelyReferencedFragments.set(operation, fragments); + } + return fragments; + } + + getVariableUsages(node: NodeWithSelectionSet): $ReadOnlyArray { + let usages = this._variableUsages.get(node); + if (!usages) { + const newUsages = []; + const typeInfo = new TypeInfo(this._schema); + visit( + node, + visitWithTypeInfo(typeInfo, { + VariableDefinition: () => false, + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + }); + }, + }), + ); + usages = newUsages; + this._variableUsages.set(node, usages); + } + return usages; + } + + getRecursiveVariableUsages( + operation: OperationDefinitionNode, + ): $ReadOnlyArray { + let usages = this._recursiveVariableUsages.get(operation); + if (!usages) { + usages = this.getVariableUsages(operation); + const fragments = this.getRecursivelyReferencedFragments(operation); + for (let i = 0; i < fragments.length; i++) { + Array.prototype.push.apply( + usages, + this.getVariableUsages(fragments[i]), + ); + } + this._recursiveVariableUsages.set(operation, usages); + } + return usages; + } + + getType(): ?GraphQLOutputType { + return this._typeInfo.getType(); + } + + getParentType(): ?GraphQLCompositeType { + return this._typeInfo.getParentType(); + } + + getInputType(): ?GraphQLInputType { + return this._typeInfo.getInputType(); + } + + getParentInputType(): ?GraphQLInputType { + return this._typeInfo.getParentInputType(); + } + + getFieldDef(): ?GraphQLField<*, *> { + return this._typeInfo.getFieldDef(); + } + + getDirective(): ?GraphQLDirective { + return this._typeInfo.getDirective(); + } + + getArgument(): ?GraphQLArgument { + return this._typeInfo.getArgument(); + } +} + +export type ValidationRule = ValidationContext => ASTVisitor; diff --git a/node_modules/graphql/validation/ValidationContext.mjs b/node_modules/graphql/validation/ValidationContext.mjs new file mode 100644 index 00000000..f4150735 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.mjs @@ -0,0 +1,263 @@ +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { visit, visitWithTypeInfo } from '../language/visitor'; +import { Kind } from '../language/kinds'; +import { TypeInfo } from '../utilities/TypeInfo'; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + */ +export var ASTValidationContext = +/*#__PURE__*/ +function () { + function ASTValidationContext(ast) { + _defineProperty(this, "_ast", void 0); + + _defineProperty(this, "_errors", void 0); + + this._ast = ast; + this._errors = []; + } + + var _proto = ASTValidationContext.prototype; + + _proto.reportError = function reportError(error) { + this._errors.push(error); + }; + + _proto.getErrors = function getErrors() { + return this._errors; + }; + + _proto.getDocument = function getDocument() { + return this._ast; + }; + + return ASTValidationContext; +}(); +export var SDLValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext) { + _inheritsLoose(SDLValidationContext, _ASTValidationContext); + + function SDLValidationContext(ast, schema) { + var _this; + + _this = _ASTValidationContext.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this)), "_schema", void 0); + + _this._schema = schema; + return _this; + } + + var _proto2 = SDLValidationContext.prototype; + + _proto2.getSchema = function getSchema() { + return this._schema; + }; + + return SDLValidationContext; +}(ASTValidationContext); +export var ValidationContext = +/*#__PURE__*/ +function (_ASTValidationContext2) { + _inheritsLoose(ValidationContext, _ASTValidationContext2); + + function ValidationContext(schema, ast, typeInfo) { + var _this2; + + _this2 = _ASTValidationContext2.call(this, ast) || this; + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_schema", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_typeInfo", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_fragmentSpreads", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursivelyReferencedFragments", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_variableUsages", void 0); + + _defineProperty(_assertThisInitialized(_assertThisInitialized(_this2)), "_recursiveVariableUsages", void 0); + + _this2._schema = schema; + _this2._typeInfo = typeInfo; + _this2._fragmentSpreads = new Map(); + _this2._recursivelyReferencedFragments = new Map(); + _this2._variableUsages = new Map(); + _this2._recursiveVariableUsages = new Map(); + return _this2; + } + + var _proto3 = ValidationContext.prototype; + + _proto3.getSchema = function getSchema() { + return this._schema; + }; + + _proto3.getFragment = function getFragment(name) { + var fragments = this._fragments; + + if (!fragments) { + this._fragments = fragments = this.getDocument().definitions.reduce(function (frags, statement) { + if (statement.kind === Kind.FRAGMENT_DEFINITION) { + frags[statement.name.value] = statement; + } + + return frags; + }, Object.create(null)); + } + + return fragments[name]; + }; + + _proto3.getFragmentSpreads = function getFragmentSpreads(node) { + var spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + var setsToVisit = [node]; + + while (setsToVisit.length !== 0) { + var set = setsToVisit.pop(); + + for (var i = 0; i < set.selections.length; i++) { + var selection = set.selections[i]; + + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + }; + + _proto3.getRecursivelyReferencedFragments = function getRecursivelyReferencedFragments(operation) { + var fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + var collectedNames = Object.create(null); + var nodesToVisit = [operation.selectionSet]; + + while (nodesToVisit.length !== 0) { + var node = nodesToVisit.pop(); + var spreads = this.getFragmentSpreads(node); + + for (var i = 0; i < spreads.length; i++) { + var fragName = spreads[i].name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + var fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + }; + + _proto3.getVariableUsages = function getVariableUsages(node) { + var usages = this._variableUsages.get(node); + + if (!usages) { + var newUsages = []; + var typeInfo = new TypeInfo(this._schema); + visit(node, visitWithTypeInfo(typeInfo, { + VariableDefinition: function VariableDefinition() { + return false; + }, + Variable: function Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue() + }); + } + })); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + }; + + _proto3.getRecursiveVariableUsages = function getRecursiveVariableUsages(operation) { + var usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + var fragments = this.getRecursivelyReferencedFragments(operation); + + for (var i = 0; i < fragments.length; i++) { + Array.prototype.push.apply(usages, this.getVariableUsages(fragments[i])); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + }; + + _proto3.getType = function getType() { + return this._typeInfo.getType(); + }; + + _proto3.getParentType = function getParentType() { + return this._typeInfo.getParentType(); + }; + + _proto3.getInputType = function getInputType() { + return this._typeInfo.getInputType(); + }; + + _proto3.getParentInputType = function getParentInputType() { + return this._typeInfo.getParentInputType(); + }; + + _proto3.getFieldDef = function getFieldDef() { + return this._typeInfo.getFieldDef(); + }; + + _proto3.getDirective = function getDirective() { + return this._typeInfo.getDirective(); + }; + + _proto3.getArgument = function getArgument() { + return this._typeInfo.getArgument(); + }; + + return ValidationContext; +}(ASTValidationContext); \ No newline at end of file diff --git a/node_modules/graphql/validation/index.js b/node_modules/graphql/validation/index.js new file mode 100644 index 00000000..f981d60b --- /dev/null +++ b/node_modules/graphql/validation/index.js @@ -0,0 +1,229 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "validate", { + enumerable: true, + get: function get() { + return _validate.validate; + } +}); +Object.defineProperty(exports, "ValidationContext", { + enumerable: true, + get: function get() { + return _ValidationContext.ValidationContext; + } +}); +Object.defineProperty(exports, "specifiedRules", { + enumerable: true, + get: function get() { + return _specifiedRules.specifiedRules; + } +}); +Object.defineProperty(exports, "FieldsOnCorrectTypeRule", { + enumerable: true, + get: function get() { + return _FieldsOnCorrectType.FieldsOnCorrectType; + } +}); +Object.defineProperty(exports, "FragmentsOnCompositeTypesRule", { + enumerable: true, + get: function get() { + return _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes; + } +}); +Object.defineProperty(exports, "KnownArgumentNamesRule", { + enumerable: true, + get: function get() { + return _KnownArgumentNames.KnownArgumentNames; + } +}); +Object.defineProperty(exports, "KnownDirectivesRule", { + enumerable: true, + get: function get() { + return _KnownDirectives.KnownDirectives; + } +}); +Object.defineProperty(exports, "KnownFragmentNamesRule", { + enumerable: true, + get: function get() { + return _KnownFragmentNames.KnownFragmentNames; + } +}); +Object.defineProperty(exports, "KnownTypeNamesRule", { + enumerable: true, + get: function get() { + return _KnownTypeNames.KnownTypeNames; + } +}); +Object.defineProperty(exports, "LoneAnonymousOperationRule", { + enumerable: true, + get: function get() { + return _LoneAnonymousOperation.LoneAnonymousOperation; + } +}); +Object.defineProperty(exports, "NoFragmentCyclesRule", { + enumerable: true, + get: function get() { + return _NoFragmentCycles.NoFragmentCycles; + } +}); +Object.defineProperty(exports, "NoUndefinedVariablesRule", { + enumerable: true, + get: function get() { + return _NoUndefinedVariables.NoUndefinedVariables; + } +}); +Object.defineProperty(exports, "NoUnusedFragmentsRule", { + enumerable: true, + get: function get() { + return _NoUnusedFragments.NoUnusedFragments; + } +}); +Object.defineProperty(exports, "NoUnusedVariablesRule", { + enumerable: true, + get: function get() { + return _NoUnusedVariables.NoUnusedVariables; + } +}); +Object.defineProperty(exports, "OverlappingFieldsCanBeMergedRule", { + enumerable: true, + get: function get() { + return _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged; + } +}); +Object.defineProperty(exports, "PossibleFragmentSpreadsRule", { + enumerable: true, + get: function get() { + return _PossibleFragmentSpreads.PossibleFragmentSpreads; + } +}); +Object.defineProperty(exports, "ProvidedRequiredArgumentsRule", { + enumerable: true, + get: function get() { + return _ProvidedRequiredArguments.ProvidedRequiredArguments; + } +}); +Object.defineProperty(exports, "ScalarLeafsRule", { + enumerable: true, + get: function get() { + return _ScalarLeafs.ScalarLeafs; + } +}); +Object.defineProperty(exports, "SingleFieldSubscriptionsRule", { + enumerable: true, + get: function get() { + return _SingleFieldSubscriptions.SingleFieldSubscriptions; + } +}); +Object.defineProperty(exports, "UniqueArgumentNamesRule", { + enumerable: true, + get: function get() { + return _UniqueArgumentNames.UniqueArgumentNames; + } +}); +Object.defineProperty(exports, "UniqueDirectivesPerLocationRule", { + enumerable: true, + get: function get() { + return _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation; + } +}); +Object.defineProperty(exports, "UniqueFragmentNamesRule", { + enumerable: true, + get: function get() { + return _UniqueFragmentNames.UniqueFragmentNames; + } +}); +Object.defineProperty(exports, "UniqueInputFieldNamesRule", { + enumerable: true, + get: function get() { + return _UniqueInputFieldNames.UniqueInputFieldNames; + } +}); +Object.defineProperty(exports, "UniqueOperationNamesRule", { + enumerable: true, + get: function get() { + return _UniqueOperationNames.UniqueOperationNames; + } +}); +Object.defineProperty(exports, "UniqueVariableNamesRule", { + enumerable: true, + get: function get() { + return _UniqueVariableNames.UniqueVariableNames; + } +}); +Object.defineProperty(exports, "ValuesOfCorrectTypeRule", { + enumerable: true, + get: function get() { + return _ValuesOfCorrectType.ValuesOfCorrectType; + } +}); +Object.defineProperty(exports, "VariablesAreInputTypesRule", { + enumerable: true, + get: function get() { + return _VariablesAreInputTypes.VariablesAreInputTypes; + } +}); +Object.defineProperty(exports, "VariablesInAllowedPositionRule", { + enumerable: true, + get: function get() { + return _VariablesInAllowedPosition.VariablesInAllowedPosition; + } +}); + +var _validate = require("./validate"); + +var _ValidationContext = require("./ValidationContext"); + +var _specifiedRules = require("./specifiedRules"); + +var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType"); + +var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes"); + +var _KnownArgumentNames = require("./rules/KnownArgumentNames"); + +var _KnownDirectives = require("./rules/KnownDirectives"); + +var _KnownFragmentNames = require("./rules/KnownFragmentNames"); + +var _KnownTypeNames = require("./rules/KnownTypeNames"); + +var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation"); + +var _NoFragmentCycles = require("./rules/NoFragmentCycles"); + +var _NoUndefinedVariables = require("./rules/NoUndefinedVariables"); + +var _NoUnusedFragments = require("./rules/NoUnusedFragments"); + +var _NoUnusedVariables = require("./rules/NoUnusedVariables"); + +var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged"); + +var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads"); + +var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments"); + +var _ScalarLeafs = require("./rules/ScalarLeafs"); + +var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions"); + +var _UniqueArgumentNames = require("./rules/UniqueArgumentNames"); + +var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation"); + +var _UniqueFragmentNames = require("./rules/UniqueFragmentNames"); + +var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames"); + +var _UniqueOperationNames = require("./rules/UniqueOperationNames"); + +var _UniqueVariableNames = require("./rules/UniqueVariableNames"); + +var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType"); + +var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes"); + +var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition"); \ No newline at end of file diff --git a/node_modules/graphql/validation/index.js.flow b/node_modules/graphql/validation/index.js.flow new file mode 100644 index 00000000..61b0b360 --- /dev/null +++ b/node_modules/graphql/validation/index.js.flow @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +export { validate } from './validate'; + +export { ValidationContext } from './ValidationContext'; +export type { ValidationRule } from './ValidationContext'; + +export { specifiedRules } from './specifiedRules'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +export { + FieldsOnCorrectType as FieldsOnCorrectTypeRule, +} from './rules/FieldsOnCorrectType'; + +// Spec Section: "Fragments on Composite Types" +export { + FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule, +} from './rules/FragmentsOnCompositeTypes'; + +// Spec Section: "Argument Names" +export { + KnownArgumentNames as KnownArgumentNamesRule, +} from './rules/KnownArgumentNames'; + +// Spec Section: "Directives Are Defined" +export { + KnownDirectives as KnownDirectivesRule, +} from './rules/KnownDirectives'; + +// Spec Section: "Fragment spread target defined" +export { + KnownFragmentNames as KnownFragmentNamesRule, +} from './rules/KnownFragmentNames'; + +// Spec Section: "Fragment Spread Type Existence" +export { KnownTypeNames as KnownTypeNamesRule } from './rules/KnownTypeNames'; + +// Spec Section: "Lone Anonymous Operation" +export { + LoneAnonymousOperation as LoneAnonymousOperationRule, +} from './rules/LoneAnonymousOperation'; + +// Spec Section: "Fragments must not form cycles" +export { + NoFragmentCycles as NoFragmentCyclesRule, +} from './rules/NoFragmentCycles'; + +// Spec Section: "All Variable Used Defined" +export { + NoUndefinedVariables as NoUndefinedVariablesRule, +} from './rules/NoUndefinedVariables'; + +// Spec Section: "Fragments must be used" +export { + NoUnusedFragments as NoUnusedFragmentsRule, +} from './rules/NoUnusedFragments'; + +// Spec Section: "All Variables Used" +export { + NoUnusedVariables as NoUnusedVariablesRule, +} from './rules/NoUnusedVariables'; + +// Spec Section: "Field Selection Merging" +export { + OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule, +} from './rules/OverlappingFieldsCanBeMerged'; + +// Spec Section: "Fragment spread is possible" +export { + PossibleFragmentSpreads as PossibleFragmentSpreadsRule, +} from './rules/PossibleFragmentSpreads'; + +// Spec Section: "Argument Optionality" +export { + ProvidedRequiredArguments as ProvidedRequiredArgumentsRule, +} from './rules/ProvidedRequiredArguments'; + +// Spec Section: "Leaf Field Selections" +export { ScalarLeafs as ScalarLeafsRule } from './rules/ScalarLeafs'; + +// Spec Section: "Subscriptions with Single Root Field" +export { + SingleFieldSubscriptions as SingleFieldSubscriptionsRule, +} from './rules/SingleFieldSubscriptions'; + +// Spec Section: "Argument Uniqueness" +export { + UniqueArgumentNames as UniqueArgumentNamesRule, +} from './rules/UniqueArgumentNames'; + +// Spec Section: "Directives Are Unique Per Location" +export { + UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule, +} from './rules/UniqueDirectivesPerLocation'; + +// Spec Section: "Fragment Name Uniqueness" +export { + UniqueFragmentNames as UniqueFragmentNamesRule, +} from './rules/UniqueFragmentNames'; + +// Spec Section: "Input Object Field Uniqueness" +export { + UniqueInputFieldNames as UniqueInputFieldNamesRule, +} from './rules/UniqueInputFieldNames'; + +// Spec Section: "Operation Name Uniqueness" +export { + UniqueOperationNames as UniqueOperationNamesRule, +} from './rules/UniqueOperationNames'; + +// Spec Section: "Variable Uniqueness" +export { + UniqueVariableNames as UniqueVariableNamesRule, +} from './rules/UniqueVariableNames'; + +// Spec Section: "Values Type Correctness" +export { + ValuesOfCorrectType as ValuesOfCorrectTypeRule, +} from './rules/ValuesOfCorrectType'; + +// Spec Section: "Variables are Input Types" +export { + VariablesAreInputTypes as VariablesAreInputTypesRule, +} from './rules/VariablesAreInputTypes'; + +// Spec Section: "All Variable Usages Are Allowed" +export { + VariablesInAllowedPosition as VariablesInAllowedPositionRule, +} from './rules/VariablesInAllowedPosition'; diff --git a/node_modules/graphql/validation/index.mjs b/node_modules/graphql/validation/index.mjs new file mode 100644 index 00000000..8ec35793 --- /dev/null +++ b/node_modules/graphql/validation/index.mjs @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +export { validate } from './validate'; +export { ValidationContext } from './ValidationContext'; +export { specifiedRules } from './specifiedRules'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +export { FieldsOnCorrectType as FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectType'; // Spec Section: "Fragments on Composite Types" + +export { FragmentsOnCompositeTypes as FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypes'; // Spec Section: "Argument Names" + +export { KnownArgumentNames as KnownArgumentNamesRule } from './rules/KnownArgumentNames'; // Spec Section: "Directives Are Defined" + +export { KnownDirectives as KnownDirectivesRule } from './rules/KnownDirectives'; // Spec Section: "Fragment spread target defined" + +export { KnownFragmentNames as KnownFragmentNamesRule } from './rules/KnownFragmentNames'; // Spec Section: "Fragment Spread Type Existence" + +export { KnownTypeNames as KnownTypeNamesRule } from './rules/KnownTypeNames'; // Spec Section: "Lone Anonymous Operation" + +export { LoneAnonymousOperation as LoneAnonymousOperationRule } from './rules/LoneAnonymousOperation'; // Spec Section: "Fragments must not form cycles" + +export { NoFragmentCycles as NoFragmentCyclesRule } from './rules/NoFragmentCycles'; // Spec Section: "All Variable Used Defined" + +export { NoUndefinedVariables as NoUndefinedVariablesRule } from './rules/NoUndefinedVariables'; // Spec Section: "Fragments must be used" + +export { NoUnusedFragments as NoUnusedFragmentsRule } from './rules/NoUnusedFragments'; // Spec Section: "All Variables Used" + +export { NoUnusedVariables as NoUnusedVariablesRule } from './rules/NoUnusedVariables'; // Spec Section: "Field Selection Merging" + +export { OverlappingFieldsCanBeMerged as OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMerged'; // Spec Section: "Fragment spread is possible" + +export { PossibleFragmentSpreads as PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreads'; // Spec Section: "Argument Optionality" + +export { ProvidedRequiredArguments as ProvidedRequiredArgumentsRule } from './rules/ProvidedRequiredArguments'; // Spec Section: "Leaf Field Selections" + +export { ScalarLeafs as ScalarLeafsRule } from './rules/ScalarLeafs'; // Spec Section: "Subscriptions with Single Root Field" + +export { SingleFieldSubscriptions as SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptions'; // Spec Section: "Argument Uniqueness" + +export { UniqueArgumentNames as UniqueArgumentNamesRule } from './rules/UniqueArgumentNames'; // Spec Section: "Directives Are Unique Per Location" + +export { UniqueDirectivesPerLocation as UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocation'; // Spec Section: "Fragment Name Uniqueness" + +export { UniqueFragmentNames as UniqueFragmentNamesRule } from './rules/UniqueFragmentNames'; // Spec Section: "Input Object Field Uniqueness" + +export { UniqueInputFieldNames as UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNames'; // Spec Section: "Operation Name Uniqueness" + +export { UniqueOperationNames as UniqueOperationNamesRule } from './rules/UniqueOperationNames'; // Spec Section: "Variable Uniqueness" + +export { UniqueVariableNames as UniqueVariableNamesRule } from './rules/UniqueVariableNames'; // Spec Section: "Values Type Correctness" + +export { ValuesOfCorrectType as ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectType'; // Spec Section: "Variables are Input Types" + +export { VariablesAreInputTypes as VariablesAreInputTypesRule } from './rules/VariablesAreInputTypes'; // Spec Section: "All Variable Usages Are Allowed" + +export { VariablesInAllowedPosition as VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPosition'; \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitions.js b/node_modules/graphql/validation/rules/ExecutableDefinitions.js new file mode 100644 index 00000000..a3240dc2 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitions.js @@ -0,0 +1,67 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nonExecutableDefinitionMessage = nonExecutableDefinitionMessage; +exports.ExecutableDefinitions = ExecutableDefinitions; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _predicates = require("../../language/predicates"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function nonExecutableDefinitionMessage(defName) { + return "The ".concat(defName, " definition is not executable."); +} +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ + + +function ExecutableDefinitions(context) { + return { + Document: function Document(node) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = node.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var definition = _step.value; + + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + context.reportError(new _GraphQLError.GraphQLError(nonExecutableDefinitionMessage(definition.kind === _kinds.Kind.SCHEMA_DEFINITION || definition.kind === _kinds.Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), [definition])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow b/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow new file mode 100644 index 00000000..4af7ec48 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitions.js.flow @@ -0,0 +1,49 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { isExecutableDefinitionNode } from '../../language/predicates'; +import type { ASTVisitor } from '../../language/visitor'; + +export function nonExecutableDefinitionMessage(defName: string): string { + return `The ${defName} definition is not executable.`; +} + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ +export function ExecutableDefinitions( + context: ASTValidationContext, +): ASTVisitor { + return { + Document(node) { + for (const definition of node.definitions) { + if (!isExecutableDefinitionNode(definition)) { + context.reportError( + new GraphQLError( + nonExecutableDefinitionMessage( + definition.kind === Kind.SCHEMA_DEFINITION || + definition.kind === Kind.SCHEMA_EXTENSION + ? 'schema' + : definition.name.value, + ), + [definition], + ), + ); + } + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs b/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs new file mode 100644 index 00000000..26bf7538 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitions.mjs @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { isExecutableDefinitionNode } from '../../language/predicates'; +export function nonExecutableDefinitionMessage(defName) { + return "The ".concat(defName, " definition is not executable."); +} +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + */ + +export function ExecutableDefinitions(context) { + return { + Document: function Document(node) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = node.definitions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var definition = _step.value; + + if (!isExecutableDefinitionNode(definition)) { + context.reportError(new GraphQLError(nonExecutableDefinitionMessage(definition.kind === Kind.SCHEMA_DEFINITION || definition.kind === Kind.SCHEMA_EXTENSION ? 'schema' : definition.name.value), [definition])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectType.js b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js new file mode 100644 index 00000000..25896e76 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js @@ -0,0 +1,165 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.undefinedFieldMessage = undefinedFieldMessage; +exports.FieldsOnCorrectType = FieldsOnCorrectType; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList")); + +var _definition = require("../../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) { + var message = "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\"."); + + if (suggestedTypeNames.length !== 0) { + var suggestions = (0, _quotedOrList.default)(suggestedTypeNames); + message += " Did you mean to use an inline fragment on ".concat(suggestions, "?"); + } else if (suggestedFieldNames.length !== 0) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedFieldNames), "?"); + } + + return message; +} +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ + + +function FieldsOnCorrectType(context) { + return { + Field: function Field(node) { + var type = context.getParentType(); + + if (type) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + var schema = context.getSchema(); + var fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo? + + var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions. + + context.reportError(new _GraphQLError.GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), [node])); + } + } + } + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest + * them, sorted by how often the type is referenced, starting with Interfaces. + */ + + +function getSuggestedTypeNames(schema, type, fieldName) { + if ((0, _definition.isAbstractType)(type)) { + var suggestedObjectTypes = []; + var interfaceUsageCount = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.getPossibleTypes(type)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var possibleType = _step.value; + + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + + suggestedObjectTypes.push(possibleType.name); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = possibleType.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var possibleInterface = _step2.value; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + + interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } // Suggest interface types based on how common they are. + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) { + return interfaceUsageCount[b] - interfaceUsageCount[a]; + }); // Suggest both interface and object types. + + return suggestedInterfaceTypes.concat(suggestedObjectTypes); + } // Otherwise, must be an Object type, which does not have possible fields. + + + return []; +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + +function getSuggestedFieldNames(schema, type, fieldName) { + if ((0, _definition.isObjectType)(type) || (0, _definition.isInterfaceType)(type)) { + var possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.default)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + + return []; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectType.js.flow b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js.flow new file mode 100644 index 00000000..3f389a9d --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectType.js.flow @@ -0,0 +1,143 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import type { FieldNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; +import type { GraphQLSchema } from '../../type/schema'; +import type { GraphQLOutputType } from '../../type/definition'; +import { + isObjectType, + isInterfaceType, + isAbstractType, +} from '../../type/definition'; + +export function undefinedFieldMessage( + fieldName: string, + type: string, + suggestedTypeNames: Array, + suggestedFieldNames: Array, +): string { + let message = `Cannot query field "${fieldName}" on type "${type}".`; + if (suggestedTypeNames.length !== 0) { + const suggestions = quotedOrList(suggestedTypeNames); + message += ` Did you mean to use an inline fragment on ${suggestions}?`; + } else if (suggestedFieldNames.length !== 0) { + message += ` Did you mean ${quotedOrList(suggestedFieldNames)}?`; + } + return message; +} + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ +export function FieldsOnCorrectType(context: ValidationContext): ASTVisitor { + return { + Field(node: FieldNode) { + const type = context.getParentType(); + if (type) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; + // First determine if there are any suggested types to condition on. + const suggestedTypeNames = getSuggestedTypeNames( + schema, + type, + fieldName, + ); + // If there are no suggested types, then perhaps this was a typo? + const suggestedFieldNames = + suggestedTypeNames.length !== 0 + ? [] + : getSuggestedFieldNames(schema, type, fieldName); + + // Report an error, including helpful suggestions. + context.reportError( + new GraphQLError( + undefinedFieldMessage( + fieldName, + type.name, + suggestedTypeNames, + suggestedFieldNames, + ), + [node], + ), + ); + } + } + }, + }; +} + +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest + * them, sorted by how often the type is referenced, starting with Interfaces. + */ +function getSuggestedTypeNames( + schema: GraphQLSchema, + type: GraphQLOutputType, + fieldName: string, +): Array { + if (isAbstractType(type)) { + const suggestedObjectTypes = []; + const interfaceUsageCount = Object.create(null); + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } + // This object type defines this field. + suggestedObjectTypes.push(possibleType.name); + for (const possibleInterface of possibleType.getInterfaces()) { + if (!possibleInterface.getFields()[fieldName]) { + continue; + } + // This interface type defines this field. + interfaceUsageCount[possibleInterface.name] = + (interfaceUsageCount[possibleInterface.name] || 0) + 1; + } + } + + // Suggest interface types based on how common they are. + const suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort( + (a, b) => interfaceUsageCount[b] - interfaceUsageCount[a], + ); + + // Suggest both interface and object types. + return suggestedInterfaceTypes.concat(suggestedObjectTypes); + } + + // Otherwise, must be an Object type, which does not have possible fields. + return []; +} + +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ +function getSuggestedFieldNames( + schema: GraphQLSchema, + type: GraphQLOutputType, + fieldName: string, +): Array { + if (isObjectType(type) || isInterfaceType(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } + // Otherwise, must be a Union type, which does not define fields. + return []; +} diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectType.mjs b/node_modules/graphql/validation/rules/FieldsOnCorrectType.mjs new file mode 100644 index 00000000..3578cd3b --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectType.mjs @@ -0,0 +1,149 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import { isObjectType, isInterfaceType, isAbstractType } from '../../type/definition'; +export function undefinedFieldMessage(fieldName, type, suggestedTypeNames, suggestedFieldNames) { + var message = "Cannot query field \"".concat(fieldName, "\" on type \"").concat(type, "\"."); + + if (suggestedTypeNames.length !== 0) { + var suggestions = quotedOrList(suggestedTypeNames); + message += " Did you mean to use an inline fragment on ".concat(suggestions, "?"); + } else if (suggestedFieldNames.length !== 0) { + message += " Did you mean ".concat(quotedOrList(suggestedFieldNames), "?"); + } + + return message; +} +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + */ + +export function FieldsOnCorrectType(context) { + return { + Field: function Field(node) { + var type = context.getParentType(); + + if (type) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + var schema = context.getSchema(); + var fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + var suggestedTypeNames = getSuggestedTypeNames(schema, type, fieldName); // If there are no suggested types, then perhaps this was a typo? + + var suggestedFieldNames = suggestedTypeNames.length !== 0 ? [] : getSuggestedFieldNames(schema, type, fieldName); // Report an error, including helpful suggestions. + + context.reportError(new GraphQLError(undefinedFieldMessage(fieldName, type.name, suggestedTypeNames, suggestedFieldNames), [node])); + } + } + } + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest + * them, sorted by how often the type is referenced, starting with Interfaces. + */ + +function getSuggestedTypeNames(schema, type, fieldName) { + if (isAbstractType(type)) { + var suggestedObjectTypes = []; + var interfaceUsageCount = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = schema.getPossibleTypes(type)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var possibleType = _step.value; + + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + + suggestedObjectTypes.push(possibleType.name); + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = possibleType.getInterfaces()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var possibleInterface = _step2.value; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + + interfaceUsageCount[possibleInterface.name] = (interfaceUsageCount[possibleInterface.name] || 0) + 1; + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + } // Suggest interface types based on how common they are. + + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var suggestedInterfaceTypes = Object.keys(interfaceUsageCount).sort(function (a, b) { + return interfaceUsageCount[b] - interfaceUsageCount[a]; + }); // Suggest both interface and object types. + + return suggestedInterfaceTypes.concat(suggestedObjectTypes); + } // Otherwise, must be an Object type, which does not have possible fields. + + + return []; +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + */ + + +function getSuggestedFieldNames(schema, type, fieldName) { + if (isObjectType(type) || isInterfaceType(type)) { + var possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + + return []; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js new file mode 100644 index 00000000..466b90eb --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js @@ -0,0 +1,63 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.inlineFragmentOnNonCompositeErrorMessage = inlineFragmentOnNonCompositeErrorMessage; +exports.fragmentOnNonCompositeErrorMessage = fragmentOnNonCompositeErrorMessage; +exports.FragmentsOnCompositeTypes = FragmentsOnCompositeTypes; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function inlineFragmentOnNonCompositeErrorMessage(type) { + return "Fragment cannot condition on non composite type \"".concat(type, "\"."); +} + +function fragmentOnNonCompositeErrorMessage(fragName, type) { + return "Fragment \"".concat(fragName, "\" cannot condition on non composite ") + "type \"".concat(type, "\"."); +} +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ + + +function FragmentsOnCompositeTypes(context) { + return { + InlineFragment: function InlineFragment(node) { + var typeCondition = node.typeCondition; + + if (typeCondition) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition); + + if (type && !(0, _definition.isCompositeType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(inlineFragmentOnNonCompositeErrorMessage((0, _printer.print)(typeCondition)), [typeCondition])); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.typeCondition); + + if (type && !(0, _definition.isCompositeType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, (0, _printer.print)(node.typeCondition)), [node.typeCondition])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js.flow b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js.flow new file mode 100644 index 00000000..f103e03a --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.js.flow @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { isCompositeType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; + +export function inlineFragmentOnNonCompositeErrorMessage(type: string): string { + return `Fragment cannot condition on non composite type "${type}".`; +} + +export function fragmentOnNonCompositeErrorMessage( + fragName: string, + type: string, +): string { + return ( + `Fragment "${fragName}" cannot condition on non composite ` + + `type "${type}".` + ); +} + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ +export function FragmentsOnCompositeTypes( + context: ValidationContext, +): ASTVisitor { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + if (typeCondition) { + const type = typeFromAST(context.getSchema(), typeCondition); + if (type && !isCompositeType(type)) { + context.reportError( + new GraphQLError( + inlineFragmentOnNonCompositeErrorMessage(print(typeCondition)), + [typeCondition], + ), + ); + } + } + }, + FragmentDefinition(node) { + const type = typeFromAST(context.getSchema(), node.typeCondition); + if (type && !isCompositeType(type)) { + context.reportError( + new GraphQLError( + fragmentOnNonCompositeErrorMessage( + node.name.value, + print(node.typeCondition), + ), + [node.typeCondition], + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.mjs b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.mjs new file mode 100644 index 00000000..df073ff5 --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypes.mjs @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import { isCompositeType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function inlineFragmentOnNonCompositeErrorMessage(type) { + return "Fragment cannot condition on non composite type \"".concat(type, "\"."); +} +export function fragmentOnNonCompositeErrorMessage(fragName, type) { + return "Fragment \"".concat(fragName, "\" cannot condition on non composite ") + "type \"".concat(type, "\"."); +} +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + */ + +export function FragmentsOnCompositeTypes(context) { + return { + InlineFragment: function InlineFragment(node) { + var typeCondition = node.typeCondition; + + if (typeCondition) { + var type = typeFromAST(context.getSchema(), typeCondition); + + if (type && !isCompositeType(type)) { + context.reportError(new GraphQLError(inlineFragmentOnNonCompositeErrorMessage(print(typeCondition)), [typeCondition])); + } + } + }, + FragmentDefinition: function FragmentDefinition(node) { + var type = typeFromAST(context.getSchema(), node.typeCondition); + + if (type && !isCompositeType(type)) { + context.reportError(new GraphQLError(fragmentOnNonCompositeErrorMessage(node.name.value, print(node.typeCondition)), [node.typeCondition])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownArgumentNames.js b/node_modules/graphql/validation/rules/KnownArgumentNames.js new file mode 100644 index 00000000..62cab657 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNames.js @@ -0,0 +1,172 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownArgMessage = unknownArgMessage; +exports.unknownDirectiveArgMessage = unknownDirectiveArgMessage; +exports.KnownArgumentNames = KnownArgumentNames; +exports.KnownArgumentNamesOnDirectives = KnownArgumentNamesOnDirectives; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList")); + +var _kinds = require("../../language/kinds"); + +var _directives = require("../../type/directives"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of ") + "type \"".concat(typeName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?"); + } + + return message; +} + +function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedArgs), "?"); + } + + return message; +} +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ + + +function KnownArgumentNames(context) { + return _objectSpread({}, KnownArgumentNamesOnDirectives(context), { + Argument: function Argument(argNode) { + var argDef = context.getArgument(); + var fieldDef = context.getFieldDef(); + var parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + var argName = argNode.name.value; + var knownArgsNames = fieldDef.args.map(function (arg) { + return arg.name; + }); + context.reportError(new _GraphQLError.GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, (0, _suggestionList.default)(argName, knownArgsNames)), argNode)); + } + } + }); +} // @internal + + +function KnownArgumentNamesOnDirectives(context) { + var directiveArgs = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + directiveArgs[directive.name] = directive.args.map(function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) { + return arg.name.value; + }) : []; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(directiveNode) { + var directiveName = directiveNode.name.value; + var knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directiveNode.arguments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var argNode = _step3.value; + var argName = argNode.name.value; + + if (knownArgs.indexOf(argName) === -1) { + var suggestions = (0, _suggestionList.default)(argName, knownArgs); + context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownArgumentNames.js.flow b/node_modules/graphql/validation/rules/KnownArgumentNames.js.flow new file mode 100644 index 00000000..4c69bb81 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNames.js.flow @@ -0,0 +1,127 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import { Kind } from '../../language/kinds'; +import { specifiedDirectives } from '../../type/directives'; + +export function unknownArgMessage( + argName: string, + fieldName: string, + typeName: string, + suggestedArgs: Array, +): string { + let message = + `Unknown argument "${argName}" on field "${fieldName}" of ` + + `type "${typeName}".`; + if (suggestedArgs.length) { + message += ` Did you mean ${quotedOrList(suggestedArgs)}?`; + } + return message; +} + +export function unknownDirectiveArgMessage( + argName: string, + directiveName: string, + suggestedArgs: Array, +): string { + let message = `Unknown argument "${argName}" on directive "@${directiveName}".`; + if (suggestedArgs.length) { + message += ` Did you mean ${quotedOrList(suggestedArgs)}?`; + } + return message; +} + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ +export function KnownArgumentNames(context: ValidationContext): ASTVisitor { + return { + ...KnownArgumentNamesOnDirectives(context), + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map(arg => arg.name); + context.reportError( + new GraphQLError( + unknownArgMessage( + argName, + fieldDef.name, + parentType.name, + suggestionList(argName, knownArgsNames), + ), + argNode, + ), + ); + } + }, + }; +} + +// @internal +export function KnownArgumentNamesOnDirectives( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const directiveArgs = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map(arg => arg.name); + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveArgs[def.name.value] = def.arguments + ? def.arguments.map(arg => arg.name.value) + : []; + } + } + + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + if (knownArgs.indexOf(argName) === -1) { + const suggestions = suggestionList(argName, knownArgs); + context.reportError( + new GraphQLError( + unknownDirectiveArgMessage(argName, directiveName, suggestions), + argNode, + ), + ); + } + } + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownArgumentNames.mjs b/node_modules/graphql/validation/rules/KnownArgumentNames.mjs new file mode 100644 index 00000000..0a132147 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNames.mjs @@ -0,0 +1,160 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import { Kind } from '../../language/kinds'; +import { specifiedDirectives } from '../../type/directives'; +export function unknownArgMessage(argName, fieldName, typeName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on field \"").concat(fieldName, "\" of ") + "type \"".concat(typeName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat(quotedOrList(suggestedArgs), "?"); + } + + return message; +} +export function unknownDirectiveArgMessage(argName, directiveName, suggestedArgs) { + var message = "Unknown argument \"".concat(argName, "\" on directive \"@").concat(directiveName, "\"."); + + if (suggestedArgs.length) { + message += " Did you mean ".concat(quotedOrList(suggestedArgs), "?"); + } + + return message; +} +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + */ + +export function KnownArgumentNames(context) { + return _objectSpread({}, KnownArgumentNamesOnDirectives(context), { + Argument: function Argument(argNode) { + var argDef = context.getArgument(); + var fieldDef = context.getFieldDef(); + var parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + var argName = argNode.name.value; + var knownArgsNames = fieldDef.args.map(function (arg) { + return arg.name; + }); + context.reportError(new GraphQLError(unknownArgMessage(argName, fieldDef.name, parentType.name, suggestionList(argName, knownArgsNames)), argNode)); + } + } + }); +} // @internal + +export function KnownArgumentNamesOnDirectives(context) { + var directiveArgs = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + directiveArgs[directive.name] = directive.args.map(function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveArgs[def.name.value] = def.arguments ? def.arguments.map(function (arg) { + return arg.name.value; + }) : []; + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(directiveNode) { + var directiveName = directiveNode.name.value; + var knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = directiveNode.arguments[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var argNode = _step3.value; + var argName = argNode.name.value; + + if (knownArgs.indexOf(argName) === -1) { + var suggestions = suggestionList(argName, knownArgs); + context.reportError(new GraphQLError(unknownDirectiveArgMessage(argName, directiveName, suggestions), argNode)); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownDirectives.js b/node_modules/graphql/validation/rules/KnownDirectives.js new file mode 100644 index 00000000..e73cc883 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectives.js @@ -0,0 +1,191 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownDirectiveMessage = unknownDirectiveMessage; +exports.misplacedDirectiveMessage = misplacedDirectiveMessage; +exports.KnownDirectives = KnownDirectives; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _directiveLocation = require("../../language/directiveLocation"); + +var _directives = require("../../type/directives"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unknownDirectiveMessage(directiveName) { + return "Unknown directive \"".concat(directiveName, "\"."); +} + +function misplacedDirectiveMessage(directiveName, location) { + return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, "."); +} +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ + + +function KnownDirectives(context) { + var locationsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + locationsMap[directive.name] = directive.locations; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(function (name) { + return name.value; + }); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(node, key, parent, path, ancestors) { + var name = node.name.value; + var locations = locationsMap[name]; + + if (!locations) { + context.reportError(new _GraphQLError.GraphQLError(unknownDirectiveMessage(name), [node])); + return; + } + + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError(new _GraphQLError.GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [node])); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + + if (!Array.isArray(appliedTo)) { + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return _directiveLocation.DirectiveLocation.QUERY; + + case 'mutation': + return _directiveLocation.DirectiveLocation.MUTATION; + + case 'subscription': + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } + + break; + + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + + case _kinds.Kind.INPUT_VALUE_DEFINITION: + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownDirectives.js.flow b/node_modules/graphql/validation/rules/KnownDirectives.js.flow new file mode 100644 index 00000000..52c9a7b0 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectives.js.flow @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { DirectiveLocation } from '../../language/directiveLocation'; +import type { ASTVisitor } from '../../language/visitor'; +import { specifiedDirectives } from '../../type/directives'; + +export function unknownDirectiveMessage(directiveName: string): string { + return `Unknown directive "${directiveName}".`; +} + +export function misplacedDirectiveMessage( + directiveName: string, + location: string, +): string { + return `Directive "${directiveName}" may not be used on ${location}.`; +} + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ +export function KnownDirectives( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const locationsMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(name => name.value); + } + } + + return { + Directive(node, key, parent, path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + + if (!locations) { + context.reportError( + new GraphQLError(unknownDirectiveMessage(name), [node]), + ); + return; + } + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError( + new GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [ + node, + ]), + ); + } + }, + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + if (!Array.isArray(appliedTo)) { + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return DirectiveLocation.QUERY; + case 'mutation': + return DirectiveLocation.MUTATION; + case 'subscription': + return DirectiveLocation.SUBSCRIPTION; + } + break; + case Kind.FIELD: + return DirectiveLocation.FIELD; + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + case Kind.INPUT_VALUE_DEFINITION: + const parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ? DirectiveLocation.INPUT_FIELD_DEFINITION + : DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} diff --git a/node_modules/graphql/validation/rules/KnownDirectives.mjs b/node_modules/graphql/validation/rules/KnownDirectives.mjs new file mode 100644 index 00000000..44588d2c --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectives.mjs @@ -0,0 +1,176 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { DirectiveLocation } from '../../language/directiveLocation'; +import { specifiedDirectives } from '../../type/directives'; +export function unknownDirectiveMessage(directiveName) { + return "Unknown directive \"".concat(directiveName, "\"."); +} +export function misplacedDirectiveMessage(directiveName, location) { + return "Directive \"".concat(directiveName, "\" may not be used on ").concat(location, "."); +} +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + */ + +export function KnownDirectives(context) { + var locationsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = definedDirectives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + locationsMap[directive.name] = directive.locations; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = astDefinitions[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var def = _step2.value; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map(function (name) { + return name.value; + }); + } + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return { + Directive: function Directive(node, key, parent, path, ancestors) { + var name = node.name.value; + var locations = locationsMap[name]; + + if (!locations) { + context.reportError(new GraphQLError(unknownDirectiveMessage(name), [node])); + return; + } + + var candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && locations.indexOf(candidateLocation) === -1) { + context.reportError(new GraphQLError(misplacedDirectiveMessage(name, candidateLocation), [node])); + } + } + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + var appliedTo = ancestors[ancestors.length - 1]; + + if (!Array.isArray(appliedTo)) { + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + switch (appliedTo.operation) { + case 'query': + return DirectiveLocation.QUERY; + + case 'mutation': + return DirectiveLocation.MUTATION; + + case 'subscription': + return DirectiveLocation.SUBSCRIPTION; + } + + break; + + case Kind.FIELD: + return DirectiveLocation.FIELD; + + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + + case Kind.INPUT_VALUE_DEFINITION: + var parentNode = ancestors[ancestors.length - 3]; + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION ? DirectiveLocation.INPUT_FIELD_DEFINITION : DirectiveLocation.ARGUMENT_DEFINITION; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownFragmentNames.js b/node_modules/graphql/validation/rules/KnownFragmentNames.js new file mode 100644 index 00000000..f00b953f --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNames.js @@ -0,0 +1,41 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownFragmentMessage = unknownFragmentMessage; +exports.KnownFragmentNames = KnownFragmentNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unknownFragmentMessage(fragName) { + return "Unknown fragment \"".concat(fragName, "\"."); +} +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ + + +function KnownFragmentNames(context) { + return { + FragmentSpread: function FragmentSpread(node) { + var fragmentName = node.name.value; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError(new _GraphQLError.GraphQLError(unknownFragmentMessage(fragmentName), [node.name])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownFragmentNames.js.flow b/node_modules/graphql/validation/rules/KnownFragmentNames.js.flow new file mode 100644 index 00000000..383e8402 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNames.js.flow @@ -0,0 +1,36 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unknownFragmentMessage(fragName: string): string { + return `Unknown fragment "${fragName}".`; +} + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ +export function KnownFragmentNames(context: ValidationContext): ASTVisitor { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + if (!fragment) { + context.reportError( + new GraphQLError(unknownFragmentMessage(fragmentName), [node.name]), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownFragmentNames.mjs b/node_modules/graphql/validation/rules/KnownFragmentNames.mjs new file mode 100644 index 00000000..061772db --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNames.mjs @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function unknownFragmentMessage(fragName) { + return "Unknown fragment \"".concat(fragName, "\"."); +} +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + */ + +export function KnownFragmentNames(context) { + return { + FragmentSpread: function FragmentSpread(node) { + var fragmentName = node.name.value; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError(new GraphQLError(unknownFragmentMessage(fragmentName), [node.name])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownTypeNames.js b/node_modules/graphql/validation/rules/KnownTypeNames.js new file mode 100644 index 00000000..2a4065d1 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNames.js @@ -0,0 +1,69 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unknownTypeMessage = unknownTypeMessage; +exports.KnownTypeNames = KnownTypeNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +var _quotedOrList = _interopRequireDefault(require("../../jsutils/quotedOrList")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unknownTypeMessage(typeName, suggestedTypes) { + var message = "Unknown type \"".concat(typeName, "\"."); + + if (suggestedTypes.length) { + message += " Did you mean ".concat((0, _quotedOrList.default)(suggestedTypes), "?"); + } + + return message; +} +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ + + +function KnownTypeNames(context) { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: function ObjectTypeDefinition() { + return false; + }, + InterfaceTypeDefinition: function InterfaceTypeDefinition() { + return false; + }, + UnionTypeDefinition: function UnionTypeDefinition() { + return false; + }, + InputObjectTypeDefinition: function InputObjectTypeDefinition() { + return false; + }, + NamedType: function NamedType(node) { + var schema = context.getSchema(); + var typeName = node.name.value; + var type = schema.getType(typeName); + + if (!type) { + context.reportError(new _GraphQLError.GraphQLError(unknownTypeMessage(typeName, (0, _suggestionList.default)(typeName, Object.keys(schema.getTypeMap()))), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/KnownTypeNames.js.flow b/node_modules/graphql/validation/rules/KnownTypeNames.js.flow new file mode 100644 index 00000000..c65c5bbd --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNames.js.flow @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unknownTypeMessage( + typeName: string, + suggestedTypes: Array, +): string { + let message = `Unknown type "${typeName}".`; + if (suggestedTypes.length) { + message += ` Did you mean ${quotedOrList(suggestedTypes)}?`; + } + return message; +} + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ +export function KnownTypeNames(context: ValidationContext): ASTVisitor { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: () => false, + InterfaceTypeDefinition: () => false, + UnionTypeDefinition: () => false, + InputObjectTypeDefinition: () => false, + NamedType(node) { + const schema = context.getSchema(); + const typeName = node.name.value; + const type = schema.getType(typeName); + if (!type) { + context.reportError( + new GraphQLError( + unknownTypeMessage( + typeName, + suggestionList(typeName, Object.keys(schema.getTypeMap())), + ), + [node], + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownTypeNames.mjs b/node_modules/graphql/validation/rules/KnownTypeNames.mjs new file mode 100644 index 00000000..861e8226 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNames.mjs @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import suggestionList from '../../jsutils/suggestionList'; +import quotedOrList from '../../jsutils/quotedOrList'; +export function unknownTypeMessage(typeName, suggestedTypes) { + var message = "Unknown type \"".concat(typeName, "\"."); + + if (suggestedTypes.length) { + message += " Did you mean ".concat(quotedOrList(suggestedTypes), "?"); + } + + return message; +} +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + */ + +export function KnownTypeNames(context) { + return { + // TODO: when validating IDL, re-enable these. Experimental version does not + // add unreferenced types, resulting in false-positive errors. Squelched + // errors for now. + ObjectTypeDefinition: function ObjectTypeDefinition() { + return false; + }, + InterfaceTypeDefinition: function InterfaceTypeDefinition() { + return false; + }, + UnionTypeDefinition: function UnionTypeDefinition() { + return false; + }, + InputObjectTypeDefinition: function InputObjectTypeDefinition() { + return false; + }, + NamedType: function NamedType(node) { + var schema = context.getSchema(); + var typeName = node.name.value; + var type = schema.getType(typeName); + + if (!type) { + context.reportError(new GraphQLError(unknownTypeMessage(typeName, suggestionList(typeName, Object.keys(schema.getTypeMap()))), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperation.js b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js new file mode 100644 index 00000000..b492a859 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js @@ -0,0 +1,46 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.anonOperationNotAloneMessage = anonOperationNotAloneMessage; +exports.LoneAnonymousOperation = LoneAnonymousOperation; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function anonOperationNotAloneMessage() { + return 'This anonymous operation must be the only defined operation.'; +} +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ + + +function LoneAnonymousOperation(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === _kinds.Kind.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new _GraphQLError.GraphQLError(anonOperationNotAloneMessage(), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperation.js.flow b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js.flow new file mode 100644 index 00000000..2faad314 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperation.js.flow @@ -0,0 +1,43 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import type { ASTVisitor } from '../../language/visitor'; + +export function anonOperationNotAloneMessage(): string { + return 'This anonymous operation must be the only defined operation.'; +} + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ +export function LoneAnonymousOperation( + context: ASTValidationContext, +): ASTVisitor { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + definition => definition.kind === Kind.OPERATION_DEFINITION, + ).length; + }, + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new GraphQLError(anonOperationNotAloneMessage(), [node]), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperation.mjs b/node_modules/graphql/validation/rules/LoneAnonymousOperation.mjs new file mode 100644 index 00000000..1b4fe089 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperation.mjs @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +export function anonOperationNotAloneMessage() { + return 'This anonymous operation must be the only defined operation.'; +} +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + */ + +export function LoneAnonymousOperation(context) { + var operationCount = 0; + return { + Document: function Document(node) { + operationCount = node.definitions.filter(function (definition) { + return definition.kind === Kind.OPERATION_DEFINITION; + }).length; + }, + OperationDefinition: function OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError(new GraphQLError(anonOperationNotAloneMessage(), [node])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinition.js b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js new file mode 100644 index 00000000..83e475fe --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js @@ -0,0 +1,52 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.schemaDefinitionNotAloneMessage = schemaDefinitionNotAloneMessage; +exports.canNotDefineSchemaWithinExtensionMessage = canNotDefineSchemaWithinExtensionMessage; +exports.LoneSchemaDefinition = LoneSchemaDefinition; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function schemaDefinitionNotAloneMessage() { + return 'Must provide only one schema definition.'; +} + +function canNotDefineSchemaWithinExtensionMessage() { + return 'Cannot define a new schema within a schema extension.'; +} +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ + + +function LoneSchemaDefinition(context) { + var oldSchema = context.getSchema(); + var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType()); + var schemaDefinitionsCount = 0; + return { + SchemaDefinition: function SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new _GraphQLError.GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node)); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError(new _GraphQLError.GraphQLError(schemaDefinitionNotAloneMessage(), node)); + } + + ++schemaDefinitionsCount; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow new file mode 100644 index 00000000..ac614a0a --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinition.js.flow @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { SDLValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function schemaDefinitionNotAloneMessage(): string { + return 'Must provide only one schema definition.'; +} + +export function canNotDefineSchemaWithinExtensionMessage(): string { + return 'Cannot define a new schema within a schema extension.'; +} + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ +export function LoneSchemaDefinition( + context: SDLValidationContext, +): ASTVisitor { + const oldSchema = context.getSchema(); + const alreadyDefined = + oldSchema && + (oldSchema.astNode || + oldSchema.getQueryType() || + oldSchema.getMutationType() || + oldSchema.getSubscriptionType()); + + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node), + ); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError( + new GraphQLError(schemaDefinitionNotAloneMessage(), node), + ); + } + ++schemaDefinitionsCount; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs b/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs new file mode 100644 index 00000000..888676ae --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinition.mjs @@ -0,0 +1,40 @@ +/** + * Copyright (c) 2018-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function schemaDefinitionNotAloneMessage() { + return 'Must provide only one schema definition.'; +} +export function canNotDefineSchemaWithinExtensionMessage() { + return 'Cannot define a new schema within a schema extension.'; +} +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + */ + +export function LoneSchemaDefinition(context) { + var oldSchema = context.getSchema(); + var alreadyDefined = oldSchema && (oldSchema.astNode || oldSchema.getQueryType() || oldSchema.getMutationType() || oldSchema.getSubscriptionType()); + var schemaDefinitionsCount = 0; + return { + SchemaDefinition: function SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError(new GraphQLError(canNotDefineSchemaWithinExtensionMessage(), node)); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError(new GraphQLError(schemaDefinitionNotAloneMessage(), node)); + } + + ++schemaDefinitionsCount; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoFragmentCycles.js b/node_modules/graphql/validation/rules/NoFragmentCycles.js new file mode 100644 index 00000000..78e108ce --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCycles.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.cycleErrorMessage = cycleErrorMessage; +exports.NoFragmentCycles = NoFragmentCycles; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function cycleErrorMessage(fragName, spreadNames) { + var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, "."); +} + +function NoFragmentCycles(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + var spreadPath = []; // Position in the spread path + + var spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + var fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + var spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (var i = 0; i < spreadNodes.length; i++) { + var spreadNode = spreadNodes[i]; + var spreadName = spreadNode.name.value; + var cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + var spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + var cyclePath = spreadPath.slice(cycleIndex); + var fragmentNames = cyclePath.slice(0, -1).map(function (s) { + return s.name.value; + }); + context.reportError(new _GraphQLError.GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath)); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoFragmentCycles.js.flow b/node_modules/graphql/validation/rules/NoFragmentCycles.js.flow new file mode 100644 index 00000000..f070774e --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCycles.js.flow @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { FragmentDefinitionNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +export function cycleErrorMessage( + fragName: string, + spreadNames: Array, +): string { + const via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return `Cannot spread fragment "${fragName}" within itself${via}.`; +} + +export function NoFragmentCycles(context: ValidationContext): ASTVisitor { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); + + // Array of AST nodes used to produce meaningful errors + const spreadPath = []; + + // Position in the spread path + const spreadPathIndexByName = Object.create(null); + + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; + + // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + function detectCycleRecursive(fragment: FragmentDefinitionNode) { + if (visitedFrags[fragment.name.value]) { + return; + } + + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (let i = 0; i < spreadNodes.length; i++) { + const spreadNode = spreadNodes[i]; + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + + spreadPath.push(spreadNode); + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const fragmentNames = cyclePath.slice(0, -1).map(s => s.name.value); + context.reportError( + new GraphQLError( + cycleErrorMessage(spreadName, fragmentNames), + cyclePath, + ), + ); + } + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/node_modules/graphql/validation/rules/NoFragmentCycles.mjs b/node_modules/graphql/validation/rules/NoFragmentCycles.mjs new file mode 100644 index 00000000..64501dbe --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCycles.mjs @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function cycleErrorMessage(fragName, spreadNames) { + var via = spreadNames.length ? ' via ' + spreadNames.join(', ') : ''; + return "Cannot spread fragment \"".concat(fragName, "\" within itself").concat(via, "."); +} +export function NoFragmentCycles(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + var visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + var spreadPath = []; // Position in the spread path + + var spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + } + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + var fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + var spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (var i = 0; i < spreadNodes.length; i++) { + var spreadNode = spreadNodes[i]; + var spreadName = spreadNode.name.value; + var cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + var spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + var cyclePath = spreadPath.slice(cycleIndex); + var fragmentNames = cyclePath.slice(0, -1).map(function (s) { + return s.name.value; + }); + context.reportError(new GraphQLError(cycleErrorMessage(spreadName, fragmentNames), cyclePath)); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariables.js b/node_modules/graphql/validation/rules/NoUndefinedVariables.js new file mode 100644 index 00000000..cbe610b2 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariables.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.undefinedVarMessage = undefinedVarMessage; +exports.NoUndefinedVariables = NoUndefinedVariables; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function undefinedVarMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined."); +} +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ + + +function NoUndefinedVariables(context) { + var variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + variableNameDefined = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + var varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariables.js.flow b/node_modules/graphql/validation/rules/NoUndefinedVariables.js.flow new file mode 100644 index 00000000..fcb85c5c --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariables.js.flow @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function undefinedVarMessage(varName: string, opName: ?string): string { + return opName + ? `Variable "$${varName}" is not defined by operation "${opName}".` + : `Variable "$${varName}" is not defined.`; +} + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ +export function NoUndefinedVariables(context: ValidationContext): ASTVisitor { + let variableNameDefined = Object.create(null); + + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + const varName = node.name.value; + if (variableNameDefined[varName] !== true) { + context.reportError( + new GraphQLError( + undefinedVarMessage( + varName, + operation.name && operation.name.value, + ), + [node, operation], + ), + ); + } + } + }, + }, + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariables.mjs b/node_modules/graphql/validation/rules/NoUndefinedVariables.mjs new file mode 100644 index 00000000..a7a5b56a --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariables.mjs @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function undefinedVarMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is not defined by operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is not defined."); +} +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + */ + +export function NoUndefinedVariables(context) { + var variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + variableNameDefined = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + var varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError(new GraphQLError(undefinedVarMessage(varName, operation.name && operation.name.value), [node, operation])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedFragments.js b/node_modules/graphql/validation/rules/NoUnusedFragments.js new file mode 100644 index 00000000..855f3499 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragments.js @@ -0,0 +1,84 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unusedFragMessage = unusedFragMessage; +exports.NoUnusedFragments = NoUnusedFragments; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unusedFragMessage(fragName) { + return "Fragment \"".concat(fragName, "\" is never used."); +} +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ + + +function NoUnusedFragments(context) { + var operationDefs = []; + var fragmentDefs = []; + return { + OperationDefinition: function OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave: function leave() { + var fragmentNameUsed = Object.create(null); + + for (var _i = 0; _i < operationDefs.length; _i++) { + var operation = operationDefs[_i]; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var fragment = _step.value; + fragmentNameUsed[fragment.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + + for (var _i2 = 0; _i2 < fragmentDefs.length; _i2++) { + var fragmentDef = fragmentDefs[_i2]; + var fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(unusedFragMessage(fragName), [fragmentDef])); + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedFragments.js.flow b/node_modules/graphql/validation/rules/NoUnusedFragments.js.flow new file mode 100644 index 00000000..3e37004c --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragments.js.flow @@ -0,0 +1,59 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unusedFragMessage(fragName: string): string { + return `Fragment "${fragName}" is never used.`; +} + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ +export function NoUnusedFragments(context: ValidationContext): ASTVisitor { + const operationDefs = []; + const fragmentDefs = []; + + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation, + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new GraphQLError(unusedFragMessage(fragName), [fragmentDef]), + ); + } + } + }, + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedFragments.mjs b/node_modules/graphql/validation/rules/NoUnusedFragments.mjs new file mode 100644 index 00000000..fc9ed962 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragments.mjs @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function unusedFragMessage(fragName) { + return "Fragment \"".concat(fragName, "\" is never used."); +} +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + */ + +export function NoUnusedFragments(context) { + var operationDefs = []; + var fragmentDefs = []; + return { + OperationDefinition: function OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + Document: { + leave: function leave() { + var fragmentNameUsed = Object.create(null); + + for (var _i = 0; _i < operationDefs.length; _i++) { + var operation = operationDefs[_i]; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = context.getRecursivelyReferencedFragments(operation)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var fragment = _step.value; + fragmentNameUsed[fragment.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + + for (var _i2 = 0; _i2 < fragmentDefs.length; _i2++) { + var fragmentDef = fragmentDefs[_i2]; + var fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError(new GraphQLError(unusedFragMessage(fragName), [fragmentDef])); + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedVariables.js b/node_modules/graphql/validation/rules/NoUnusedVariables.js new file mode 100644 index 00000000..d62cd94d --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariables.js @@ -0,0 +1,80 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.unusedVariableMessage = unusedVariableMessage; +exports.NoUnusedVariables = NoUnusedVariables; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function unusedVariableMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used."); +} +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ + + +function NoUnusedVariables(context) { + var variableDefs = []; + return { + OperationDefinition: { + enter: function enter() { + variableDefs = []; + }, + leave: function leave(operation) { + var variableNameUsed = Object.create(null); + var usages = context.getRecursiveVariableUsages(operation); + var opName = operation.name ? operation.name.value : null; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + variableNameUsed[node.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + for (var _i = 0; _i < variableDefs.length; _i++) { + var variableDef = variableDefs[_i]; + var variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError(new _GraphQLError.GraphQLError(unusedVariableMessage(variableName, opName), [variableDef])); + } + } + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/NoUnusedVariables.js.flow b/node_modules/graphql/validation/rules/NoUnusedVariables.js.flow new file mode 100644 index 00000000..e438afb7 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariables.js.flow @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function unusedVariableMessage( + varName: string, + opName: ?string, +): string { + return opName + ? `Variable "$${varName}" is never used in operation "${opName}".` + : `Variable "$${varName}" is never used.`; +} + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ +export function NoUnusedVariables(context: ValidationContext): ASTVisitor { + let variableDefs = []; + + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + const opName = operation.name ? operation.name.value : null; + + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } + + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + if (variableNameUsed[variableName] !== true) { + context.reportError( + new GraphQLError(unusedVariableMessage(variableName, opName), [ + variableDef, + ]), + ); + } + } + }, + }, + VariableDefinition(def) { + variableDefs.push(def); + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedVariables.mjs b/node_modules/graphql/validation/rules/NoUnusedVariables.mjs new file mode 100644 index 00000000..08f8f172 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariables.mjs @@ -0,0 +1,70 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function unusedVariableMessage(varName, opName) { + return opName ? "Variable \"$".concat(varName, "\" is never used in operation \"").concat(opName, "\".") : "Variable \"$".concat(varName, "\" is never used."); +} +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + */ + +export function NoUnusedVariables(context) { + var variableDefs = []; + return { + OperationDefinition: { + enter: function enter() { + variableDefs = []; + }, + leave: function leave(operation) { + var variableNameUsed = Object.create(null); + var usages = context.getRecursiveVariableUsages(operation); + var opName = operation.name ? operation.name.value : null; + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node; + variableNameUsed[node.name.value] = true; + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + for (var _i = 0; _i < variableDefs.length; _i++) { + var variableDef = variableDefs[_i]; + var variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError(new GraphQLError(unusedVariableMessage(variableName, opName), [variableDef])); + } + } + } + }, + VariableDefinition: function VariableDefinition(def) { + variableDefs.push(def); + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js new file mode 100644 index 00000000..4e7f71c5 --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js @@ -0,0 +1,595 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fieldsConflictMessage = fieldsConflictMessage; +exports.OverlappingFieldsCanBeMerged = OverlappingFieldsCanBeMerged; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _find = _interopRequireDefault(require("../../jsutils/find")); + +var _kinds = require("../../language/kinds"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function fieldsConflictMessage(responseName, reason) { + return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.'; +} + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(function (_ref) { + var responseName = _ref[0], + subreason = _ref[1]; + return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason)); + }).join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ + + +function OverlappingFieldsCanBeMerged(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + var cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet: function SelectionSet(selectionSet) { + var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + + for (var _i = 0; _i < conflicts.length; _i++) { + var _ref3 = conflicts[_i]; + var _ref2$ = _ref3[0]; + var responseName = _ref2$[0]; + var reason = _ref2$[1]; + var fields1 = _ref3[1]; + var fields2 = _ref3[2]; + context.reportError(new _GraphQLError.GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2))); + } + } + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + var conflicts = []; + + var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), + fieldMap = _getFieldsAndFragment[0], + fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + var comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (var j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + // Memoize so a fragment is not compared for conflicts more than once. + if (comparedFragments[fragmentName]) { + return; + } + + comparedFragments[fragmentName] = true; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. + + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (var i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), + fieldMap1 = _getReferencedFieldsA2[0], + fragmentNames1 = _getReferencedFieldsA2[1]; + + var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), + fieldMap2 = _getReferencedFieldsA3[0], + fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + var conflicts = []; + + var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), + fieldMap1 = _getFieldsAndFragment2[0], + fragmentNames1 = _getFieldsAndFragment2[1]; + + var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), + fieldMap2 = _getFieldsAndFragment3[0], + fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + if (fragmentNames2.length !== 0) { + var comparedFragments = Object.create(null); + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); + } + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + + if (fragmentNames1.length !== 0) { + var _comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); + } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + + for (var _i2 = 0; _i2 < fragmentNames1.length; _i2++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i2], fragmentNames2[_j]); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + var _arr = Object.keys(fieldMap); + + for (var _i3 = 0; _i3 < _arr.length; _i3++) { + var responseName = _arr[_i3]; + var fields = fieldMap[responseName]; // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + + if (fields.length > 1) { + for (var i = 0; i < fields.length; i++) { + for (var j = i + 1; j < fields.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + var _arr2 = Object.keys(fieldMap1); + + for (var _i4 = 0; _i4 < _arr2.length; _i4++) { + var responseName = _arr2[_i4]; + var fields2 = fieldMap2[responseName]; + + if (fields2) { + var fields1 = fieldMap1[responseName]; + + for (var i = 0; i < fields1.length; i++) { + for (var j = 0; j < fields2.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + var parentType1 = field1[0], + node1 = field1[1], + def1 = field1[2]; + var parentType2 = field2[0], + node2 = field2[1], + def2 = field2[2]; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && (0, _definition.isObjectType)(parentType1) && (0, _definition.isObjectType)(parentType2); // The return type for each field. + + var type1 = def1 && def1.type; + var type2 = def2 && def2.type; + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + var name1 = node1.name.value; + var name2 = node2.name.value; + + if (name1 !== name2) { + return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]]; + } // Two field calls must have the same arguments. + + + if (!sameArguments(node1.arguments || [], node2.arguments || [])) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, "they return conflicting types ".concat((0, _inspect.default)(type1), " and ").concat((0, _inspect.default)(type2))], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + + var selectionSet1 = node1.selectionSet; + var selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, (0, _definition.getNamedType)(type1), selectionSet1, (0, _definition.getNamedType)(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(arguments1, arguments2) { + if (arguments1.length !== arguments2.length) { + return false; + } + + return arguments1.every(function (argument1) { + var argument2 = (0, _find.default)(arguments2, function (argument) { + return argument.name.value === argument1.name.value; + }); + + if (!argument2) { + return false; + } + + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return !value1 && !value2 || (0, _printer.print)(value1) === (0, _printer.print)(value2); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + + +function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if ((0, _definition.isListType)(type2)) { + return true; + } + + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + + if ((0, _definition.isLeafType)(type1) || (0, _definition.isLeafType)(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + var cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (!cached) { + var nodeAndDefs = Object.create(null); + var fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + + return cached; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + var fragmentType = (0, _typeFromAST.typeFromAST)(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} + +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case _kinds.Kind.FIELD: + var fieldName = selection.name.value; + var fieldDef = void 0; + + if ((0, _definition.isObjectType)(parentType) || (0, _definition.isInterfaceType)(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + var responseName = selection.alias ? selection.alias.value : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case _kinds.Kind.INLINE_FRAGMENT: + var typeCondition = selection.typeCondition; + var inlineFragmentType = typeCondition ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) : parentType; + + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + + break; + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(function (_ref4) { + var reason = _ref4[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref5) { + var fields1 = _ref5[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref6) { + var fields2 = _ref6[2]; + return allFields.concat(fields2); + }, [node2])]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ + + +var PairSet = +/*#__PURE__*/ +function () { + function PairSet() { + _defineProperty(this, "_data", void 0); + + this._data = Object.create(null); + } + + var _proto = PairSet.prototype; + + _proto.has = function has(a, b, areMutuallyExclusive) { + var first = this._data[a]; + var result = first && first[b]; + + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + + + if (areMutuallyExclusive === false) { + return result === false; + } + + return true; + }; + + _proto.add = function add(a, b, areMutuallyExclusive) { + _pairSetAdd(this._data, a, b, areMutuallyExclusive); + + _pairSetAdd(this._data, b, a, areMutuallyExclusive); + }; + + return PairSet; +}(); + +function _pairSetAdd(data, a, b, areMutuallyExclusive) { + var map = data[a]; + + if (!map) { + map = Object.create(null); + data[a] = map; + } + + map[b] = areMutuallyExclusive; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js.flow b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js.flow new file mode 100644 index 00000000..7a15f4d6 --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.js.flow @@ -0,0 +1,847 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import inspect from '../../jsutils/inspect'; +import find from '../../jsutils/find'; +import type { ObjMap } from '../../jsutils/ObjMap'; +import type { + SelectionSetNode, + FieldNode, + ArgumentNode, + FragmentDefinitionNode, +} from '../../language/ast'; +import { Kind } from '../../language/kinds'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { + getNamedType, + isNonNullType, + isLeafType, + isObjectType, + isListType, + isInterfaceType, +} from '../../type/definition'; +import type { + GraphQLNamedType, + GraphQLOutputType, + GraphQLCompositeType, + GraphQLField, +} from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; + +export function fieldsConflictMessage( + responseName: string, + reason: ConflictReasonMessage, +): string { + return ( + `Fields "${responseName}" conflict because ${reasonMessage(reason)}. ` + + 'Use different aliases on the fields to fetch both if this was intentional.' + ); +} + +function reasonMessage(reason: ConflictReasonMessage): string { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subreason]) => + `subfields "${responseName}" conflict because ${reasonMessage( + subreason, + )}`, + ) + .join(' and '); + } + return reason; +} + +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ +export function OverlappingFieldsCanBeMerged( + context: ValidationContext, +): ASTVisitor { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + const comparedFragmentPairs = new PairSet(); + + // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + const cachedFieldsAndFragmentNames = new Map(); + + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + context.getParentType(), + selectionSet, + ); + for (const [[responseName, reason], fields1, fields2] of conflicts) { + context.reportError( + new GraphQLError( + fieldsConflictMessage(responseName, reason), + fields1.concat(fields2), + ), + ); + } + }, + }; +} + +type Conflict = [ConflictReason, Array, Array]; +// Field name and reason. +type ConflictReason = [string, ConflictReasonMessage]; +// Reason is a string, or a nested list of conflicts. +type ConflictReasonMessage = string | Array; +// Tuple defining a field node in a context. +type NodeAndDef = [GraphQLCompositeType, FieldNode, ?GraphQLField<*, *>]; +// Map of array of those. +type NodeAndDefCollection = ObjMap>; + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ + +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, +): Array { + const conflicts = []; + + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, + ); + + // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + fieldMap, + ); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + const comparedFragments = Object.create(null); + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ); + // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j], + ); + } + } + } + return conflicts; +} + +// Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. +function collectConflictsBetweenFieldsAndFragment( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragments: ObjMap, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fieldMap: NodeAndDefCollection, + fragmentName: string, +): void { + // Memoize so a fragment is not compared for conflicts more than once. + if (comparedFragments[fragmentName]) { + return; + } + comparedFragments[fragmentName] = true; + + const fragment = context.getFragment(fragmentName); + if (!fragment) { + return; + } + + const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, + ); + + // Do not compare a fragment's fieldMap to itself. + if (fieldMap === fieldMap2) { + return; + } + + // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2, + ); + + // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + for (let i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentNames2[i], + ); + } +} + +// Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. +function collectConflictsBetweenFragments( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + fragmentName1: string, + fragmentName2: string, +): void { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } + + // Memoize so two fragments are not compared for conflicts more than once. + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive, + ) + ) { + return; + } + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + if (!fragment1 || !fragment2) { + return; + } + + const [fieldMap1, fragmentNames1] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ); + const [fieldMap2, fragmentNames2] = getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2, + ); + + // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); + + // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentNames2[j], + ); + } + + // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + for (let i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentNames1[i], + fragmentName2, + ); + } +} + +// Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. +function findConflictsBetweenSubSelectionSets( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + areMutuallyExclusive: boolean, + parentType1: ?GraphQLNamedType, + selectionSet1: SelectionSetNode, + parentType2: ?GraphQLNamedType, + selectionSet2: SelectionSetNode, +): Array { + const conflicts = []; + + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1, + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2, + ); + + // (H) First, collect all conflicts between these two collections of field. + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); + + // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + if (fragmentNames2.length !== 0) { + const comparedFragments = Object.create(null); + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentNames2[j], + ); + } + } + + // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + if (fragmentNames1.length !== 0) { + const comparedFragments = Object.create(null); + for (let i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragments, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentNames1[i], + ); + } + } + + // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + for (let i = 0; i < fragmentNames1.length; i++) { + for (let j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentNames1[i], + fragmentNames2[j], + ); + } + } + return conflicts; +} + +// Collect all Conflicts "within" one collection of fields. +function collectConflictsWithin( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + fieldMap: NodeAndDefCollection, +): void { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const responseName of Object.keys(fieldMap)) { + const fields = fieldMap[responseName]; + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + false, // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j], + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} + +// Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. +function collectConflictsBetween( + context: ValidationContext, + conflicts: Array, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + fieldMap1: NodeAndDefCollection, + fieldMap2: NodeAndDefCollection, +): void { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const responseName of Object.keys(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + if (fields2) { + const fields1 = fieldMap1[responseName]; + for (let i = 0; i < fields1.length; i++) { + for (let j = 0; j < fields2.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + fields1[i], + fields2[j], + ); + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} + +// Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. +function findConflict( + context: ValidationContext, + cachedFieldsAndFragmentNames, + comparedFragmentPairs: PairSet, + parentFieldsAreMutuallyExclusive: boolean, + responseName: string, + field1: NodeAndDef, + field2: NodeAndDef, +): ?Conflict { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; + + // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + isObjectType(parentType1) && + isObjectType(parentType2)); + + // The return type for each field. + const type1 = def1 && def1.type; + const type2 = def2 && def2.type; + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + if (name1 !== name2) { + return [ + [responseName, `${name1} and ${name2} are different fields`], + [node1], + [node2], + ]; + } + + // Two field calls must have the same arguments. + if (!sameArguments(node1.arguments || [], node2.arguments || [])) { + return [ + [responseName, 'they have differing arguments'], + [node1], + [node2], + ]; + } + } + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types ${inspect(type1)} and ${inspect(type2)}`, + ], + [node1], + [node2], + ]; + } + + // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFragmentPairs, + areMutuallyExclusive, + getNamedType(type1), + selectionSet1, + getNamedType(type2), + selectionSet2, + ); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments( + arguments1: $ReadOnlyArray, + arguments2: $ReadOnlyArray, +): boolean { + if (arguments1.length !== arguments2.length) { + return false; + } + return arguments1.every(argument1 => { + const argument2 = find( + arguments2, + argument => argument.name.value === argument1.name.value, + ); + if (!argument2) { + return false; + } + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return (!value1 && !value2) || print(value1) === print(value2); +} + +// Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. +function doTypesConflict( + type1: GraphQLOutputType, + type2: GraphQLOutputType, +): boolean { + if (isListType(type1)) { + return isListType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isListType(type2)) { + return true; + } + if (isNonNullType(type1)) { + return isNonNullType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + if (isNonNullType(type2)) { + return true; + } + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + return false; +} + +// Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. +function getFieldsAndFragmentNames( + context: ValidationContext, + cachedFieldsAndFragmentNames, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, +): [NodeAndDefCollection, Array] { + let cached = cachedFieldsAndFragmentNames.get(selectionSet); + if (!cached) { + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, + ); + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + return cached; +} + +// Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. +function getReferencedFieldsAndFragmentNames( + context: ValidationContext, + cachedFieldsAndFragmentNames, + fragment: FragmentDefinitionNode, +) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + if (cached) { + return cached; + } + + const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet, + ); +} + +function _collectFieldsAndFragmentNames( + context: ValidationContext, + parentType: ?GraphQLNamedType, + selectionSet: SelectionSetNode, + nodeAndDefs, + fragmentNames, +): void { + for (let i = 0; i < selectionSet.selections.length; i++) { + const selection = selectionSet.selections[i]; + switch (selection.kind) { + case Kind.FIELD: + const fieldName = selection.name.value; + let fieldDef; + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + const responseName = selection.alias + ? selection.alias.value + : fieldName; + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + case Kind.INLINE_FRAGMENT: + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? typeFromAST(context.getSchema(), typeCondition) + : parentType; + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames, + ); + break; + } + } +} + +// Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. +function subfieldConflicts( + conflicts: Array, + responseName: string, + node1: FieldNode, + node2: FieldNode, +): ?Conflict { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + conflicts.reduce((allFields, [, fields1]) => allFields.concat(fields1), [ + node1, + ]), + conflicts.reduce( + (allFields, [, , fields2]) => allFields.concat(fields2), + [node2], + ), + ]; + } +} + +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ +class PairSet { + _data: ObjMap>; + + constructor(): void { + this._data = Object.create(null); + } + + has(a: string, b: string, areMutuallyExclusive: boolean) { + const first = this._data[a]; + const result = first && first[b]; + if (result === undefined) { + return false; + } + // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + if (areMutuallyExclusive === false) { + return result === false; + } + return true; + } + + add(a: string, b: string, areMutuallyExclusive: boolean) { + _pairSetAdd(this._data, a, b, areMutuallyExclusive); + _pairSetAdd(this._data, b, a, areMutuallyExclusive); + } +} + +function _pairSetAdd(data, a, b, areMutuallyExclusive) { + let map = data[a]; + if (!map) { + map = Object.create(null); + data[a] = map; + } + map[b] = areMutuallyExclusive; +} diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.mjs b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.mjs new file mode 100644 index 00000000..fce16c2b --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMerged.mjs @@ -0,0 +1,586 @@ +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import inspect from '../../jsutils/inspect'; +import find from '../../jsutils/find'; +import { Kind } from '../../language/kinds'; +import { print } from '../../language/printer'; +import { getNamedType, isNonNullType, isLeafType, isObjectType, isListType, isInterfaceType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function fieldsConflictMessage(responseName, reason) { + return "Fields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(reason), ". ") + 'Use different aliases on the fields to fetch both if this was intentional.'; +} + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason.map(function (_ref) { + var responseName = _ref[0], + subreason = _ref[1]; + return "subfields \"".concat(responseName, "\" conflict because ").concat(reasonMessage(subreason)); + }).join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + */ + + +export function OverlappingFieldsCanBeMerged(context) { + // A memoization for when two fragments are compared "between" each other for + // conflicts. Two fragments may be compared many times, so memoizing this can + // dramatically improve the performance of this validator. + var comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + var cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet: function SelectionSet(selectionSet) { + var conflicts = findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, context.getParentType(), selectionSet); + + for (var _i = 0; _i < conflicts.length; _i++) { + var _ref3 = conflicts[_i]; + var _ref2$ = _ref3[0]; + var responseName = _ref2$[0]; + var reason = _ref2$[1]; + var fields1 = _ref3[1]; + var fields2 = _ref3[2]; + context.reportError(new GraphQLError(fieldsConflictMessage(responseName, reason), fields1.concat(fields2))); + } + } + }; +} + +/** + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that a the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + */ +// Find all conflicts found "within" a selection set, including those found +// via spreading in fragments. Called when visiting each SelectionSet in the +// GraphQL Document. +function findConflictsWithinSelectionSet(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentType, selectionSet) { + var conflicts = []; + + var _getFieldsAndFragment = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet), + fieldMap = _getFieldsAndFragment[0], + fragmentNames = _getFieldsAndFragment[1]; // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + + collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + var comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, false, fieldMap, fragmentNames[i]); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (var j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, fragmentNames[i], fragmentNames[j]); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + + +function collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentName) { + // Memoize so a fragment is not compared for conflicts more than once. + if (comparedFragments[fragmentName]) { + return; + } + + comparedFragments[fragmentName] = true; + var fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + var _getReferencedFieldsA = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment), + fieldMap2 = _getReferencedFieldsA[0], + fragmentNames2 = _getReferencedFieldsA[1]; // Do not compare a fragment's fieldMap to itself. + + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fieldMap2); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (var i = 0; i < fragmentNames2.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap, fragmentNames2[i]); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + + +function collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentName2) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + + if (comparedFragmentPairs.has(fragmentName1, fragmentName2, areMutuallyExclusive)) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + var fragment1 = context.getFragment(fragmentName1); + var fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + var _getReferencedFieldsA2 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment1), + fieldMap1 = _getReferencedFieldsA2[0], + fragmentNames1 = _getReferencedFieldsA2[1]; + + var _getReferencedFieldsA3 = getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment2), + fieldMap2 = _getReferencedFieldsA3[0], + fragmentNames2 = _getReferencedFieldsA3[1]; // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentName1, fragmentNames2[j]); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[i], fragmentName2); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + + +function findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, parentType1, selectionSet1, parentType2, selectionSet2) { + var conflicts = []; + + var _getFieldsAndFragment2 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType1, selectionSet1), + fieldMap1 = _getFieldsAndFragment2[0], + fragmentNames1 = _getFieldsAndFragment2[1]; + + var _getFieldsAndFragment3 = getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType2, selectionSet2), + fieldMap2 = _getFieldsAndFragment3[0], + fragmentNames2 = _getFieldsAndFragment3[1]; // (H) First, collect all conflicts between these two collections of field. + + + collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fieldMap2); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + if (fragmentNames2.length !== 0) { + var comparedFragments = Object.create(null); + + for (var j = 0; j < fragmentNames2.length; j++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap1, fragmentNames2[j]); + } + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + + if (fragmentNames1.length !== 0) { + var _comparedFragments = Object.create(null); + + for (var i = 0; i < fragmentNames1.length; i++) { + collectConflictsBetweenFieldsAndFragment(context, conflicts, cachedFieldsAndFragmentNames, _comparedFragments, comparedFragmentPairs, areMutuallyExclusive, fieldMap2, fragmentNames1[i]); + } + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + + for (var _i2 = 0; _i2 < fragmentNames1.length; _i2++) { + for (var _j = 0; _j < fragmentNames2.length; _j++) { + collectConflictsBetweenFragments(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, fragmentNames1[_i2], fragmentNames2[_j]); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + + +function collectConflictsWithin(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, fieldMap) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + var _arr = Object.keys(fieldMap); + + for (var _i3 = 0; _i3 < _arr.length; _i3++) { + var responseName = _arr[_i3]; + var fields = fieldMap[responseName]; // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + + if (fields.length > 1) { + for (var i = 0; i < fields.length; i++) { + for (var j = i + 1; j < fields.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, false, // within one collection is never mutually exclusive + responseName, fields[i], fields[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + + +function collectConflictsBetween(context, conflicts, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, fieldMap1, fieldMap2) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + var _arr2 = Object.keys(fieldMap1); + + for (var _i4 = 0; _i4 < _arr2.length; _i4++) { + var responseName = _arr2[_i4]; + var fields2 = fieldMap2[responseName]; + + if (fields2) { + var fields1 = fieldMap1[responseName]; + + for (var i = 0; i < fields1.length; i++) { + for (var j = 0; j < fields2.length; j++) { + var conflict = findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, fields1[i], fields2[j]); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + + +function findConflict(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, parentFieldsAreMutuallyExclusive, responseName, field1, field2) { + var parentType1 = field1[0], + node1 = field1[1], + def1 = field1[2]; + var parentType2 = field2[0], + node2 = field2[1], + def2 = field2[2]; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + var areMutuallyExclusive = parentFieldsAreMutuallyExclusive || parentType1 !== parentType2 && isObjectType(parentType1) && isObjectType(parentType2); // The return type for each field. + + var type1 = def1 && def1.type; + var type2 = def2 && def2.type; + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + var name1 = node1.name.value; + var name2 = node2.name.value; + + if (name1 !== name2) { + return [[responseName, "".concat(name1, " and ").concat(name2, " are different fields")], [node1], [node2]]; + } // Two field calls must have the same arguments. + + + if (!sameArguments(node1.arguments || [], node2.arguments || [])) { + return [[responseName, 'they have differing arguments'], [node1], [node2]]; + } + } + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [[responseName, "they return conflicting types ".concat(inspect(type1), " and ").concat(inspect(type2))], [node1], [node2]]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + + var selectionSet1 = node1.selectionSet; + var selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + var conflicts = findConflictsBetweenSubSelectionSets(context, cachedFieldsAndFragmentNames, comparedFragmentPairs, areMutuallyExclusive, getNamedType(type1), selectionSet1, getNamedType(type2), selectionSet2); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(arguments1, arguments2) { + if (arguments1.length !== arguments2.length) { + return false; + } + + return arguments1.every(function (argument1) { + var argument2 = find(arguments2, function (argument) { + return argument.name.value === argument1.name.value; + }); + + if (!argument2) { + return false; + } + + return sameValue(argument1.value, argument2.value); + }); +} + +function sameValue(value1, value2) { + return !value1 && !value2 || print(value1) === print(value2); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + + +function doTypesConflict(type1, type2) { + if (isListType(type1)) { + return isListType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if (isListType(type2)) { + return true; + } + + if (isNonNullType(type1)) { + return isNonNullType(type2) ? doTypesConflict(type1.ofType, type2.ofType) : true; + } + + if (isNonNullType(type2)) { + return true; + } + + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + + +function getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, parentType, selectionSet) { + var cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (!cached) { + var nodeAndDefs = Object.create(null); + var fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames); + + cached = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, cached); + } + + return cached; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + + +function getReferencedFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragment) { + // Short-circuit building a type from the node if possible. + var cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + var fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames(context, cachedFieldsAndFragmentNames, fragmentType, fragment.selectionSet); +} + +function _collectFieldsAndFragmentNames(context, parentType, selectionSet, nodeAndDefs, fragmentNames) { + for (var i = 0; i < selectionSet.selections.length; i++) { + var selection = selectionSet.selections[i]; + + switch (selection.kind) { + case Kind.FIELD: + var fieldName = selection.name.value; + var fieldDef = void 0; + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + var responseName = selection.alias ? selection.alias.value : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case Kind.INLINE_FRAGMENT: + var typeCondition = selection.typeCondition; + var inlineFragmentType = typeCondition ? typeFromAST(context.getSchema(), typeCondition) : parentType; + + _collectFieldsAndFragmentNames(context, inlineFragmentType, selection.selectionSet, nodeAndDefs, fragmentNames); + + break; + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [[responseName, conflicts.map(function (_ref4) { + var reason = _ref4[0]; + return reason; + })], conflicts.reduce(function (allFields, _ref5) { + var fields1 = _ref5[1]; + return allFields.concat(fields1); + }, [node1]), conflicts.reduce(function (allFields, _ref6) { + var fields2 = _ref6[2]; + return allFields.concat(fields2); + }, [node2])]; + } +} +/** + * A way to keep track of pairs of things when the ordering of the pair does + * not matter. We do this by maintaining a sort of double adjacency sets. + */ + + +var PairSet = +/*#__PURE__*/ +function () { + function PairSet() { + _defineProperty(this, "_data", void 0); + + this._data = Object.create(null); + } + + var _proto = PairSet.prototype; + + _proto.has = function has(a, b, areMutuallyExclusive) { + var first = this._data[a]; + var result = first && first[b]; + + if (result === undefined) { + return false; + } // areMutuallyExclusive being false is a superset of being true, + // hence if we want to know if this PairSet "has" these two with no + // exclusivity, we have to ensure it was added as such. + + + if (areMutuallyExclusive === false) { + return result === false; + } + + return true; + }; + + _proto.add = function add(a, b, areMutuallyExclusive) { + _pairSetAdd(this._data, a, b, areMutuallyExclusive); + + _pairSetAdd(this._data, b, a, areMutuallyExclusive); + }; + + return PairSet; +}(); + +function _pairSetAdd(data, a, b, areMutuallyExclusive) { + var map = data[a]; + + if (!map) { + map = Object.create(null); + data[a] = map; + } + + map[b] = areMutuallyExclusive; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js new file mode 100644 index 00000000..28e1ae45 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js @@ -0,0 +1,78 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.typeIncompatibleSpreadMessage = typeIncompatibleSpreadMessage; +exports.typeIncompatibleAnonSpreadMessage = typeIncompatibleAnonSpreadMessage; +exports.PossibleFragmentSpreads = PossibleFragmentSpreads; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _GraphQLError = require("../../error/GraphQLError"); + +var _typeComparators = require("../../utilities/typeComparators"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +var _definition = require("../../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function typeIncompatibleSpreadMessage(fragName, parentType, fragType) { + return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of ") + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} + +function typeIncompatibleAnonSpreadMessage(parentType, fragType) { + return 'Fragment cannot be spread here as objects of ' + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ + + +function PossibleFragmentSpreads(context) { + return { + InlineFragment: function InlineFragment(node) { + var fragType = context.getType(); + var parentType = context.getParentType(); + + if ((0, _definition.isCompositeType)(fragType) && (0, _definition.isCompositeType)(parentType) && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleAnonSpreadMessage((0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), [node])); + } + }, + FragmentSpread: function FragmentSpread(node) { + var fragName = node.name.value; + var fragType = getFragmentType(context, fragName); + var parentType = context.getParentType(); + + if (fragType && parentType && !(0, _typeComparators.doTypesOverlap)(context.getSchema(), fragType, parentType)) { + context.reportError(new _GraphQLError.GraphQLError(typeIncompatibleSpreadMessage(fragName, (0, _inspect.default)(parentType), (0, _inspect.default)(fragType)), [node])); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + + if (frag) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), frag.typeCondition); + + if ((0, _definition.isCompositeType)(type)) { + return type; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js.flow b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js.flow new file mode 100644 index 00000000..bbcadae7 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.js.flow @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../../jsutils/inspect'; +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; +import { doTypesOverlap } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +import { isCompositeType } from '../../type/definition'; + +export function typeIncompatibleSpreadMessage( + fragName: string, + parentType: string, + fragType: string, +): string { + return ( + `Fragment "${fragName}" cannot be spread here as objects of ` + + `type "${parentType}" can never be of type "${fragType}".` + ); +} + +export function typeIncompatibleAnonSpreadMessage( + parentType: string, + fragType: string, +): string { + return ( + 'Fragment cannot be spread here as objects of ' + + `type "${parentType}" can never be of type "${fragType}".` + ); +} + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ +export function PossibleFragmentSpreads( + context: ValidationContext, +): ASTVisitor { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + if ( + isCompositeType(fragType) && + isCompositeType(parentType) && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + context.reportError( + new GraphQLError( + typeIncompatibleAnonSpreadMessage( + inspect(parentType), + inspect(fragType), + ), + [node], + ), + ); + } + }, + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + if ( + fragType && + parentType && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + context.reportError( + new GraphQLError( + typeIncompatibleSpreadMessage( + fragName, + inspect(parentType), + inspect(fragType), + ), + [node], + ), + ); + } + }, + }; +} + +function getFragmentType(context, name) { + const frag = context.getFragment(name); + if (frag) { + const type = typeFromAST(context.getSchema(), frag.typeCondition); + if (isCompositeType(type)) { + return type; + } + } +} diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreads.mjs b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.mjs new file mode 100644 index 00000000..9b0b858a --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreads.mjs @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../../jsutils/inspect'; +import { GraphQLError } from '../../error/GraphQLError'; +import { doTypesOverlap } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +import { isCompositeType } from '../../type/definition'; +export function typeIncompatibleSpreadMessage(fragName, parentType, fragType) { + return "Fragment \"".concat(fragName, "\" cannot be spread here as objects of ") + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} +export function typeIncompatibleAnonSpreadMessage(parentType, fragType) { + return 'Fragment cannot be spread here as objects of ' + "type \"".concat(parentType, "\" can never be of type \"").concat(fragType, "\"."); +} +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + */ + +export function PossibleFragmentSpreads(context) { + return { + InlineFragment: function InlineFragment(node) { + var fragType = context.getType(); + var parentType = context.getParentType(); + + if (isCompositeType(fragType) && isCompositeType(parentType) && !doTypesOverlap(context.getSchema(), fragType, parentType)) { + context.reportError(new GraphQLError(typeIncompatibleAnonSpreadMessage(inspect(parentType), inspect(fragType)), [node])); + } + }, + FragmentSpread: function FragmentSpread(node) { + var fragName = node.name.value; + var fragType = getFragmentType(context, fragName); + var parentType = context.getParentType(); + + if (fragType && parentType && !doTypesOverlap(context.getSchema(), fragType, parentType)) { + context.reportError(new GraphQLError(typeIncompatibleSpreadMessage(fragName, inspect(parentType), inspect(fragType)), [node])); + } + } + }; +} + +function getFragmentType(context, name) { + var frag = context.getFragment(name); + + if (frag) { + var type = typeFromAST(context.getSchema(), frag.typeCondition); + + if (isCompositeType(type)) { + return type; + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js new file mode 100644 index 00000000..cf2f12f6 --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js @@ -0,0 +1,185 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.missingFieldArgMessage = missingFieldArgMessage; +exports.missingDirectiveArgMessage = missingDirectiveArgMessage; +exports.ProvidedRequiredArguments = ProvidedRequiredArguments; +exports.ProvidedRequiredArgumentsOnDirectives = ProvidedRequiredArgumentsOnDirectives; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap")); + +var _definition = require("../../type/definition"); + +var _printer = require("../../language/printer"); + +var _directives = require("../../type/directives"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +function missingFieldArgMessage(fieldName, argName, type) { + return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} + +function missingDirectiveArgMessage(directiveName, argName, type) { + return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ + + +function ProvidedRequiredArguments(context) { + return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(fieldNode) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } + + var argNodes = fieldNode.arguments || []; + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fieldDef.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var argDef = _step.value; + var argNode = argNodeMap[argDef.name]; + + if (!argNode && (0, _definition.isRequiredArgument)(argDef)) { + context.reportError(new _GraphQLError.GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, (0, _inspect.default)(argDef.type)), [fieldNode])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }); +} // @internal + + +function ProvidedRequiredArgumentsOnDirectives(context) { + var requiredArgsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : _directives.specifiedDirectives; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = definedDirectives[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + requiredArgsMap[directive.name] = (0, _keyMap.default)(directive.args.filter(_definition.isRequiredArgument), function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = astDefinitions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var def = _step3.value; + + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + requiredArgsMap[def.name.value] = (0, _keyMap.default)(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) { + return arg.name.value; + }); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(directiveNode) { + var directiveName = directiveNode.name.value; + var requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var argNodes = directiveNode.arguments || []; + var argNodeMap = (0, _keyMap.default)(argNodes, function (arg) { + return arg.name.value; + }); + + var _arr = Object.keys(requiredArgs); + + for (var _i = 0; _i < _arr.length; _i++) { + var argName = _arr[_i]; + + if (!argNodeMap[argName]) { + var argType = requiredArgs[argName].type; + context.reportError(new _GraphQLError.GraphQLError(missingDirectiveArgMessage(directiveName, argName, (0, _definition.isType)(argType) ? (0, _inspect.default)(argType) : (0, _printer.print)(argType)), directiveNode)); + } + } + } + } + } + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js.flow b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js.flow new file mode 100644 index 00000000..7ed1c58e --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.js.flow @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { + ValidationContext, + SDLValidationContext, +} from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import inspect from '../../jsutils/inspect'; +import keyMap from '../../jsutils/keyMap'; +import { isType, isRequiredArgument } from '../../type/definition'; +import type { ASTVisitor } from '../../language/visitor'; +import { print } from '../../language/printer'; +import { specifiedDirectives } from '../../type/directives'; + +export function missingFieldArgMessage( + fieldName: string, + argName: string, + type: string, +): string { + return ( + `Field "${fieldName}" argument "${argName}" of type ` + + `"${type}" is required but not provided.` + ); +} + +export function missingDirectiveArgMessage( + directiveName: string, + argName: string, + type: string, +): string { + return ( + `Directive "@${directiveName}" argument "${argName}" of type ` + + `"${type}" is required but not provided.` + ); +} + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ +export function ProvidedRequiredArguments( + context: ValidationContext, +): ASTVisitor { + return { + ...ProvidedRequiredArgumentsOnDirectives(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + const fieldDef = context.getFieldDef(); + if (!fieldDef) { + return false; + } + const argNodes = fieldNode.arguments || []; + + const argNodeMap = keyMap(argNodes, arg => arg.name.value); + for (const argDef of fieldDef.args) { + const argNode = argNodeMap[argDef.name]; + if (!argNode && isRequiredArgument(argDef)) { + context.reportError( + new GraphQLError( + missingFieldArgMessage( + fieldDef.name, + argDef.name, + inspect(argDef.type), + ), + [fieldNode], + ), + ); + } + } + }, + }, + }; +} + +// @internal +export function ProvidedRequiredArgumentsOnDirectives( + context: ValidationContext | SDLValidationContext, +): ASTVisitor { + const requiredArgsMap = Object.create(null); + + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = keyMap( + directive.args.filter(isRequiredArgument), + arg => arg.name, + ); + } + + const astDefinitions = context.getDocument().definitions; + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + requiredArgsMap[def.name.value] = keyMap( + def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], + arg => arg.name.value, + ); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + if (requiredArgs) { + const argNodes = directiveNode.arguments || []; + const argNodeMap = keyMap(argNodes, arg => arg.name.value); + for (const argName of Object.keys(requiredArgs)) { + if (!argNodeMap[argName]) { + const argType = requiredArgs[argName].type; + context.reportError( + new GraphQLError( + missingDirectiveArgMessage( + directiveName, + argName, + isType(argType) ? inspect(argType) : print(argType), + ), + directiveNode, + ), + ); + } + } + } + }, + }, + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArguments.mjs b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.mjs new file mode 100644 index 00000000..0badafab --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArguments.mjs @@ -0,0 +1,171 @@ +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } + +function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import inspect from '../../jsutils/inspect'; +import keyMap from '../../jsutils/keyMap'; +import { isType, isRequiredArgument } from '../../type/definition'; +import { print } from '../../language/printer'; +import { specifiedDirectives } from '../../type/directives'; +export function missingFieldArgMessage(fieldName, argName, type) { + return "Field \"".concat(fieldName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} +export function missingDirectiveArgMessage(directiveName, argName, type) { + return "Directive \"@".concat(directiveName, "\" argument \"").concat(argName, "\" of type ") + "\"".concat(type, "\" is required but not provided."); +} +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + */ + +export function ProvidedRequiredArguments(context) { + return _objectSpread({}, ProvidedRequiredArgumentsOnDirectives(context), { + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(fieldNode) { + var fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } + + var argNodes = fieldNode.arguments || []; + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = fieldDef.args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var argDef = _step.value; + var argNode = argNodeMap[argDef.name]; + + if (!argNode && isRequiredArgument(argDef)) { + context.reportError(new GraphQLError(missingFieldArgMessage(fieldDef.name, argDef.name, inspect(argDef.type)), [fieldNode])); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }); +} // @internal + +export function ProvidedRequiredArgumentsOnDirectives(context) { + var requiredArgsMap = Object.create(null); + var schema = context.getSchema(); + var definedDirectives = schema ? schema.getDirectives() : specifiedDirectives; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = definedDirectives[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var directive = _step2.value; + requiredArgsMap[directive.name] = keyMap(directive.args.filter(isRequiredArgument), function (arg) { + return arg.name; + }); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var astDefinitions = context.getDocument().definitions; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = astDefinitions[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var def = _step3.value; + + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + requiredArgsMap[def.name.value] = keyMap(def.arguments ? def.arguments.filter(isRequiredArgumentNode) : [], function (arg) { + return arg.name.value; + }); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave: function leave(directiveNode) { + var directiveName = directiveNode.name.value; + var requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var argNodes = directiveNode.arguments || []; + var argNodeMap = keyMap(argNodes, function (arg) { + return arg.name.value; + }); + + var _arr = Object.keys(requiredArgs); + + for (var _i = 0; _i < _arr.length; _i++) { + var argName = _arr[_i]; + + if (!argNodeMap[argName]) { + var argType = requiredArgs[argName].type; + context.reportError(new GraphQLError(missingDirectiveArgMessage(directiveName, argName, isType(argType) ? inspect(argType) : print(argType)), directiveNode)); + } + } + } + } + } + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ScalarLeafs.js b/node_modules/graphql/validation/rules/ScalarLeafs.js new file mode 100644 index 00000000..55ae9a8d --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafs.js @@ -0,0 +1,58 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.noSubselectionAllowedMessage = noSubselectionAllowedMessage; +exports.requiredSubselectionMessage = requiredSubselectionMessage; +exports.ScalarLeafs = ScalarLeafs; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _GraphQLError = require("../../error/GraphQLError"); + +var _definition = require("../../type/definition"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function noSubselectionAllowedMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" must not have a selection since ") + "type \"".concat(type, "\" has no subfields."); +} + +function requiredSubselectionMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a ") + "selection of subfields. Did you mean \"".concat(fieldName, " { ... }\"?"); +} +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ + + +function ScalarLeafs(context) { + return { + Field: function Field(node) { + var type = context.getType(); + var selectionSet = node.selectionSet; + + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + context.reportError(new _GraphQLError.GraphQLError(noSubselectionAllowedMessage(node.name.value, (0, _inspect.default)(type)), [selectionSet])); + } + } else if (!selectionSet) { + context.reportError(new _GraphQLError.GraphQLError(requiredSubselectionMessage(node.name.value, (0, _inspect.default)(type)), [node])); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ScalarLeafs.js.flow b/node_modules/graphql/validation/rules/ScalarLeafs.js.flow new file mode 100644 index 00000000..b7fe0663 --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafs.js.flow @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../../jsutils/inspect'; +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { FieldNode } from '../../language/ast'; +import { getNamedType, isLeafType } from '../../type/definition'; +import type { ASTVisitor } from '../../language/visitor'; + +export function noSubselectionAllowedMessage( + fieldName: string, + type: string, +): string { + return ( + `Field "${fieldName}" must not have a selection since ` + + `type "${type}" has no subfields.` + ); +} + +export function requiredSubselectionMessage( + fieldName: string, + type: string, +): string { + return ( + `Field "${fieldName}" of type "${type}" must have a ` + + `selection of subfields. Did you mean "${fieldName} { ... }"?` + ); +} + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ +export function ScalarLeafs(context: ValidationContext): ASTVisitor { + return { + Field(node: FieldNode) { + const type = context.getType(); + const selectionSet = node.selectionSet; + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + context.reportError( + new GraphQLError( + noSubselectionAllowedMessage(node.name.value, inspect(type)), + [selectionSet], + ), + ); + } + } else if (!selectionSet) { + context.reportError( + new GraphQLError( + requiredSubselectionMessage(node.name.value, inspect(type)), + [node], + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ScalarLeafs.mjs b/node_modules/graphql/validation/rules/ScalarLeafs.mjs new file mode 100644 index 00000000..39d6d585 --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafs.mjs @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../../jsutils/inspect'; +import { GraphQLError } from '../../error/GraphQLError'; +import { getNamedType, isLeafType } from '../../type/definition'; +export function noSubselectionAllowedMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" must not have a selection since ") + "type \"".concat(type, "\" has no subfields."); +} +export function requiredSubselectionMessage(fieldName, type) { + return "Field \"".concat(fieldName, "\" of type \"").concat(type, "\" must have a ") + "selection of subfields. Did you mean \"".concat(fieldName, " { ... }\"?"); +} +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + */ + +export function ScalarLeafs(context) { + return { + Field: function Field(node) { + var type = context.getType(); + var selectionSet = node.selectionSet; + + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + context.reportError(new GraphQLError(noSubselectionAllowedMessage(node.name.value, inspect(type)), [selectionSet])); + } + } else if (!selectionSet) { + context.reportError(new GraphQLError(requiredSubselectionMessage(node.name.value, inspect(type)), [node])); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js new file mode 100644 index 00000000..602e4c70 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js @@ -0,0 +1,39 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.singleFieldOnlyMessage = singleFieldOnlyMessage; +exports.SingleFieldSubscriptions = SingleFieldSubscriptions; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function singleFieldOnlyMessage(name) { + return (name ? "Subscription \"".concat(name, "\" ") : 'Anonymous Subscription ') + 'must select only one top level field.'; +} +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ + + +function SingleFieldSubscriptions(context) { + return { + OperationDefinition: function OperationDefinition(node) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError(new _GraphQLError.GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1))); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js.flow b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js.flow new file mode 100644 index 00000000..6230a123 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.js.flow @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { OperationDefinitionNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +export function singleFieldOnlyMessage(name: ?string): string { + return ( + (name ? `Subscription "${name}" ` : 'Anonymous Subscription ') + + 'must select only one top level field.' + ); +} + +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ +export function SingleFieldSubscriptions( + context: ASTValidationContext, +): ASTVisitor { + return { + OperationDefinition(node: OperationDefinitionNode) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError( + new GraphQLError( + singleFieldOnlyMessage(node.name && node.name.value), + node.selectionSet.selections.slice(1), + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptions.mjs b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.mjs new file mode 100644 index 00000000..a0e5fcde --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptions.mjs @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function singleFieldOnlyMessage(name) { + return (name ? "Subscription \"".concat(name, "\" ") : 'Anonymous Subscription ') + 'must select only one top level field.'; +} +/** + * Subscriptions must only include one field. + * + * A GraphQL subscription is valid only if it contains a single root field. + */ + +export function SingleFieldSubscriptions(context) { + return { + OperationDefinition: function OperationDefinition(node) { + if (node.operation === 'subscription') { + if (node.selectionSet.selections.length !== 1) { + context.reportError(new GraphQLError(singleFieldOnlyMessage(node.name && node.name.value), node.selectionSet.selections.slice(1))); + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNames.js b/node_modules/graphql/validation/rules/UniqueArgumentNames.js new file mode 100644 index 00000000..e9aafefc --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNames.js @@ -0,0 +1,51 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateArgMessage = duplicateArgMessage; +exports.UniqueArgumentNames = UniqueArgumentNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateArgMessage(argName) { + return "There can be only one argument named \"".concat(argName, "\"."); +} +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ + + +function UniqueArgumentNames(context) { + var knownArgNames = Object.create(null); + return { + Field: function Field() { + knownArgNames = Object.create(null); + }, + Directive: function Directive() { + knownArgNames = Object.create(null); + }, + Argument: function Argument(node) { + var argName = node.name.value; + + if (knownArgNames[argName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNames.js.flow b/node_modules/graphql/validation/rules/UniqueArgumentNames.js.flow new file mode 100644 index 00000000..a49768c9 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNames.js.flow @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateArgMessage(argName: string): string { + return `There can be only one argument named "${argName}".`; +} + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ +export function UniqueArgumentNames(context: ASTValidationContext): ASTVisitor { + let knownArgNames = Object.create(null); + return { + Field() { + knownArgNames = Object.create(null); + }, + Directive() { + knownArgNames = Object.create(null); + }, + Argument(node) { + const argName = node.name.value; + if (knownArgNames[argName]) { + context.reportError( + new GraphQLError(duplicateArgMessage(argName), [ + knownArgNames[argName], + node.name, + ]), + ); + } else { + knownArgNames[argName] = node.name; + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNames.mjs b/node_modules/graphql/validation/rules/UniqueArgumentNames.mjs new file mode 100644 index 00000000..3a4b29eb --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNames.mjs @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateArgMessage(argName) { + return "There can be only one argument named \"".concat(argName, "\"."); +} +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + */ + +export function UniqueArgumentNames(context) { + var knownArgNames = Object.create(null); + return { + Field: function Field() { + knownArgNames = Object.create(null); + }, + Directive: function Directive() { + knownArgNames = Object.create(null); + }, + Argument: function Argument(node) { + var argName = node.name.value; + + if (knownArgNames[argName]) { + context.reportError(new GraphQLError(duplicateArgMessage(argName), [knownArgNames[argName], node.name])); + } else { + knownArgNames[argName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js new file mode 100644 index 00000000..bee96861 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js @@ -0,0 +1,73 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateDirectiveMessage = duplicateDirectiveMessage; +exports.UniqueDirectivesPerLocation = UniqueDirectivesPerLocation; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateDirectiveMessage(directiveName) { + return "The directive \"".concat(directiveName, "\" can only be used once at ") + 'this location.'; +} +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ + + +function UniqueDirectivesPerLocation(context) { + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter: function enter(node) { + // Flow can't refine that node.directives will only contain directives, + var directives = node.directives; + + if (directives) { + var knownDirectives = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = directives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + var directiveName = directive.name.value; + + if (knownDirectives[directiveName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive])); + } else { + knownDirectives[directiveName] = directive; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js.flow b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js.flow new file mode 100644 index 00000000..a866d81e --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.js.flow @@ -0,0 +1,57 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { DirectiveNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateDirectiveMessage(directiveName: string): string { + return ( + `The directive "${directiveName}" can only be used once at ` + + 'this location.' + ); +} + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ +export function UniqueDirectivesPerLocation( + context: ASTValidationContext, +): ASTVisitor { + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + // Flow can't refine that node.directives will only contain directives, + // so we cast so the rest of the code is well typed. + const directives: ?$ReadOnlyArray = (node: any).directives; + if (directives) { + const knownDirectives = Object.create(null); + for (const directive of directives) { + const directiveName = directive.name.value; + if (knownDirectives[directiveName]) { + context.reportError( + new GraphQLError(duplicateDirectiveMessage(directiveName), [ + knownDirectives[directiveName], + directive, + ]), + ); + } else { + knownDirectives[directiveName] = directive; + } + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.mjs b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.mjs new file mode 100644 index 00000000..d908fd3d --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocation.mjs @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateDirectiveMessage(directiveName) { + return "The directive \"".concat(directiveName, "\" can only be used once at ") + 'this location.'; +} +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all directives at a given location + * are uniquely named. + */ + +export function UniqueDirectivesPerLocation(context) { + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter: function enter(node) { + // Flow can't refine that node.directives will only contain directives, + var directives = node.directives; + + if (directives) { + var knownDirectives = Object.create(null); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = directives[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var directive = _step.value; + var directiveName = directive.name.value; + + if (knownDirectives[directiveName]) { + context.reportError(new GraphQLError(duplicateDirectiveMessage(directiveName), [knownDirectives[directiveName], directive])); + } else { + knownDirectives[directiveName] = directive; + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNames.js b/node_modules/graphql/validation/rules/UniqueFragmentNames.js new file mode 100644 index 00000000..12719b8c --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNames.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateFragmentNameMessage = duplicateFragmentNameMessage; +exports.UniqueFragmentNames = UniqueFragmentNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateFragmentNameMessage(fragName) { + return "There can be only one fragment named \"".concat(fragName, "\"."); +} +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ + + +function UniqueFragmentNames(context) { + var knownFragmentNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + var fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNames.js.flow b/node_modules/graphql/validation/rules/UniqueFragmentNames.js.flow new file mode 100644 index 00000000..b03a8a43 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNames.js.flow @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateFragmentNameMessage(fragName: string): string { + return `There can be only one fragment named "${fragName}".`; +} + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ +export function UniqueFragmentNames(context: ASTValidationContext): ASTVisitor { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + FragmentDefinition(node) { + const fragmentName = node.name.value; + if (knownFragmentNames[fragmentName]) { + context.reportError( + new GraphQLError(duplicateFragmentNameMessage(fragmentName), [ + knownFragmentNames[fragmentName], + node.name, + ]), + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNames.mjs b/node_modules/graphql/validation/rules/UniqueFragmentNames.mjs new file mode 100644 index 00000000..602a98ad --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNames.mjs @@ -0,0 +1,37 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateFragmentNameMessage(fragName) { + return "There can be only one fragment named \"".concat(fragName, "\"."); +} +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + */ + +export function UniqueFragmentNames(context) { + var knownFragmentNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + return false; + }, + FragmentDefinition: function FragmentDefinition(node) { + var fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError(new GraphQLError(duplicateFragmentNameMessage(fragmentName), [knownFragmentNames[fragmentName], node.name])); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNames.js b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js new file mode 100644 index 00000000..b1bab2a5 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js @@ -0,0 +1,55 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateInputFieldMessage = duplicateInputFieldMessage; +exports.UniqueInputFieldNames = UniqueInputFieldNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateInputFieldMessage(fieldName) { + return "There can be only one input field named \"".concat(fieldName, "\"."); +} +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ + + +function UniqueInputFieldNames(context) { + var knownNameStack = []; + var knownNames = Object.create(null); + return { + ObjectValue: { + enter: function enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave: function leave() { + knownNames = knownNameStack.pop(); + } + }, + ObjectField: function ObjectField(node) { + var fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNames.js.flow b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js.flow new file mode 100644 index 00000000..3a07772e --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNames.js.flow @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateInputFieldMessage(fieldName: string): string { + return `There can be only one input field named "${fieldName}".`; +} + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ +export function UniqueInputFieldNames( + context: ASTValidationContext, +): ASTVisitor { + const knownNameStack = []; + let knownNames = Object.create(null); + + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave() { + knownNames = knownNameStack.pop(); + }, + }, + ObjectField(node) { + const fieldName = node.name.value; + if (knownNames[fieldName]) { + context.reportError( + new GraphQLError(duplicateInputFieldMessage(fieldName), [ + knownNames[fieldName], + node.name, + ]), + ); + } else { + knownNames[fieldName] = node.name; + } + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNames.mjs b/node_modules/graphql/validation/rules/UniqueInputFieldNames.mjs new file mode 100644 index 00000000..c36424e0 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNames.mjs @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateInputFieldMessage(fieldName) { + return "There can be only one input field named \"".concat(fieldName, "\"."); +} +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + */ + +export function UniqueInputFieldNames(context) { + var knownNameStack = []; + var knownNames = Object.create(null); + return { + ObjectValue: { + enter: function enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + leave: function leave() { + knownNames = knownNameStack.pop(); + } + }, + ObjectField: function ObjectField(node) { + var fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError(new GraphQLError(duplicateInputFieldMessage(fieldName), [knownNames[fieldName], node.name])); + } else { + knownNames[fieldName] = node.name; + } + + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueOperationNames.js b/node_modules/graphql/validation/rules/UniqueOperationNames.js new file mode 100644 index 00000000..f64f323d --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNames.js @@ -0,0 +1,49 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateOperationNameMessage = duplicateOperationNameMessage; +exports.UniqueOperationNames = UniqueOperationNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateOperationNameMessage(operationName) { + return "There can be only one operation named \"".concat(operationName, "\"."); +} +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ + + +function UniqueOperationNames(context) { + var knownOperationNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition(node) { + var operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueOperationNames.js.flow b/node_modules/graphql/validation/rules/UniqueOperationNames.js.flow new file mode 100644 index 00000000..d4763467 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNames.js.flow @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateOperationNameMessage(operationName: string): string { + return `There can be only one operation named "${operationName}".`; +} + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ +export function UniqueOperationNames( + context: ASTValidationContext, +): ASTVisitor { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new GraphQLError( + duplicateOperationNameMessage(operationName.value), + [knownOperationNames[operationName.value], operationName], + ), + ); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + return false; + }, + FragmentDefinition: () => false, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueOperationNames.mjs b/node_modules/graphql/validation/rules/UniqueOperationNames.mjs new file mode 100644 index 00000000..2d6c1808 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNames.mjs @@ -0,0 +1,39 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateOperationNameMessage(operationName) { + return "There can be only one operation named \"".concat(operationName, "\"."); +} +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + */ + +export function UniqueOperationNames(context) { + var knownOperationNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition(node) { + var operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError(new GraphQLError(duplicateOperationNameMessage(operationName.value), [knownOperationNames[operationName.value], operationName])); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + FragmentDefinition: function FragmentDefinition() { + return false; + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueVariableNames.js b/node_modules/graphql/validation/rules/UniqueVariableNames.js new file mode 100644 index 00000000..d374cd06 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNames.js @@ -0,0 +1,45 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.duplicateVariableMessage = duplicateVariableMessage; +exports.UniqueVariableNames = UniqueVariableNames; + +var _GraphQLError = require("../../error/GraphQLError"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function duplicateVariableMessage(variableName) { + return "There can be only one variable named \"".concat(variableName, "\"."); +} +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + + +function UniqueVariableNames(context) { + var knownVariableNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition: function VariableDefinition(node) { + var variableName = node.variable.name.value; + + if (knownVariableNames[variableName]) { + context.reportError(new _GraphQLError.GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/UniqueVariableNames.js.flow b/node_modules/graphql/validation/rules/UniqueVariableNames.js.flow new file mode 100644 index 00000000..7020d289 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNames.js.flow @@ -0,0 +1,44 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ASTValidationContext } from '../ValidationContext'; +import type { VariableDefinitionNode } from '../../language/ast'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ASTVisitor } from '../../language/visitor'; + +export function duplicateVariableMessage(variableName: string): string { + return `There can be only one variable named "${variableName}".`; +} + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ +export function UniqueVariableNames(context: ASTValidationContext): ASTVisitor { + let knownVariableNames = Object.create(null); + return { + OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition(node: VariableDefinitionNode) { + const variableName = node.variable.name.value; + if (knownVariableNames[variableName]) { + context.reportError( + new GraphQLError(duplicateVariableMessage(variableName), [ + knownVariableNames[variableName], + node.variable.name, + ]), + ); + } else { + knownVariableNames[variableName] = node.variable.name; + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueVariableNames.mjs b/node_modules/graphql/validation/rules/UniqueVariableNames.mjs new file mode 100644 index 00000000..4c86f9d3 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNames.mjs @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +export function duplicateVariableMessage(variableName) { + return "There can be only one variable named \"".concat(variableName, "\"."); +} +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + */ + +export function UniqueVariableNames(context) { + var knownVariableNames = Object.create(null); + return { + OperationDefinition: function OperationDefinition() { + knownVariableNames = Object.create(null); + }, + VariableDefinition: function VariableDefinition(node) { + var variableName = node.variable.name.value; + + if (knownVariableNames[variableName]) { + context.reportError(new GraphQLError(duplicateVariableMessage(variableName), [knownVariableNames[variableName], node.variable.name])); + } else { + knownVariableNames[variableName] = node.variable.name; + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectType.js b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js new file mode 100644 index 00000000..18511190 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js @@ -0,0 +1,182 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.badValueMessage = badValueMessage; +exports.requiredFieldMessage = requiredFieldMessage; +exports.unknownFieldMessage = unknownFieldMessage; +exports.ValuesOfCorrectType = ValuesOfCorrectType; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _isInvalid = _interopRequireDefault(require("../../jsutils/isInvalid")); + +var _keyMap = _interopRequireDefault(require("../../jsutils/keyMap")); + +var _orList = _interopRequireDefault(require("../../jsutils/orList")); + +var _suggestionList = _interopRequireDefault(require("../../jsutils/suggestionList")); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function badValueMessage(typeName, valueName, message) { + return "Expected type ".concat(typeName, ", found ").concat(valueName) + (message ? "; ".concat(message) : '.'); +} + +function requiredFieldMessage(typeName, fieldName, fieldTypeName) { + return "Field ".concat(typeName, ".").concat(fieldName, " of required type ") + "".concat(fieldTypeName, " was not provided."); +} + +function unknownFieldMessage(typeName, fieldName, message) { + return "Field \"".concat(fieldName, "\" is not defined by type ").concat(typeName) + (message ? "; ".concat(message) : '.'); +} +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ + + +function ValuesOfCorrectType(context) { + return { + NullValue: function NullValue(node) { + var type = context.getInputType(); + + if ((0, _definition.isNonNullType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(type), (0, _printer.print)(node)), node)); + } + }, + ListValue: function ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + var type = (0, _definition.getNullableType)(context.getParentInputType()); + + if (!(0, _definition.isListType)(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue: function ObjectValue(node) { + var type = (0, _definition.getNamedType)(context.getInputType()); + + if (!(0, _definition.isInputObjectType)(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + + var inputFields = type.getFields(); + var fieldNodeMap = (0, _keyMap.default)(node.fields, function (field) { + return field.name.value; + }); + + var _arr = Object.keys(inputFields); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var fieldDef = inputFields[fieldName]; + var fieldNode = fieldNodeMap[fieldName]; + + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + var typeStr = (0, _inspect.default)(fieldDef.type); + context.reportError(new _GraphQLError.GraphQLError(requiredFieldMessage(type.name, fieldName, typeStr), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var parentType = (0, _definition.getNamedType)(context.getParentInputType()); + var fieldType = context.getInputType(); + + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + var suggestions = (0, _suggestionList.default)(node.name.value, Object.keys(parentType.getFields())); + var didYouMean = suggestions.length !== 0 ? "Did you mean ".concat((0, _orList.default)(suggestions), "?") : undefined; + context.reportError(new _GraphQLError.GraphQLError(unknownFieldMessage(parentType.name, node.name.value, didYouMean), node)); + } + }, + EnumValue: function EnumValue(node) { + var type = (0, _definition.getNamedType)(context.getInputType()); + + if (!(0, _definition.isEnumType)(type)) { + isValidScalar(context, node); + } else if (!type.getValue(node.value)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage(type.name, (0, _printer.print)(node), enumTypeSuggestion(type, node)), node)); + } + }, + IntValue: function IntValue(node) { + return isValidScalar(context, node); + }, + FloatValue: function FloatValue(node) { + return isValidScalar(context, node); + }, + StringValue: function StringValue(node) { + return isValidScalar(context, node); + }, + BooleanValue: function BooleanValue(node) { + return isValidScalar(context, node); + } + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + + +function isValidScalar(context, node) { + // Report any error at the full type expected by the location. + var locationType = context.getInputType(); + + if (!locationType) { + return; + } + + var type = (0, _definition.getNamedType)(locationType); + + if (!(0, _definition.isScalarType)(type)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), enumTypeSuggestion(type, node)), node)); + return; + } // Scalars determine if a literal value is valid via parseLiteral() which + // may throw or return an invalid value to indicate failure. + + + try { + var parseResult = type.parseLiteral(node, undefined + /* variables */ + ); + + if ((0, _isInvalid.default)(parseResult)) { + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node)), node)); + } + } catch (error) { + // Ensure a reference to the original error is maintained. + context.reportError(new _GraphQLError.GraphQLError(badValueMessage((0, _inspect.default)(locationType), (0, _printer.print)(node), error.message), node, undefined, undefined, undefined, error)); + } +} + +function enumTypeSuggestion(type, node) { + if ((0, _definition.isEnumType)(type)) { + var suggestions = (0, _suggestionList.default)((0, _printer.print)(node), type.getValues().map(function (value) { + return value.name; + })); + + if (suggestions.length !== 0) { + return "Did you mean the enum value ".concat((0, _orList.default)(suggestions), "?"); + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectType.js.flow b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js.flow new file mode 100644 index 00000000..8df13583 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectType.js.flow @@ -0,0 +1,221 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { ValueNode } from '../../language/ast'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { + isScalarType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isRequiredInputField, + getNullableType, + getNamedType, +} from '../../type/definition'; +import type { GraphQLType } from '../../type/definition'; +import inspect from '../../jsutils/inspect'; +import isInvalid from '../../jsutils/isInvalid'; +import keyMap from '../../jsutils/keyMap'; +import orList from '../../jsutils/orList'; +import suggestionList from '../../jsutils/suggestionList'; + +export function badValueMessage( + typeName: string, + valueName: string, + message?: string, +): string { + return ( + `Expected type ${typeName}, found ${valueName}` + + (message ? `; ${message}` : '.') + ); +} + +export function requiredFieldMessage( + typeName: string, + fieldName: string, + fieldTypeName: string, +): string { + return ( + `Field ${typeName}.${fieldName} of required type ` + + `${fieldTypeName} was not provided.` + ); +} + +export function unknownFieldMessage( + typeName: string, + fieldName: string, + message?: string, +): string { + return ( + `Field "${fieldName}" is not defined by type ${typeName}` + + (message ? `; ${message}` : '.') + ); +} + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ +export function ValuesOfCorrectType(context: ValidationContext): ASTVisitor { + return { + NullValue(node) { + const type = context.getInputType(); + if (isNonNullType(type)) { + context.reportError( + new GraphQLError(badValueMessage(inspect(type), print(node)), node), + ); + } + }, + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = getNullableType(context.getParentInputType()); + if (!isListType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue(node) { + const type = getNamedType(context.getInputType()); + if (!isInputObjectType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + // Ensure every required field exists. + const inputFields = type.getFields(); + const fieldNodeMap = keyMap(node.fields, field => field.name.value); + for (const fieldName of Object.keys(inputFields)) { + const fieldDef = inputFields[fieldName]; + const fieldNode = fieldNodeMap[fieldName]; + if (!fieldNode && isRequiredInputField(fieldDef)) { + const typeStr = inspect(fieldDef.type); + context.reportError( + new GraphQLError( + requiredFieldMessage(type.name, fieldName, typeStr), + node, + ), + ); + } + } + }, + ObjectField(node) { + const parentType = getNamedType(context.getParentInputType()); + const fieldType = context.getInputType(); + if (!fieldType && isInputObjectType(parentType)) { + const suggestions = suggestionList( + node.name.value, + Object.keys(parentType.getFields()), + ); + const didYouMean = + suggestions.length !== 0 + ? `Did you mean ${orList(suggestions)}?` + : undefined; + context.reportError( + new GraphQLError( + unknownFieldMessage(parentType.name, node.name.value, didYouMean), + node, + ), + ); + } + }, + EnumValue(node) { + const type = getNamedType(context.getInputType()); + if (!isEnumType(type)) { + isValidScalar(context, node); + } else if (!type.getValue(node.value)) { + context.reportError( + new GraphQLError( + badValueMessage( + type.name, + print(node), + enumTypeSuggestion(type, node), + ), + node, + ), + ); + } + }, + IntValue: node => isValidScalar(context, node), + FloatValue: node => isValidScalar(context, node), + StringValue: node => isValidScalar(context, node), + BooleanValue: node => isValidScalar(context, node), + }; +} + +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ +function isValidScalar(context: ValidationContext, node: ValueNode): void { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + if (!locationType) { + return; + } + + const type = getNamedType(locationType); + + if (!isScalarType(type)) { + context.reportError( + new GraphQLError( + badValueMessage( + inspect(locationType), + print(node), + enumTypeSuggestion(type, node), + ), + node, + ), + ); + return; + } + + // Scalars determine if a literal value is valid via parseLiteral() which + // may throw or return an invalid value to indicate failure. + try { + const parseResult = type.parseLiteral(node, undefined /* variables */); + if (isInvalid(parseResult)) { + context.reportError( + new GraphQLError( + badValueMessage(inspect(locationType), print(node)), + node, + ), + ); + } + } catch (error) { + // Ensure a reference to the original error is maintained. + context.reportError( + new GraphQLError( + badValueMessage(inspect(locationType), print(node), error.message), + node, + undefined, + undefined, + undefined, + error, + ), + ); + } +} + +function enumTypeSuggestion(type: GraphQLType, node: ValueNode): string | void { + if (isEnumType(type)) { + const suggestions = suggestionList( + print(node), + type.getValues().map(value => value.name), + ); + if (suggestions.length !== 0) { + return `Did you mean the enum value ${orList(suggestions)}?`; + } + } +} diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectType.mjs b/node_modules/graphql/validation/rules/ValuesOfCorrectType.mjs new file mode 100644 index 00000000..a1907c0d --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectType.mjs @@ -0,0 +1,158 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import { isScalarType, isEnumType, isInputObjectType, isListType, isNonNullType, isRequiredInputField, getNullableType, getNamedType } from '../../type/definition'; +import inspect from '../../jsutils/inspect'; +import isInvalid from '../../jsutils/isInvalid'; +import keyMap from '../../jsutils/keyMap'; +import orList from '../../jsutils/orList'; +import suggestionList from '../../jsutils/suggestionList'; +export function badValueMessage(typeName, valueName, message) { + return "Expected type ".concat(typeName, ", found ").concat(valueName) + (message ? "; ".concat(message) : '.'); +} +export function requiredFieldMessage(typeName, fieldName, fieldTypeName) { + return "Field ".concat(typeName, ".").concat(fieldName, " of required type ") + "".concat(fieldTypeName, " was not provided."); +} +export function unknownFieldMessage(typeName, fieldName, message) { + return "Field \"".concat(fieldName, "\" is not defined by type ").concat(typeName) + (message ? "; ".concat(message) : '.'); +} +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + */ + +export function ValuesOfCorrectType(context) { + return { + NullValue: function NullValue(node) { + var type = context.getInputType(); + + if (isNonNullType(type)) { + context.reportError(new GraphQLError(badValueMessage(inspect(type), print(node)), node)); + } + }, + ListValue: function ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + var type = getNullableType(context.getParentInputType()); + + if (!isListType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } + }, + ObjectValue: function ObjectValue(node) { + var type = getNamedType(context.getInputType()); + + if (!isInputObjectType(type)) { + isValidScalar(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + + var inputFields = type.getFields(); + var fieldNodeMap = keyMap(node.fields, function (field) { + return field.name.value; + }); + + var _arr = Object.keys(inputFields); + + for (var _i = 0; _i < _arr.length; _i++) { + var fieldName = _arr[_i]; + var fieldDef = inputFields[fieldName]; + var fieldNode = fieldNodeMap[fieldName]; + + if (!fieldNode && isRequiredInputField(fieldDef)) { + var typeStr = inspect(fieldDef.type); + context.reportError(new GraphQLError(requiredFieldMessage(type.name, fieldName, typeStr), node)); + } + } + }, + ObjectField: function ObjectField(node) { + var parentType = getNamedType(context.getParentInputType()); + var fieldType = context.getInputType(); + + if (!fieldType && isInputObjectType(parentType)) { + var suggestions = suggestionList(node.name.value, Object.keys(parentType.getFields())); + var didYouMean = suggestions.length !== 0 ? "Did you mean ".concat(orList(suggestions), "?") : undefined; + context.reportError(new GraphQLError(unknownFieldMessage(parentType.name, node.name.value, didYouMean), node)); + } + }, + EnumValue: function EnumValue(node) { + var type = getNamedType(context.getInputType()); + + if (!isEnumType(type)) { + isValidScalar(context, node); + } else if (!type.getValue(node.value)) { + context.reportError(new GraphQLError(badValueMessage(type.name, print(node), enumTypeSuggestion(type, node)), node)); + } + }, + IntValue: function IntValue(node) { + return isValidScalar(context, node); + }, + FloatValue: function FloatValue(node) { + return isValidScalar(context, node); + }, + StringValue: function StringValue(node) { + return isValidScalar(context, node); + }, + BooleanValue: function BooleanValue(node) { + return isValidScalar(context, node); + } + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + */ + +function isValidScalar(context, node) { + // Report any error at the full type expected by the location. + var locationType = context.getInputType(); + + if (!locationType) { + return; + } + + var type = getNamedType(locationType); + + if (!isScalarType(type)) { + context.reportError(new GraphQLError(badValueMessage(inspect(locationType), print(node), enumTypeSuggestion(type, node)), node)); + return; + } // Scalars determine if a literal value is valid via parseLiteral() which + // may throw or return an invalid value to indicate failure. + + + try { + var parseResult = type.parseLiteral(node, undefined + /* variables */ + ); + + if (isInvalid(parseResult)) { + context.reportError(new GraphQLError(badValueMessage(inspect(locationType), print(node)), node)); + } + } catch (error) { + // Ensure a reference to the original error is maintained. + context.reportError(new GraphQLError(badValueMessage(inspect(locationType), print(node), error.message), node, undefined, undefined, undefined, error)); + } +} + +function enumTypeSuggestion(type, node) { + if (isEnumType(type)) { + var suggestions = suggestionList(print(node), type.getValues().map(function (value) { + return value.name; + })); + + if (suggestions.length !== 0) { + return "Did you mean the enum value ".concat(orList(suggestions), "?"); + } + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypes.js b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js new file mode 100644 index 00000000..b4853b63 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js @@ -0,0 +1,47 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.nonInputTypeOnVarMessage = nonInputTypeOnVarMessage; +exports.VariablesAreInputTypes = VariablesAreInputTypes; + +var _GraphQLError = require("../../error/GraphQLError"); + +var _printer = require("../../language/printer"); + +var _definition = require("../../type/definition"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function nonInputTypeOnVarMessage(variableName, typeName) { + return "Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."); +} +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ + + +function VariablesAreInputTypes(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var type = (0, _typeFromAST.typeFromAST)(context.getSchema(), node.type); // If the variable type is not an input type, return an error. + + if (type && !(0, _definition.isInputType)(type)) { + var variableName = node.variable.name.value; + context.reportError(new _GraphQLError.GraphQLError(nonInputTypeOnVarMessage(variableName, (0, _printer.print)(node.type)), [node.type])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypes.js.flow b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js.flow new file mode 100644 index 00000000..455cfdac --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypes.js.flow @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import type { VariableDefinitionNode } from '../../language/ast'; +import { print } from '../../language/printer'; +import type { ASTVisitor } from '../../language/visitor'; +import { isInputType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; + +export function nonInputTypeOnVarMessage( + variableName: string, + typeName: string, +): string { + return `Variable "$${variableName}" cannot be non-input type "${typeName}".`; +} + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ +export function VariablesAreInputTypes(context: ValidationContext): ASTVisitor { + return { + VariableDefinition(node: VariableDefinitionNode): ?GraphQLError { + const type = typeFromAST(context.getSchema(), node.type); + + // If the variable type is not an input type, return an error. + if (type && !isInputType(type)) { + const variableName = node.variable.name.value; + context.reportError( + new GraphQLError( + nonInputTypeOnVarMessage(variableName, print(node.type)), + [node.type], + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypes.mjs b/node_modules/graphql/validation/rules/VariablesAreInputTypes.mjs new file mode 100644 index 00000000..d1810d08 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypes.mjs @@ -0,0 +1,34 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import { GraphQLError } from '../../error/GraphQLError'; +import { print } from '../../language/printer'; +import { isInputType } from '../../type/definition'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function nonInputTypeOnVarMessage(variableName, typeName) { + return "Variable \"$".concat(variableName, "\" cannot be non-input type \"").concat(typeName, "\"."); +} +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + */ + +export function VariablesAreInputTypes(context) { + return { + VariableDefinition: function VariableDefinition(node) { + var type = typeFromAST(context.getSchema(), node.type); // If the variable type is not an input type, return an error. + + if (type && !isInputType(type)) { + var variableName = node.variable.name.value; + context.reportError(new GraphQLError(nonInputTypeOnVarMessage(variableName, print(node.type)), [node.type])); + } + } + }; +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js new file mode 100644 index 00000000..7c4fdd02 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js @@ -0,0 +1,117 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.badVarPosMessage = badVarPosMessage; +exports.VariablesInAllowedPosition = VariablesInAllowedPosition; + +var _inspect = _interopRequireDefault(require("../../jsutils/inspect")); + +var _GraphQLError = require("../../error/GraphQLError"); + +var _kinds = require("../../language/kinds"); + +var _definition = require("../../type/definition"); + +var _typeComparators = require("../../utilities/typeComparators"); + +var _typeFromAST = require("../../utilities/typeFromAST"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +function badVarPosMessage(varName, varType, expectedType) { + return "Variable \"$".concat(varName, "\" of type \"").concat(varType, "\" used in ") + "position expecting type \"".concat(expectedType, "\"."); +} +/** + * Variables passed to field arguments conform to type + */ + + +function VariablesInAllowedPosition(context) { + var varDefMap = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + varDefMap = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node, + type = _ref2.type, + defaultValue = _ref2.defaultValue; + var varName = node.name.value; + var varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + var schema = context.getSchema(); + var varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + context.reportError(new _GraphQLError.GraphQLError(badVarPosMessage(varName, (0, _inspect.default)(varType), (0, _inspect.default)(type)), [varDef, node])); + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if ((0, _definition.isNonNullType)(locationType) && !(0, _definition.isNonNullType)(varType)) { + var hasNonNullVariableDefaultValue = varDefaultValue && varDefaultValue.kind !== _kinds.Kind.NULL; + var hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + var nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, nullableLocationType); + } + + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); +} \ No newline at end of file diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js.flow b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js.flow new file mode 100644 index 00000000..5b1f017a --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.js.flow @@ -0,0 +1,110 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import inspect from '../../jsutils/inspect'; +import type { ValidationContext } from '../ValidationContext'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import type { ValueNode } from '../../language/ast'; +import type { ASTVisitor } from '../../language/visitor'; +import { isNonNullType } from '../../type/definition'; +import { isTypeSubTypeOf } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +import type { GraphQLType } from '../../type/definition'; +import type { GraphQLSchema } from '../../type/schema'; + +export function badVarPosMessage( + varName: string, + varType: string, + expectedType: string, +): string { + return ( + `Variable "$${varName}" of type "${varType}" used in ` + + `position expecting type "${expectedType}".` + ); +} + +/** + * Variables passed to field arguments conform to type + */ +export function VariablesInAllowedPosition( + context: ValidationContext, +): ASTVisitor { + let varDefMap = Object.create(null); + + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node, type, defaultValue } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = typeFromAST(schema, varDef.type); + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue, + ) + ) { + context.reportError( + new GraphQLError( + badVarPosMessage(varName, inspect(varType), inspect(type)), + [varDef, node], + ), + ); + } + } + } + }, + }, + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; +} + +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ +function allowedVariableUsage( + schema: GraphQLSchema, + varType: GraphQLType, + varDefaultValue: ?ValueNode, + locationType: GraphQLType, + locationDefaultValue: ?mixed, +): boolean { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + const hasNonNullVariableDefaultValue = + varDefaultValue && varDefaultValue.kind !== Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + const nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + return isTypeSubTypeOf(schema, varType, locationType); +} diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPosition.mjs b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.mjs new file mode 100644 index 00000000..c039ecba --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPosition.mjs @@ -0,0 +1,99 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import inspect from '../../jsutils/inspect'; +import { GraphQLError } from '../../error/GraphQLError'; +import { Kind } from '../../language/kinds'; +import { isNonNullType } from '../../type/definition'; +import { isTypeSubTypeOf } from '../../utilities/typeComparators'; +import { typeFromAST } from '../../utilities/typeFromAST'; +export function badVarPosMessage(varName, varType, expectedType) { + return "Variable \"$".concat(varName, "\" of type \"").concat(varType, "\" used in ") + "position expecting type \"".concat(expectedType, "\"."); +} +/** + * Variables passed to field arguments conform to type + */ + +export function VariablesInAllowedPosition(context) { + var varDefMap = Object.create(null); + return { + OperationDefinition: { + enter: function enter() { + varDefMap = Object.create(null); + }, + leave: function leave(operation) { + var usages = context.getRecursiveVariableUsages(operation); + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = usages[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _ref2 = _step.value; + var node = _ref2.node, + type = _ref2.type, + defaultValue = _ref2.defaultValue; + var varName = node.name.value; + var varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + var schema = context.getSchema(); + var varType = typeFromAST(schema, varDef.type); + + if (varType && !allowedVariableUsage(schema, varType, varDef.defaultValue, type, defaultValue)) { + context.reportError(new GraphQLError(badVarPosMessage(varName, inspect(varType), inspect(type)), [varDef, node])); + } + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + }, + VariableDefinition: function VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + } + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * which includes considering if default values exist for either the variable + * or the location at which it is located. + */ + +function allowedVariableUsage(schema, varType, varDefaultValue, locationType, locationDefaultValue) { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + var hasNonNullVariableDefaultValue = varDefaultValue && varDefaultValue.kind !== Kind.NULL; + var hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + var nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + + return isTypeSubTypeOf(schema, varType, locationType); +} \ No newline at end of file diff --git a/node_modules/graphql/validation/specifiedRules.js b/node_modules/graphql/validation/specifiedRules.js new file mode 100644 index 00000000..9065587c --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.js @@ -0,0 +1,107 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.specifiedSDLRules = exports.specifiedRules = void 0; + +var _ExecutableDefinitions = require("./rules/ExecutableDefinitions"); + +var _UniqueOperationNames = require("./rules/UniqueOperationNames"); + +var _LoneAnonymousOperation = require("./rules/LoneAnonymousOperation"); + +var _SingleFieldSubscriptions = require("./rules/SingleFieldSubscriptions"); + +var _KnownTypeNames = require("./rules/KnownTypeNames"); + +var _FragmentsOnCompositeTypes = require("./rules/FragmentsOnCompositeTypes"); + +var _VariablesAreInputTypes = require("./rules/VariablesAreInputTypes"); + +var _ScalarLeafs = require("./rules/ScalarLeafs"); + +var _FieldsOnCorrectType = require("./rules/FieldsOnCorrectType"); + +var _UniqueFragmentNames = require("./rules/UniqueFragmentNames"); + +var _KnownFragmentNames = require("./rules/KnownFragmentNames"); + +var _NoUnusedFragments = require("./rules/NoUnusedFragments"); + +var _PossibleFragmentSpreads = require("./rules/PossibleFragmentSpreads"); + +var _NoFragmentCycles = require("./rules/NoFragmentCycles"); + +var _UniqueVariableNames = require("./rules/UniqueVariableNames"); + +var _NoUndefinedVariables = require("./rules/NoUndefinedVariables"); + +var _NoUnusedVariables = require("./rules/NoUnusedVariables"); + +var _KnownDirectives = require("./rules/KnownDirectives"); + +var _UniqueDirectivesPerLocation = require("./rules/UniqueDirectivesPerLocation"); + +var _KnownArgumentNames = require("./rules/KnownArgumentNames"); + +var _UniqueArgumentNames = require("./rules/UniqueArgumentNames"); + +var _ValuesOfCorrectType = require("./rules/ValuesOfCorrectType"); + +var _ProvidedRequiredArguments = require("./rules/ProvidedRequiredArguments"); + +var _VariablesInAllowedPosition = require("./rules/VariablesInAllowedPosition"); + +var _OverlappingFieldsCanBeMerged = require("./rules/OverlappingFieldsCanBeMerged"); + +var _UniqueInputFieldNames = require("./rules/UniqueInputFieldNames"); + +var _LoneSchemaDefinition = require("./rules/LoneSchemaDefinition"); + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// Spec Section: "Executable Definitions" +// Spec Section: "Operation Name Uniqueness" +// Spec Section: "Lone Anonymous Operation" +// Spec Section: "Subscriptions with Single Root Field" +// Spec Section: "Fragment Spread Type Existence" +// Spec Section: "Fragments on Composite Types" +// Spec Section: "Variables are Input Types" +// Spec Section: "Leaf Field Selections" +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +// Spec Section: "Fragment Name Uniqueness" +// Spec Section: "Fragment spread target defined" +// Spec Section: "Fragments must be used" +// Spec Section: "Fragment spread is possible" +// Spec Section: "Fragments must not form cycles" +// Spec Section: "Variable Uniqueness" +// Spec Section: "All Variable Used Defined" +// Spec Section: "All Variables Used" +// Spec Section: "Directives Are Defined" +// Spec Section: "Directives Are Unique Per Location" +// Spec Section: "Argument Names" +// Spec Section: "Argument Uniqueness" +// Spec Section: "Value Type Correctness" +// Spec Section: "Argument Optionality" +// Spec Section: "All Variable Usages Are Allowed" +// Spec Section: "Field Selection Merging" +// Spec Section: "Input Object Field Uniqueness" + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +var specifiedRules = [_ExecutableDefinitions.ExecutableDefinitions, _UniqueOperationNames.UniqueOperationNames, _LoneAnonymousOperation.LoneAnonymousOperation, _SingleFieldSubscriptions.SingleFieldSubscriptions, _KnownTypeNames.KnownTypeNames, _FragmentsOnCompositeTypes.FragmentsOnCompositeTypes, _VariablesAreInputTypes.VariablesAreInputTypes, _ScalarLeafs.ScalarLeafs, _FieldsOnCorrectType.FieldsOnCorrectType, _UniqueFragmentNames.UniqueFragmentNames, _KnownFragmentNames.KnownFragmentNames, _NoUnusedFragments.NoUnusedFragments, _PossibleFragmentSpreads.PossibleFragmentSpreads, _NoFragmentCycles.NoFragmentCycles, _UniqueVariableNames.UniqueVariableNames, _NoUndefinedVariables.NoUndefinedVariables, _NoUnusedVariables.NoUnusedVariables, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _KnownArgumentNames.KnownArgumentNames, _UniqueArgumentNames.UniqueArgumentNames, _ValuesOfCorrectType.ValuesOfCorrectType, _ProvidedRequiredArguments.ProvidedRequiredArguments, _VariablesInAllowedPosition.VariablesInAllowedPosition, _OverlappingFieldsCanBeMerged.OverlappingFieldsCanBeMerged, _UniqueInputFieldNames.UniqueInputFieldNames]; +exports.specifiedRules = specifiedRules; +// @internal +var specifiedSDLRules = [_LoneSchemaDefinition.LoneSchemaDefinition, _KnownDirectives.KnownDirectives, _UniqueDirectivesPerLocation.UniqueDirectivesPerLocation, _KnownArgumentNames.KnownArgumentNamesOnDirectives, _UniqueArgumentNames.UniqueArgumentNames, _UniqueInputFieldNames.UniqueInputFieldNames, _ProvidedRequiredArguments.ProvidedRequiredArgumentsOnDirectives]; +exports.specifiedSDLRules = specifiedSDLRules; \ No newline at end of file diff --git a/node_modules/graphql/validation/specifiedRules.js.flow b/node_modules/graphql/validation/specifiedRules.js.flow new file mode 100644 index 00000000..f4e1960b --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.js.flow @@ -0,0 +1,138 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import type { ValidationRule, SDLValidationRule } from './ValidationContext'; + +// Spec Section: "Executable Definitions" +import { ExecutableDefinitions } from './rules/ExecutableDefinitions'; + +// Spec Section: "Operation Name Uniqueness" +import { UniqueOperationNames } from './rules/UniqueOperationNames'; + +// Spec Section: "Lone Anonymous Operation" +import { LoneAnonymousOperation } from './rules/LoneAnonymousOperation'; + +// Spec Section: "Subscriptions with Single Root Field" +import { SingleFieldSubscriptions } from './rules/SingleFieldSubscriptions'; + +// Spec Section: "Fragment Spread Type Existence" +import { KnownTypeNames } from './rules/KnownTypeNames'; + +// Spec Section: "Fragments on Composite Types" +import { FragmentsOnCompositeTypes } from './rules/FragmentsOnCompositeTypes'; + +// Spec Section: "Variables are Input Types" +import { VariablesAreInputTypes } from './rules/VariablesAreInputTypes'; + +// Spec Section: "Leaf Field Selections" +import { ScalarLeafs } from './rules/ScalarLeafs'; + +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +import { FieldsOnCorrectType } from './rules/FieldsOnCorrectType'; + +// Spec Section: "Fragment Name Uniqueness" +import { UniqueFragmentNames } from './rules/UniqueFragmentNames'; + +// Spec Section: "Fragment spread target defined" +import { KnownFragmentNames } from './rules/KnownFragmentNames'; + +// Spec Section: "Fragments must be used" +import { NoUnusedFragments } from './rules/NoUnusedFragments'; + +// Spec Section: "Fragment spread is possible" +import { PossibleFragmentSpreads } from './rules/PossibleFragmentSpreads'; + +// Spec Section: "Fragments must not form cycles" +import { NoFragmentCycles } from './rules/NoFragmentCycles'; + +// Spec Section: "Variable Uniqueness" +import { UniqueVariableNames } from './rules/UniqueVariableNames'; + +// Spec Section: "All Variable Used Defined" +import { NoUndefinedVariables } from './rules/NoUndefinedVariables'; + +// Spec Section: "All Variables Used" +import { NoUnusedVariables } from './rules/NoUnusedVariables'; + +// Spec Section: "Directives Are Defined" +import { KnownDirectives } from './rules/KnownDirectives'; + +// Spec Section: "Directives Are Unique Per Location" +import { UniqueDirectivesPerLocation } from './rules/UniqueDirectivesPerLocation'; + +// Spec Section: "Argument Names" +import { KnownArgumentNames } from './rules/KnownArgumentNames'; + +// Spec Section: "Argument Uniqueness" +import { UniqueArgumentNames } from './rules/UniqueArgumentNames'; + +// Spec Section: "Value Type Correctness" +import { ValuesOfCorrectType } from './rules/ValuesOfCorrectType'; + +// Spec Section: "Argument Optionality" +import { ProvidedRequiredArguments } from './rules/ProvidedRequiredArguments'; + +// Spec Section: "All Variable Usages Are Allowed" +import { VariablesInAllowedPosition } from './rules/VariablesInAllowedPosition'; + +// Spec Section: "Field Selection Merging" +import { OverlappingFieldsCanBeMerged } from './rules/OverlappingFieldsCanBeMerged'; + +// Spec Section: "Input Object Field Uniqueness" +import { UniqueInputFieldNames } from './rules/UniqueInputFieldNames'; + +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +export const specifiedRules: $ReadOnlyArray = [ + ExecutableDefinitions, + UniqueOperationNames, + LoneAnonymousOperation, + SingleFieldSubscriptions, + KnownTypeNames, + FragmentsOnCompositeTypes, + VariablesAreInputTypes, + ScalarLeafs, + FieldsOnCorrectType, + UniqueFragmentNames, + KnownFragmentNames, + NoUnusedFragments, + PossibleFragmentSpreads, + NoFragmentCycles, + UniqueVariableNames, + NoUndefinedVariables, + NoUnusedVariables, + KnownDirectives, + UniqueDirectivesPerLocation, + KnownArgumentNames, + UniqueArgumentNames, + ValuesOfCorrectType, + ProvidedRequiredArguments, + VariablesInAllowedPosition, + OverlappingFieldsCanBeMerged, + UniqueInputFieldNames, +]; + +import { LoneSchemaDefinition } from './rules/LoneSchemaDefinition'; +import { KnownArgumentNamesOnDirectives } from './rules/KnownArgumentNames'; +import { ProvidedRequiredArgumentsOnDirectives } from './rules/ProvidedRequiredArguments'; + +// @internal +export const specifiedSDLRules: $ReadOnlyArray = [ + LoneSchemaDefinition, + KnownDirectives, + UniqueDirectivesPerLocation, + KnownArgumentNamesOnDirectives, + UniqueArgumentNames, + UniqueInputFieldNames, + ProvidedRequiredArgumentsOnDirectives, +]; diff --git a/node_modules/graphql/validation/specifiedRules.mjs b/node_modules/graphql/validation/specifiedRules.mjs new file mode 100644 index 00000000..97f0bb87 --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.mjs @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +// Spec Section: "Executable Definitions" +import { ExecutableDefinitions } from './rules/ExecutableDefinitions'; // Spec Section: "Operation Name Uniqueness" + +import { UniqueOperationNames } from './rules/UniqueOperationNames'; // Spec Section: "Lone Anonymous Operation" + +import { LoneAnonymousOperation } from './rules/LoneAnonymousOperation'; // Spec Section: "Subscriptions with Single Root Field" + +import { SingleFieldSubscriptions } from './rules/SingleFieldSubscriptions'; // Spec Section: "Fragment Spread Type Existence" + +import { KnownTypeNames } from './rules/KnownTypeNames'; // Spec Section: "Fragments on Composite Types" + +import { FragmentsOnCompositeTypes } from './rules/FragmentsOnCompositeTypes'; // Spec Section: "Variables are Input Types" + +import { VariablesAreInputTypes } from './rules/VariablesAreInputTypes'; // Spec Section: "Leaf Field Selections" + +import { ScalarLeafs } from './rules/ScalarLeafs'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +import { FieldsOnCorrectType } from './rules/FieldsOnCorrectType'; // Spec Section: "Fragment Name Uniqueness" + +import { UniqueFragmentNames } from './rules/UniqueFragmentNames'; // Spec Section: "Fragment spread target defined" + +import { KnownFragmentNames } from './rules/KnownFragmentNames'; // Spec Section: "Fragments must be used" + +import { NoUnusedFragments } from './rules/NoUnusedFragments'; // Spec Section: "Fragment spread is possible" + +import { PossibleFragmentSpreads } from './rules/PossibleFragmentSpreads'; // Spec Section: "Fragments must not form cycles" + +import { NoFragmentCycles } from './rules/NoFragmentCycles'; // Spec Section: "Variable Uniqueness" + +import { UniqueVariableNames } from './rules/UniqueVariableNames'; // Spec Section: "All Variable Used Defined" + +import { NoUndefinedVariables } from './rules/NoUndefinedVariables'; // Spec Section: "All Variables Used" + +import { NoUnusedVariables } from './rules/NoUnusedVariables'; // Spec Section: "Directives Are Defined" + +import { KnownDirectives } from './rules/KnownDirectives'; // Spec Section: "Directives Are Unique Per Location" + +import { UniqueDirectivesPerLocation } from './rules/UniqueDirectivesPerLocation'; // Spec Section: "Argument Names" + +import { KnownArgumentNames } from './rules/KnownArgumentNames'; // Spec Section: "Argument Uniqueness" + +import { UniqueArgumentNames } from './rules/UniqueArgumentNames'; // Spec Section: "Value Type Correctness" + +import { ValuesOfCorrectType } from './rules/ValuesOfCorrectType'; // Spec Section: "Argument Optionality" + +import { ProvidedRequiredArguments } from './rules/ProvidedRequiredArguments'; // Spec Section: "All Variable Usages Are Allowed" + +import { VariablesInAllowedPosition } from './rules/VariablesInAllowedPosition'; // Spec Section: "Field Selection Merging" + +import { OverlappingFieldsCanBeMerged } from './rules/OverlappingFieldsCanBeMerged'; // Spec Section: "Input Object Field Uniqueness" + +import { UniqueInputFieldNames } from './rules/UniqueInputFieldNames'; +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + +export var specifiedRules = [ExecutableDefinitions, UniqueOperationNames, LoneAnonymousOperation, SingleFieldSubscriptions, KnownTypeNames, FragmentsOnCompositeTypes, VariablesAreInputTypes, ScalarLeafs, FieldsOnCorrectType, UniqueFragmentNames, KnownFragmentNames, NoUnusedFragments, PossibleFragmentSpreads, NoFragmentCycles, UniqueVariableNames, NoUndefinedVariables, NoUnusedVariables, KnownDirectives, UniqueDirectivesPerLocation, KnownArgumentNames, UniqueArgumentNames, ValuesOfCorrectType, ProvidedRequiredArguments, VariablesInAllowedPosition, OverlappingFieldsCanBeMerged, UniqueInputFieldNames]; +import { LoneSchemaDefinition } from './rules/LoneSchemaDefinition'; +import { KnownArgumentNamesOnDirectives } from './rules/KnownArgumentNames'; +import { ProvidedRequiredArgumentsOnDirectives } from './rules/ProvidedRequiredArguments'; // @internal + +export var specifiedSDLRules = [LoneSchemaDefinition, KnownDirectives, UniqueDirectivesPerLocation, KnownArgumentNamesOnDirectives, UniqueArgumentNames, UniqueInputFieldNames, ProvidedRequiredArgumentsOnDirectives]; \ No newline at end of file diff --git a/node_modules/graphql/validation/validate.js b/node_modules/graphql/validation/validate.js new file mode 100644 index 00000000..f9a4ab51 --- /dev/null +++ b/node_modules/graphql/validation/validate.js @@ -0,0 +1,110 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.validate = validate; +exports.validateSDL = validateSDL; +exports.assertValidSDL = assertValidSDL; +exports.assertValidSDLExtension = assertValidSDLExtension; + +var _invariant = _interopRequireDefault(require("../jsutils/invariant")); + +var _visitor = require("../language/visitor"); + +var _validate = require("../type/validate"); + +var _TypeInfo = require("../utilities/TypeInfo"); + +var _specifiedRules = require("./specifiedRules"); + +var _ValidationContext = require("./ValidationContext"); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +function validate(schema, documentAST) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedRules; + var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new _TypeInfo.TypeInfo(schema); + !documentAST ? (0, _invariant.default)(0, 'Must provide document') : void 0; // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + var context = new _ValidationContext.ValidationContext(schema, documentAST, typeInfo); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + var visitor = (0, _visitor.visitInParallel)(rules.map(function (rule) { + return rule(context); + })); // Visit the whole document with each instance of all provided rules. + + (0, _visitor.visit)(documentAST, (0, _visitor.visitWithTypeInfo)(typeInfo, visitor)); + return context.getErrors(); +} // @internal + + +function validateSDL(documentAST, schemaToExtend) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _specifiedRules.specifiedSDLRules; + var context = new _ValidationContext.SDLValidationContext(documentAST, schemaToExtend); + var visitors = rules.map(function (rule) { + return rule(context); + }); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return context.getErrors(); +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + +function assertValidSDL(documentAST) { + var errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + + +function assertValidSDLExtension(documentAST, schema) { + var errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} \ No newline at end of file diff --git a/node_modules/graphql/validation/validate.js.flow b/node_modules/graphql/validation/validate.js.flow new file mode 100644 index 00000000..9fe1b2ad --- /dev/null +++ b/node_modules/graphql/validation/validate.js.flow @@ -0,0 +1,95 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict + */ + +import invariant from '../jsutils/invariant'; +import type { GraphQLError } from '../error'; +import { visit, visitInParallel, visitWithTypeInfo } from '../language/visitor'; +import type { DocumentNode } from '../language/ast'; +import type { GraphQLSchema } from '../type/schema'; +import { assertValidSchema } from '../type/validate'; +import { TypeInfo } from '../utilities/TypeInfo'; +import { specifiedRules, specifiedSDLRules } from './specifiedRules'; +import type { SDLValidationRule, ValidationRule } from './ValidationContext'; +import { SDLValidationContext, ValidationContext } from './ValidationContext'; + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ +export function validate( + schema: GraphQLSchema, + documentAST: DocumentNode, + rules?: $ReadOnlyArray = specifiedRules, + typeInfo?: TypeInfo = new TypeInfo(schema), +): $ReadOnlyArray { + invariant(documentAST, 'Must provide document'); + // If the schema used for validation is invalid, throw an error. + assertValidSchema(schema); + + const context = new ValidationContext(schema, documentAST, typeInfo); + // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + const visitor = visitInParallel(rules.map(rule => rule(context))); + // Visit the whole document with each instance of all provided rules. + visit(documentAST, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} + +// @internal +export function validateSDL( + documentAST: DocumentNode, + schemaToExtend?: ?GraphQLSchema, + rules?: $ReadOnlyArray = specifiedSDLRules, +): $ReadOnlyArray { + const context = new SDLValidationContext(documentAST, schemaToExtend); + const visitors = rules.map(rule => rule(context)); + visit(documentAST, visitInParallel(visitors)); + return context.getErrors(); +} + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDL(documentAST: DocumentNode): void { + const errors = validateSDL(documentAST); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} + +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export function assertValidSDLExtension( + documentAST: DocumentNode, + schema: GraphQLSchema, +): void { + const errors = validateSDL(documentAST, schema); + if (errors.length !== 0) { + throw new Error(errors.map(error => error.message).join('\n\n')); + } +} diff --git a/node_modules/graphql/validation/validate.mjs b/node_modules/graphql/validation/validate.mjs new file mode 100644 index 00000000..41707878 --- /dev/null +++ b/node_modules/graphql/validation/validate.mjs @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * strict + */ +import invariant from '../jsutils/invariant'; +import { visit, visitInParallel, visitWithTypeInfo } from '../language/visitor'; +import { assertValidSchema } from '../type/validate'; +import { TypeInfo } from '../utilities/TypeInfo'; +import { specifiedRules, specifiedSDLRules } from './specifiedRules'; +import { SDLValidationContext, ValidationContext } from './ValidationContext'; +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rules is a function which returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + */ + +export function validate(schema, documentAST) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedRules; + var typeInfo = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new TypeInfo(schema); + !documentAST ? invariant(0, 'Must provide document') : void 0; // If the schema used for validation is invalid, throw an error. + + assertValidSchema(schema); + var context = new ValidationContext(schema, documentAST, typeInfo); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + var visitor = visitInParallel(rules.map(function (rule) { + return rule(context); + })); // Visit the whole document with each instance of all provided rules. + + visit(documentAST, visitWithTypeInfo(typeInfo, visitor)); + return context.getErrors(); +} // @internal + +export function validateSDL(documentAST, schemaToExtend) { + var rules = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specifiedSDLRules; + var context = new SDLValidationContext(documentAST, schemaToExtend); + var visitors = rules.map(function (rule) { + return rule(context); + }); + visit(documentAST, visitInParallel(visitors)); + return context.getErrors(); +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDL(documentAST) { + var errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDLExtension(documentAST, schema) { + var errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map(function (error) { + return error.message; + }).join('\n\n')); + } +} \ No newline at end of file diff --git a/node_modules/http-errors/HISTORY.md b/node_modules/http-errors/HISTORY.md new file mode 100644 index 00000000..cba86e2d --- /dev/null +++ b/node_modules/http-errors/HISTORY.md @@ -0,0 +1,132 @@ +2018-03-29 / 1.6.3 +================== + + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: setprototypeof@1.1.0 + * deps: statuses@'>= 1.3.1 < 2' + +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/node_modules/http-errors/LICENSE b/node_modules/http-errors/LICENSE new file mode 100644 index 00000000..82af4df5 --- /dev/null +++ b/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.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/http-errors/README.md b/node_modules/http-errors/README.md new file mode 100644 index 00000000..79663d82 --- /dev/null +++ b/node_modules/http-errors/README.md @@ -0,0 +1,135 @@ +# http-errors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +All errors inherit from JavaScript `Error` and the exported `createError.HttpError`. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + + + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + + + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |UnorderedCollection | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/node_modules/http-errors/index.js b/node_modules/http-errors/index.js new file mode 100644 index 00000000..9509303e --- /dev/null +++ b/node_modules/http-errors/index.js @@ -0,0 +1,260 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue + } + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') + } + break + case 'object': + props = arg + break + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) + + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} + +/** + * Convert a string of words to a JavaScript identifier. + * @private + */ + +function toIdentifier (str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} diff --git a/node_modules/http-errors/package.json b/node_modules/http-errors/package.json new file mode 100644 index 00000000..d24201f7 --- /dev/null +++ b/node_modules/http-errors/package.json @@ -0,0 +1,95 @@ +{ + "_args": [ + [ + "http-errors@1.6.3", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "http-errors@1.6.3", + "_id": "http-errors@1.6.3", + "_inBundle": false, + "_integrity": "sha1-i1VoC7S+KDoLW/TqLjhYC+HZMg0=", + "_location": "/http-errors", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "http-errors@1.6.3", + "name": "http-errors", + "escapedName": "http-errors", + "rawSpec": "1.6.3", + "saveSpec": null, + "fetchSpec": "1.6.3" + }, + "_requiredBy": [ + "/body-parser", + "/express-graphql", + "/send" + ], + "_resolved": "http://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", + "_spec": "1.6.3", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.3", + "setprototypeof": "1.1.0", + "statuses": ">= 1.4.0 < 2" + }, + "description": "Create HTTP error objects", + "devDependencies": { + "eslint": "4.18.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.9.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "homepage": "https://github.com/jshttp/http-errors#readme", + "keywords": [ + "http", + "error" + ], + "license": "MIT", + "name": "http-errors", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "version": "1.6.3" +} diff --git a/node_modules/iconv-lite/.npmignore b/node_modules/iconv-lite/.npmignore new file mode 100644 index 00000000..5cd2673c --- /dev/null +++ b/node_modules/iconv-lite/.npmignore @@ -0,0 +1,6 @@ +*~ +*sublime-* +generation +test +wiki +coverage diff --git a/node_modules/iconv-lite/.travis.yml b/node_modules/iconv-lite/.travis.yml new file mode 100644 index 00000000..3eab7fdb --- /dev/null +++ b/node_modules/iconv-lite/.travis.yml @@ -0,0 +1,23 @@ + sudo: false + language: node_js + node_js: + - "0.10" + - "0.11" + - "0.12" + - "iojs" + - "4" + - "6" + - "8" + - "node" + + + env: + - CXX=g++-4.8 + addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - gcc-4.8 + - g++-4.8 + diff --git a/node_modules/iconv-lite/Changelog.md b/node_modules/iconv-lite/Changelog.md new file mode 100644 index 00000000..64aae34b --- /dev/null +++ b/node_modules/iconv-lite/Changelog.md @@ -0,0 +1,134 @@ + +# 0.4.19 / 2017-09-09 + + * Fixed iso8859-1 codec regression in handling untranslatable characters (#162, caused by #147) + * Re-generated windows1255 codec, because it was updated in iconv project + * Fixed grammar in error message when iconv-lite is loaded with encoding other than utf8 + + +# 0.4.18 / 2017-06-13 + + * Fixed CESU-8 regression in Node v8. + + +# 0.4.17 / 2017-04-22 + + * Updated typescript definition file to support Angular 2 AoT mode (#153 by @larssn) + + +# 0.4.16 / 2017-04-22 + + * Added support for React Native (#150) + * Changed iso8859-1 encoding to usine internal 'binary' encoding, as it's the same thing (#147 by @mscdex) + * Fixed typo in Readme (#138 by @jiangzhuo) + * Fixed build for Node v6.10+ by making correct version comparison + * Added a warning if iconv-lite is loaded not as utf-8 (see #142) + + +# 0.4.15 / 2016-11-21 + + * Fixed typescript type definition (#137) + + +# 0.4.14 / 2016-11-20 + + * Preparation for v1.0 + * Added Node v6 and latest Node versions to Travis CI test rig + * Deprecated Node v0.8 support + * Typescript typings (@larssn) + * Fix encoding of Euro character in GB 18030 (inspired by @lygstate) + * Add ms prefix to dbcs windows encodings (@rokoroku) + + +# 0.4.13 / 2015-10-01 + + * Fix silly mistake in deprecation notice. + + +# 0.4.12 / 2015-09-26 + + * Node v4 support: + * Added CESU-8 decoding (#106) + * Added deprecation notice for `extendNodeEncodings` + * Added Travis tests for Node v4 and io.js latest (#105 by @Mithgol) + + +# 0.4.11 / 2015-07-03 + + * Added CESU-8 encoding. + + +# 0.4.10 / 2015-05-26 + + * Changed UTF-16 endianness heuristic to take into account any ASCII chars, not + just spaces. This should minimize the importance of "default" endianness. + + +# 0.4.9 / 2015-05-24 + + * Streamlined BOM handling: strip BOM by default, add BOM when encoding if + addBOM: true. Added docs to Readme. + * UTF16 now uses UTF16-LE by default. + * Fixed minor issue with big5 encoding. + * Added io.js testing on Travis; updated node-iconv version to test against. + Now we just skip testing SBCS encodings that node-iconv doesn't support. + * (internal refactoring) Updated codec interface to use classes. + * Use strict mode in all files. + + +# 0.4.8 / 2015-04-14 + + * added alias UNICODE-1-1-UTF-7 for UTF-7 encoding (#94) + + +# 0.4.7 / 2015-02-05 + + * stop official support of Node.js v0.8. Should still work, but no guarantees. + reason: Packages needed for testing are hard to get on Travis CI. + * work in environment where Object.prototype is monkey patched with enumerable + props (#89). + + +# 0.4.6 / 2015-01-12 + + * fix rare aliases of single-byte encodings (thanks @mscdex) + * double the timeout for dbcs tests to make them less flaky on travis + + +# 0.4.5 / 2014-11-20 + + * fix windows-31j and x-sjis encoding support (@nleush) + * minor fix: undefined variable reference when internal error happens + + +# 0.4.4 / 2014-07-16 + + * added encodings UTF-7 (RFC2152) and UTF-7-IMAP (RFC3501 Section 5.1.3) + * fixed streaming base64 encoding + + +# 0.4.3 / 2014-06-14 + + * added encodings UTF-16BE and UTF-16 with BOM + + +# 0.4.2 / 2014-06-12 + + * don't throw exception if `extendNodeEncodings()` is called more than once + + +# 0.4.1 / 2014-06-11 + + * codepage 808 added + + +# 0.4.0 / 2014-06-10 + + * code is rewritten from scratch + * all widespread encodings are supported + * streaming interface added + * browserify compatibility added + * (optional) extend core primitive encodings to make usage even simpler + * moved from vows to mocha as the testing framework + + diff --git a/node_modules/iconv-lite/LICENSE b/node_modules/iconv-lite/LICENSE new file mode 100644 index 00000000..d518d837 --- /dev/null +++ b/node_modules/iconv-lite/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011 Alexander Shtuchkin + +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/iconv-lite/README.md b/node_modules/iconv-lite/README.md new file mode 100644 index 00000000..767daede --- /dev/null +++ b/node_modules/iconv-lite/README.md @@ -0,0 +1,160 @@ +## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite) + + * Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io). + * Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser), + [Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others. + * Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv) (see below for performance comparison). + * Intuitive encode/decode API + * Streaming support for Node v0.10+ + * [Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings. + * In-browser usage via [Browserify](https://github.com/substack/node-browserify) (~180k gzip compressed with Buffer shim included). + * Typescript [type definition file](https://github.com/ashtuchkin/iconv-lite/blob/master/lib/index.d.ts) included. + * React Native is supported (need to explicitly `npm install` two more modules: `buffer` and `stream`). + * License: MIT. + +[![NPM Stats](https://nodei.co/npm/iconv-lite.png?downloads=true&downloadRank=true)](https://npmjs.org/packages/iconv-lite/) + +## Usage +### Basic API +```javascript +var iconv = require('iconv-lite'); + +// Convert from an encoded buffer to js string. +str = iconv.decode(new Buffer([0x68, 0x65, 0x6c, 0x6c, 0x6f]), 'win1251'); + +// Convert from js string to an encoded buffer. +buf = iconv.encode("Sample input string", 'win1251'); + +// Check if encoding is supported +iconv.encodingExists("us-ascii") +``` + +### Streaming API (Node v0.10+) +```javascript + +// Decode stream (from binary stream to js strings) +http.createServer(function(req, res) { + var converterStream = iconv.decodeStream('win1251'); + req.pipe(converterStream); + + converterStream.on('data', function(str) { + console.log(str); // Do something with decoded strings, chunk-by-chunk. + }); +}); + +// Convert encoding streaming example +fs.createReadStream('file-in-win1251.txt') + .pipe(iconv.decodeStream('win1251')) + .pipe(iconv.encodeStream('ucs2')) + .pipe(fs.createWriteStream('file-in-ucs2.txt')); + +// Sugar: all encode/decode streams have .collect(cb) method to accumulate data. +http.createServer(function(req, res) { + req.pipe(iconv.decodeStream('win1251')).collect(function(err, body) { + assert(typeof body == 'string'); + console.log(body); // full request body string + }); +}); +``` + +### [Deprecated] Extend Node.js own encodings +> NOTE: This doesn't work on latest Node versions. See [details](https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility). + +```javascript +// After this call all Node basic primitives will understand iconv-lite encodings. +iconv.extendNodeEncodings(); + +// Examples: +buf = new Buffer(str, 'win1251'); +buf.write(str, 'gbk'); +str = buf.toString('latin1'); +assert(Buffer.isEncoding('iso-8859-15')); +Buffer.byteLength(str, 'us-ascii'); + +http.createServer(function(req, res) { + req.setEncoding('big5'); + req.collect(function(err, body) { + console.log(body); + }); +}); + +fs.createReadStream("file.txt", "shift_jis"); + +// External modules are also supported (if they use Node primitives, which they probably do). +request = require('request'); +request({ + url: "http://github.com/", + encoding: "cp932" +}); + +// To remove extensions +iconv.undoExtendNodeEncodings(); +``` + +## Supported encodings + + * All node.js native encodings: utf8, ucs2 / utf16-le, ascii, binary, base64, hex. + * Additional unicode encodings: utf16, utf16-be, utf-7, utf-7-imap. + * All widespread singlebyte encodings: Windows 125x family, ISO-8859 family, + IBM/DOS codepages, Macintosh family, KOI8 family, all others supported by iconv library. + Aliases like 'latin1', 'us-ascii' also supported. + * All widespread multibyte encodings: CP932, CP936, CP949, CP950, GB2312, GBK, GB18030, Big5, Shift_JIS, EUC-JP. + +See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings). + +Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors! + +Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors! + + +## Encoding/decoding speed + +Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0). +Note: your results may vary, so please always check on your hardware. + + operation iconv@2.1.4 iconv-lite@0.4.7 + ---------------------------------------------------------- + encode('win1251') ~96 Mb/s ~320 Mb/s + decode('win1251') ~95 Mb/s ~246 Mb/s + +## BOM handling + + * Decoding: BOM is stripped by default, unless overridden by passing `stripBOM: false` in options + (f.ex. `iconv.decode(buf, enc, {stripBOM: false})`). + A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found. + * If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module. + * Encoding: No BOM added, unless overridden by `addBOM: true` option. + +## UTF-16 Encodings + +This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be +smart about endianness in the following ways: + * Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be + overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`. + * Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override. + +## Other notes + +When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding). +Untranslatable characters are set to � or ?. No transliteration is currently supported. +Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77). + +## Testing + +```bash +$ git clone git@github.com:ashtuchkin/iconv-lite.git +$ cd iconv-lite +$ npm install +$ npm test + +$ # To view performance: +$ node test/performance.js + +$ # To view test coverage: +$ npm run coverage +$ open coverage/lcov-report/index.html +``` + +## Adoption +[![NPM](https://nodei.co/npm-dl/iconv-lite.png)](https://nodei.co/npm/iconv-lite/) +[![Codeship Status for ashtuchkin/iconv-lite](https://www.codeship.com/projects/81670840-fa72-0131-4520-4a01a6c01acc/status)](https://www.codeship.com/projects/29053) diff --git a/node_modules/iconv-lite/encodings/dbcs-codec.js b/node_modules/iconv-lite/encodings/dbcs-codec.js new file mode 100644 index 00000000..7b3c980b --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-codec.js @@ -0,0 +1,555 @@ +"use strict"; +var Buffer = require("buffer").Buffer; + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; + } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + } + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; + } + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + } + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); + } + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); + } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char + } + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); + } + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; + } + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal + } + } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; +} + +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; + + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} + + + +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; +} + +DBCSEncoder.prototype.write = function(str) { + var newBuf = new Buffer(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); + } + else { + var uCode = nextChar; + nextChar = -1; + } + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } + } + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; + } + + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; + + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; + + } else if (resCode == undefined) { // Current character is not part of the sequence. + + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. + + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. + } + } + seqObj = undefined; + } + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; + } + } + } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + else { + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; + } + } + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = new Buffer(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; + } + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte + } + } else { + // See todo above. + } + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; + } + + return newBuf.slice(0, j); +} + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = new Buffer(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = new Buffer(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. + } + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); + } + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; + } + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; + } + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; + } + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; + } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; + } + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = new Buffer(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); + } + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; + } + return l; +} + diff --git a/node_modules/iconv-lite/encodings/dbcs-data.js b/node_modules/iconv-lite/encodings/dbcs-data.js new file mode 100644 index 00000000..4b619143 --- /dev/null +++ b/node_modules/iconv-lite/encodings/dbcs-data.js @@ -0,0 +1,176 @@ +"use strict"; + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + 'shiftjis': { + type: '_dbcs', + table: function() { return require('./tables/shiftjis.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return require('./tables/eucjp.json') }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json') }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) }, + gb18030: function() { return require('./tables/gb18030-ranges.json') }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, + + 'chinese': 'gb18030', + + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return require('./tables/cp949.json') }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json') }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', +}; diff --git a/node_modules/iconv-lite/encodings/index.js b/node_modules/iconv-lite/encodings/index.js new file mode 100644 index 00000000..e3040031 --- /dev/null +++ b/node_modules/iconv-lite/encodings/index.js @@ -0,0 +1,22 @@ +"use strict"; + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + require("./internal"), + require("./utf16"), + require("./utf7"), + require("./sbcs-codec"), + require("./sbcs-data"), + require("./sbcs-data-generated"), + require("./dbcs-codec"), + require("./dbcs-data"), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; +} diff --git a/node_modules/iconv-lite/encodings/internal.js b/node_modules/iconv-lite/encodings/internal.js new file mode 100644 index 00000000..b0adf6a9 --- /dev/null +++ b/node_modules/iconv-lite/encodings/internal.js @@ -0,0 +1,188 @@ +"use strict"; +var Buffer = require("buffer").Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, + + // Codec. + _internal: InternalCodec, +}; + +//------------------------------------------------------------------------------ + +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (new Buffer('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; + } + } +} + +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; + +//------------------------------------------------------------------------------ + +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = require('string_decoder').StringDecoder; + +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; + + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); +} + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; +} + +InternalEncoder.prototype.write = function(str) { + return new Buffer(str, this.enc); +} + +InternalEncoder.prototype.end = function() { +} + + +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. + +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return new Buffer(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return new Buffer(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = new Buffer(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); + } + } + return buf.slice(0, bufIdx); +} + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; + } + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; + } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); + } + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; + } + } + } + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; +} + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; +} diff --git a/node_modules/iconv-lite/encodings/sbcs-codec.js b/node_modules/iconv-lite/encodings/sbcs-codec.js new file mode 100644 index 00000000..7789e00e --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-codec.js @@ -0,0 +1,73 @@ +"use strict"; +var Buffer = require("buffer").Buffer; + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; + } + + this.decodeBuf = new Buffer(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = new Buffer(65536); + encodeBuf.fill(iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = new Buffer(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = new Buffer(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; + } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { +} diff --git a/node_modules/iconv-lite/encodings/sbcs-data-generated.js b/node_modules/iconv-lite/encodings/sbcs-data-generated.js new file mode 100644 index 00000000..9b482360 --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data-generated.js @@ -0,0 +1,451 @@ +"use strict"; + +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�ݰħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤Ĩϧ¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩšēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖרŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖרÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨͧĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Чš©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£Ø×¤ĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/sbcs-data.js b/node_modules/iconv-lite/encodings/sbcs-data.js new file mode 100644 index 00000000..2d6f846a --- /dev/null +++ b/node_modules/iconv-lite/encodings/sbcs-data.js @@ -0,0 +1,169 @@ +"use strict"; + +// Manually added data to be used by sbcs codec in addition to generated one. + +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, + + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", + + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", + + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", + + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", + + "cp819": "iso88591", + "ibm819": "iso88591", + + "cyrillic": "iso88595", + + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", + + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", + + "hebrew": "iso88598", + "hebrew8": "iso88598", + + "turkish": "iso88599", + "turkish8": "iso88599", + + "thai": "iso885911", + "thai8": "iso885911", + + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", + + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", + + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", + + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", + + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", +}; + diff --git a/node_modules/iconv-lite/encodings/tables/big5-added.json b/node_modules/iconv-lite/encodings/tables/big5-added.json new file mode 100644 index 00000000..3c3d3c2f --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/big5-added.json @@ -0,0 +1,122 @@ +[ +["8740","䏰䰲䘃䖦䕸𧉧䵷䖳𧲱䳢𧳅㮕䜶䝄䱇䱀𤊿𣘗𧍒𦺋𧃒䱗𪍑䝏䗚䲅𧱬䴇䪤䚡𦬣爥𥩔𡩣𣸆𣽡晍囻"], +["8767","綕夝𨮹㷴霴𧯯寛𡵞媤㘥𩺰嫑宷峼杮薓𩥅瑡璝㡵𡵓𣚞𦀡㻬"], +["87a1","𥣞㫵竼龗𤅡𨤍𣇪𠪊𣉞䌊蒄龖鐯䤰蘓墖靊鈘秐稲晠権袝瑌篅枂稬剏遆㓦珄𥶹瓆鿇垳䤯呌䄱𣚎堘穲𧭥讏䚮𦺈䆁𥶙箮𢒼鿈𢓁𢓉𢓌鿉蔄𣖻䂴鿊䓡𪷿拁灮鿋"], +["8840","㇀",4,"𠄌㇅𠃑𠃍㇆㇇𠃋𡿨㇈𠃊㇉㇊㇋㇌𠄎㇍㇎ĀÁǍÀĒÉĚÈŌÓǑÒ࿿Ê̄Ế࿿Ê̌ỀÊāáǎàɑēéěèīíǐìōóǒòūúǔùǖǘǚ"], +["88a1","ǜü࿿ê̄ế࿿ê̌ềêɡ⏚⏛"], +["8940","𪎩𡅅"], +["8943","攊"], +["8946","丽滝鵎釟"], +["894c","𧜵撑会伨侨兖兴农凤务动医华发变团声处备夲头学实実岚庆总斉柾栄桥济炼电纤纬纺织经统缆缷艺苏药视设询车轧轮"], +["89a1","琑糼緍楆竉刧"], +["89ab","醌碸酞肼"], +["89b0","贋胶𠧧"], +["89b5","肟黇䳍鷉鸌䰾𩷶𧀎鸊𪄳㗁"], +["89c1","溚舾甙"], +["89c5","䤑马骏龙禇𨑬𡷊𠗐𢫦两亁亀亇亿仫伷㑌侽㹈倃傈㑽㒓㒥円夅凛凼刅争剹劐匧㗇厩㕑厰㕓参吣㕭㕲㚁咓咣咴咹哐哯唘唣唨㖘唿㖥㖿嗗㗅"], +["8a40","𧶄唥"], +["8a43","𠱂𠴕𥄫喐𢳆㧬𠍁蹆𤶸𩓥䁓𨂾睺𢰸㨴䟕𨅝𦧲𤷪擝𠵼𠾴𠳕𡃴撍蹾𠺖𠰋𠽤𢲩𨉖𤓓"], +["8a64","𠵆𩩍𨃩䟴𤺧𢳂骲㩧𩗴㿭㔆𥋇𩟔𧣈𢵄鵮頕"], +["8a76","䏙𦂥撴哣𢵌𢯊𡁷㧻𡁯"], +["8aa1","𦛚𦜖𧦠擪𥁒𠱃蹨𢆡𨭌𠜱"], +["8aac","䠋𠆩㿺塳𢶍"], +["8ab2","𤗈𠓼𦂗𠽌𠶖啹䂻䎺"], +["8abb","䪴𢩦𡂝膪飵𠶜捹㧾𢝵跀嚡摼㹃"], +["8ac9","𪘁𠸉𢫏𢳉"], +["8ace","𡃈𣧂㦒㨆𨊛㕸𥹉𢃇噒𠼱𢲲𩜠㒼氽𤸻"], +["8adf","𧕴𢺋𢈈𪙛𨳍𠹺𠰴𦠜羓𡃏𢠃𢤹㗻𥇣𠺌𠾍𠺪㾓𠼰𠵇𡅏𠹌"], +["8af6","𠺫𠮩𠵈𡃀𡄽㿹𢚖搲𠾭"], +["8b40","𣏴𧘹𢯎𠵾𠵿𢱑𢱕㨘𠺘𡃇𠼮𪘲𦭐𨳒𨶙𨳊閪哌苄喹"], +["8b55","𩻃鰦骶𧝞𢷮煀腭胬尜𦕲脴㞗卟𨂽醶𠻺𠸏𠹷𠻻㗝𤷫㘉𠳖嚯𢞵𡃉𠸐𠹸𡁸𡅈𨈇𡑕𠹹𤹐𢶤婔𡀝𡀞𡃵𡃶垜𠸑"], +["8ba1","𧚔𨋍𠾵𠹻𥅾㜃𠾶𡆀𥋘𪊽𤧚𡠺𤅷𨉼墙剨㘚𥜽箲孨䠀䬬鼧䧧鰟鮍𥭴𣄽嗻㗲嚉丨夂𡯁屮靑𠂆乛亻㔾尣彑忄㣺扌攵歺氵氺灬爫丬犭𤣩罒礻糹罓𦉪㓁"], +["8bde","𦍋耂肀𦘒𦥑卝衤见𧢲讠贝钅镸长门𨸏韦页风飞饣𩠐鱼鸟黄歯龜丷𠂇阝户钢"], +["8c40","倻淾𩱳龦㷉袏𤅎灷峵䬠𥇍㕙𥴰愢𨨲辧釶熑朙玺𣊁𪄇㲋𡦀䬐磤琂冮𨜏䀉橣𪊺䈣蘏𠩯稪𩥇𨫪靕灍匤𢁾鏴盙𨧣龧矝亣俰傼丯众龨吴綋墒壐𡶶庒庙忂𢜒斋"], +["8ca1","𣏹椙橃𣱣泿"], +["8ca7","爀𤔅玌㻛𤨓嬕璹讃𥲤𥚕窓篬糃繬苸薗龩袐龪躹龫迏蕟駠鈡龬𨶹𡐿䁱䊢娚"], +["8cc9","顨杫䉶圽"], +["8cce","藖𤥻芿𧄍䲁𦵴嵻𦬕𦾾龭龮宖龯曧繛湗秊㶈䓃𣉖𢞖䎚䔶"], +["8ce6","峕𣬚諹屸㴒𣕑嵸龲煗䕘𤃬𡸣䱷㥸㑊𠆤𦱁諌侴𠈹妿腬顖𩣺弻"], +["8d40","𠮟"], +["8d42","𢇁𨥭䄂䚻𩁹㼇龳𪆵䃸㟖䛷𦱆䅼𨚲𧏿䕭㣔𥒚䕡䔛䶉䱻䵶䗪㿈𤬏㙡䓞䒽䇭崾嵈嵖㷼㠏嶤嶹㠠㠸幂庽弥徃㤈㤔㤿㥍惗愽峥㦉憷憹懏㦸戬抐拥挘㧸嚱"], +["8da1","㨃揢揻搇摚㩋擀崕嘡龟㪗斆㪽旿晓㫲暒㬢朖㭂枤栀㭘桊梄㭲㭱㭻椉楃牜楤榟榅㮼槖㯝橥橴橱檂㯬檙㯲檫檵櫔櫶殁毁毪汵沪㳋洂洆洦涁㳯涤涱渕渘温溆𨧀溻滢滚齿滨滩漤漴㵆𣽁澁澾㵪㵵熷岙㶊瀬㶑灐灔灯灿炉𠌥䏁㗱𠻘"], +["8e40","𣻗垾𦻓焾𥟠㙎榢𨯩孴穉𥣡𩓙穥穽𥦬窻窰竂竃燑𦒍䇊竚竝竪䇯咲𥰁笋筕笩𥌎𥳾箢筯莜𥮴𦱿篐萡箒箸𥴠㶭𥱥蒒篺簆簵𥳁籄粃𤢂粦晽𤕸糉糇糦籴糳糵糎"], +["8ea1","繧䔝𦹄絝𦻖璍綉綫焵綳緒𤁗𦀩緤㴓緵𡟹緥𨍭縝𦄡𦅚繮纒䌫鑬縧罀罁罇礶𦋐駡羗𦍑羣𡙡𠁨䕜𣝦䔃𨌺翺𦒉者耈耝耨耯𪂇𦳃耻耼聡𢜔䦉𦘦𣷣𦛨朥肧𨩈脇脚墰𢛶汿𦒘𤾸擧𡒊舘𡡞橓𤩥𤪕䑺舩𠬍𦩒𣵾俹𡓽蓢荢𦬊𤦧𣔰𡝳𣷸芪椛芳䇛"], +["8f40","蕋苐茚𠸖𡞴㛁𣅽𣕚艻苢茘𣺋𦶣𦬅𦮗𣗎㶿茝嗬莅䔋𦶥莬菁菓㑾𦻔橗蕚㒖𦹂𢻯葘𥯤葱㷓䓤檧葊𣲵祘蒨𦮖𦹷𦹃蓞萏莑䒠蒓蓤𥲑䉀𥳀䕃蔴嫲𦺙䔧蕳䔖枿蘖"], +["8fa1","𨘥𨘻藁𧂈蘂𡖂𧃍䕫䕪蘨㙈𡢢号𧎚虾蝱𪃸蟮𢰧螱蟚蠏噡虬桖䘏衅衆𧗠𣶹𧗤衞袜䙛袴袵揁装睷𧜏覇覊覦覩覧覼𨨥觧𧤤𧪽誜瞓釾誐𧩙竩𧬺𣾏䜓𧬸煼謌謟𥐰𥕥謿譌譍誩𤩺讐讛誯𡛟䘕衏貛𧵔𧶏貫㜥𧵓賖𧶘𧶽贒贃𡤐賛灜贑𤳉㻐起"], +["9040","趩𨀂𡀔𤦊㭼𨆼𧄌竧躭躶軃鋔輙輭𨍥𨐒辥錃𪊟𠩐辳䤪𨧞𨔽𣶻廸𣉢迹𪀔𨚼𨔁𢌥㦀𦻗逷𨔼𧪾遡𨕬𨘋邨𨜓郄𨛦邮都酧㫰醩釄粬𨤳𡺉鈎沟鉁鉢𥖹銹𨫆𣲛𨬌𥗛"], +["90a1","𠴱錬鍫𨫡𨯫炏嫃𨫢𨫥䥥鉄𨯬𨰹𨯿鍳鑛躼閅閦鐦閠濶䊹𢙺𨛘𡉼𣸮䧟氜陻隖䅬隣𦻕懚隶磵𨫠隽双䦡𦲸𠉴𦐐𩂯𩃥𤫑𡤕𣌊霱虂霶䨏䔽䖅𤫩灵孁霛靜𩇕靗孊𩇫靟鐥僐𣂷𣂼鞉鞟鞱鞾韀韒韠𥑬韮琜𩐳響韵𩐝𧥺䫑頴頳顋顦㬎𧅵㵑𠘰𤅜"], +["9140","𥜆飊颷飈飇䫿𦴧𡛓喰飡飦飬鍸餹𤨩䭲𩡗𩤅駵騌騻騐驘𥜥㛄𩂱𩯕髠髢𩬅髴䰎鬔鬭𨘀倴鬴𦦨㣃𣁽魐魀𩴾婅𡡣鮎𤉋鰂鯿鰌𩹨鷔𩾷𪆒𪆫𪃡𪄣𪇟鵾鶃𪄴鸎梈"], +["91a1","鷄𢅛𪆓𪈠𡤻𪈳鴹𪂹𪊴麐麕麞麢䴴麪麯𤍤黁㭠㧥㴝伲㞾𨰫鼂鼈䮖鐤𦶢鼗鼖鼹嚟嚊齅馸𩂋韲葿齢齩竜龎爖䮾𤥵𤦻煷𤧸𤍈𤩑玞𨯚𡣺禟𨥾𨸶鍩鏳𨩄鋬鎁鏋𨥬𤒹爗㻫睲穃烐𤑳𤏸煾𡟯炣𡢾𣖙㻇𡢅𥐯𡟸㜢𡛻𡠹㛡𡝴𡣑𥽋㜣𡛀坛𤨥𡏾𡊨"], +["9240","𡏆𡒶蔃𣚦蔃葕𤦔𧅥𣸱𥕜𣻻𧁒䓴𣛮𩦝𦼦柹㜳㰕㷧塬𡤢栐䁗𣜿𤃡𤂋𤄏𦰡哋嚞𦚱嚒𠿟𠮨𠸍鏆𨬓鎜仸儫㠙𤐶亼𠑥𠍿佋侊𥙑婨𠆫𠏋㦙𠌊𠐔㐵伩𠋀𨺳𠉵諚𠈌亘"], +["92a1","働儍侢伃𤨎𣺊佂倮偬傁俌俥偘僼兙兛兝兞湶𣖕𣸹𣺿浲𡢄𣺉冨凃𠗠䓝𠒣𠒒𠒑赺𨪜𠜎剙劤𠡳勡鍮䙺熌𤎌𠰠𤦬𡃤槑𠸝瑹㻞璙琔瑖玘䮎𤪼𤂍叐㖄爏𤃉喴𠍅响𠯆圝鉝雴鍦埝垍坿㘾壋媙𨩆𡛺𡝯𡜐娬妸銏婾嫏娒𥥆𡧳𡡡𤊕㛵洅瑃娡𥺃"], +["9340","媁𨯗𠐓鏠璌𡌃焅䥲鐈𨧻鎽㞠尞岞幞幈𡦖𡥼𣫮廍孏𡤃𡤄㜁𡢠㛝𡛾㛓脪𨩇𡶺𣑲𨦨弌弎𡤧𡞫婫𡜻孄蘔𧗽衠恾𢡠𢘫忛㺸𢖯𢖾𩂈𦽳懀𠀾𠁆𢘛憙憘恵𢲛𢴇𤛔𩅍"], +["93a1","摱𤙥𢭪㨩𢬢𣑐𩣪𢹸挷𪑛撶挱揑𤧣𢵧护𢲡搻敫楲㯴𣂎𣊭𤦉𣊫唍𣋠𡣙𩐿曎𣊉𣆳㫠䆐𥖄𨬢𥖏𡛼𥕛𥐥磮𣄃𡠪𣈴㑤𣈏𣆂𤋉暎𦴤晫䮓昰𧡰𡷫晣𣋒𣋡昞𥡲㣑𣠺𣞼㮙𣞢𣏾瓐㮖枏𤘪梶栞㯄檾㡣𣟕𤒇樳橒櫉欅𡤒攑梘橌㯗橺歗𣿀𣲚鎠鋲𨯪𨫋"], +["9440","銉𨀞𨧜鑧涥漋𤧬浧𣽿㶏渄𤀼娽渊塇洤硂焻𤌚𤉶烱牐犇犔𤞏𤜥兹𤪤𠗫瑺𣻸𣙟𤩊𤤗𥿡㼆㺱𤫟𨰣𣼵悧㻳瓌琼鎇琷䒟𦷪䕑疃㽣𤳙𤴆㽘畕癳𪗆㬙瑨𨫌𤦫𤦎㫻"], +["94a1","㷍𤩎㻿𤧅𤣳釺圲鍂𨫣𡡤僟𥈡𥇧睸𣈲眎眏睻𤚗𣞁㩞𤣰琸璛㺿𤪺𤫇䃈𤪖𦆮錇𥖁砞碍碈磒珐祙𧝁𥛣䄎禛蒖禥樭𣻺稺秴䅮𡛦䄲鈵秱𠵌𤦌𠊙𣶺𡝮㖗啫㕰㚪𠇔𠰍竢婙𢛵𥪯𥪜娍𠉛磰娪𥯆竾䇹籝籭䈑𥮳𥺼𥺦糍𤧹𡞰粎籼粮檲緜縇緓罎𦉡"], +["9540","𦅜𧭈綗𥺂䉪𦭵𠤖柖𠁎𣗏埄𦐒𦏸𤥢翝笧𠠬𥫩𥵃笌𥸎駦虅驣樜𣐿㧢𤧷𦖭騟𦖠蒀𧄧𦳑䓪脷䐂胆脉腂𦞴飃𦩂艢艥𦩑葓𦶧蘐𧈛媆䅿𡡀嬫𡢡嫤𡣘蚠蜨𣶏蠭𧐢娂"], +["95a1","衮佅袇袿裦襥襍𥚃襔𧞅𧞄𨯵𨯙𨮜𨧹㺭蒣䛵䛏㟲訽訜𩑈彍鈫𤊄旔焩烄𡡅鵭貟賩𧷜妚矃姰䍮㛔踪躧𤰉輰轊䋴汘澻𢌡䢛潹溋𡟚鯩㚵𤤯邻邗啱䤆醻鐄𨩋䁢𨫼鐧𨰝𨰻蓥訫閙閧閗閖𨴴瑅㻂𤣿𤩂𤏪㻧𣈥随𨻧𨹦𨹥㻌𤧭𤩸𣿮琒瑫㻼靁𩂰"], +["9640","桇䨝𩂓𥟟靝鍨𨦉𨰦𨬯𦎾銺嬑譩䤼珹𤈛鞛靱餸𠼦巁𨯅𤪲頟𩓚鋶𩗗釥䓀𨭐𤩧𨭤飜𨩅㼀鈪䤥萔餻饍𧬆㷽馛䭯馪驜𨭥𥣈檏騡嫾騯𩣱䮐𩥈馼䮽䮗鍽塲𡌂堢𤦸"], +["96a1","𡓨硄𢜟𣶸棅㵽鑘㤧慐𢞁𢥫愇鱏鱓鱻鰵鰐魿鯏𩸭鮟𪇵𪃾鴡䲮𤄄鸘䲰鴌𪆴𪃭𪃳𩤯鶥蒽𦸒𦿟𦮂藼䔳𦶤𦺄𦷰萠藮𦸀𣟗𦁤秢𣖜𣙀䤭𤧞㵢鏛銾鍈𠊿碹鉷鑍俤㑀遤𥕝砽硔碶硋𡝗𣇉𤥁㚚佲濚濙瀞瀞吔𤆵垻壳垊鴖埗焴㒯𤆬燫𦱀𤾗嬨𡞵𨩉"], +["9740","愌嫎娋䊼𤒈㜬䭻𨧼鎻鎸𡣖𠼝葲𦳀𡐓𤋺𢰦𤏁妔𣶷𦝁綨𦅛𦂤𤦹𤦋𨧺鋥珢㻩璴𨭣𡢟㻡𤪳櫘珳珻㻖𤨾𤪔𡟙𤩦𠎧𡐤𤧥瑈𤤖炥𤥶銄珦鍟𠓾錱𨫎𨨖鎆𨯧𥗕䤵𨪂煫"], +["97a1","𤥃𠳿嚤𠘚𠯫𠲸唂秄𡟺緾𡛂𤩐𡡒䔮鐁㜊𨫀𤦭妰𡢿𡢃𧒄媡㛢𣵛㚰鉟婹𨪁𡡢鍴㳍𠪴䪖㦊僴㵩㵌𡎜煵䋻𨈘渏𩃤䓫浗𧹏灧沯㳖𣿭𣸭渂漌㵯𠏵畑㚼㓈䚀㻚䡱姄鉮䤾轁𨰜𦯀堒埈㛖𡑒烾𤍢𤩱𢿣𡊰𢎽梹楧𡎘𣓥𧯴𣛟𨪃𣟖𣏺𤲟樚𣚭𦲷萾䓟䓎"], +["9840","𦴦𦵑𦲂𦿞漗𧄉茽𡜺菭𦲀𧁓𡟛妉媂𡞳婡婱𡤅𤇼㜭姯𡜼㛇熎鎐暚𤊥婮娫𤊓樫𣻹𧜶𤑛𤋊焝𤉙𨧡侰𦴨峂𤓎𧹍𤎽樌𤉖𡌄炦焳𤏩㶥泟勇𤩏繥姫崯㷳彜𤩝𡟟綤萦"], +["98a1","咅𣫺𣌀𠈔坾𠣕𠘙㿥𡾞𪊶瀃𩅛嵰玏糓𨩙𩐠俈翧狍猐𧫴猸猹𥛶獁獈㺩𧬘遬燵𤣲珡臶㻊県㻑沢国琙琞琟㻢㻰㻴㻺瓓㼎㽓畂畭畲疍㽼痈痜㿀癍㿗癴㿜発𤽜熈嘣覀塩䀝睃䀹条䁅㗛瞘䁪䁯属瞾矋売砘点砜䂨砹硇硑硦葈𥔵礳栃礲䄃"], +["9940","䄉禑禙辻稆込䅧窑䆲窼艹䇄竏竛䇏両筢筬筻簒簛䉠䉺类粜䊌粸䊔糭输烀𠳏総緔緐緽羮羴犟䎗耠耥笹耮耱联㷌垴炠肷胩䏭脌猪脎脒畠脔䐁㬹腖腙腚"], +["99a1","䐓堺腼膄䐥膓䐭膥埯臁臤艔䒏芦艶苊苘苿䒰荗险榊萅烵葤惣蒈䔄蒾蓡蓸蔐蔸蕒䔻蕯蕰藠䕷虲蚒蚲蛯际螋䘆䘗袮裿褤襇覑𧥧訩訸誔誴豑賔賲贜䞘塟跃䟭仮踺嗘坔蹱嗵躰䠷軎転軤軭軲辷迁迊迌逳駄䢭飠鈓䤞鈨鉘鉫銱銮銿"], +["9a40","鋣鋫鋳鋴鋽鍃鎄鎭䥅䥑麿鐗匁鐝鐭鐾䥪鑔鑹锭関䦧间阳䧥枠䨤靀䨵鞲韂噔䫤惨颹䬙飱塄餎餙冴餜餷饂饝饢䭰駅䮝騼鬏窃魩鮁鯝鯱鯴䱭鰠㝯𡯂鵉鰺"], +["9aa1","黾噐鶓鶽鷀鷼银辶鹻麬麱麽黆铜黢黱黸竈齄𠂔𠊷𠎠椚铃妬𠓗塀铁㞹𠗕𠘕𠙶𡚺块煳𠫂𠫍𠮿呪吆𠯋咞𠯻𠰻𠱓𠱥𠱼惧𠲍噺𠲵𠳝𠳭𠵯𠶲𠷈楕鰯螥𠸄𠸎𠻗𠾐𠼭𠹳尠𠾼帋𡁜𡁏𡁶朞𡁻𡂈𡂖㙇𡂿𡃓𡄯𡄻卤蒭𡋣𡍵𡌶讁𡕷𡘙𡟃𡟇乸炻𡠭𡥪"], +["9b40","𡨭𡩅𡰪𡱰𡲬𡻈拃𡻕𡼕熘桕𢁅槩㛈𢉼𢏗𢏺𢜪𢡱𢥏苽𢥧𢦓𢫕覥𢫨辠𢬎鞸𢬿顇骽𢱌"], +["9b62","𢲈𢲷𥯨𢴈𢴒𢶷𢶕𢹂𢽴𢿌𣀳𣁦𣌟𣏞徱晈暿𧩹𣕧𣗳爁𤦺矗𣘚𣜖纇𠍆墵朎"], +["9ba1","椘𣪧𧙗𥿢𣸑𣺹𧗾𢂚䣐䪸𤄙𨪚𤋮𤌍𤀻𤌴𤎖𤩅𠗊凒𠘑妟𡺨㮾𣳿𤐄𤓖垈𤙴㦛𤜯𨗨𩧉㝢𢇃譞𨭎駖𤠒𤣻𤨕爉𤫀𠱸奥𤺥𤾆𠝹軚𥀬劏圿煱𥊙𥐙𣽊𤪧喼𥑆𥑮𦭒釔㑳𥔿𧘲𥕞䜘𥕢𥕦𥟇𤤿𥡝偦㓻𣏌惞𥤃䝼𨥈𥪮𥮉𥰆𡶐垡煑澶𦄂𧰒遖𦆲𤾚譢𦐂𦑊"], +["9c40","嵛𦯷輶𦒄𡤜諪𤧶𦒈𣿯𦔒䯀𦖿𦚵𢜛鑥𥟡憕娧晉侻嚹𤔡𦛼乪𤤴陖涏𦲽㘘襷𦞙𦡮𦐑𦡞營𦣇筂𩃀𠨑𦤦鄄𦤹穅鷰𦧺騦𦨭㙟𦑩𠀡禃𦨴𦭛崬𣔙菏𦮝䛐𦲤画补𦶮墶"], +["9ca1","㜜𢖍𧁋𧇍㱔𧊀𧊅銁𢅺𧊋錰𧋦𤧐氹钟𧑐𠻸蠧裵𢤦𨑳𡞱溸𤨪𡠠㦤㚹尐秣䔿暶𩲭𩢤襃𧟌𧡘囖䃟𡘊㦡𣜯𨃨𡏅熭荦𧧝𩆨婧䲷𧂯𨦫𧧽𧨊𧬋𧵦𤅺筃祾𨀉澵𪋟樃𨌘厢𦸇鎿栶靝𨅯𨀣𦦵𡏭𣈯𨁈嶅𨰰𨂃圕頣𨥉嶫𤦈斾槕叒𤪥𣾁㰑朶𨂐𨃴𨄮𡾡𨅏"], +["9d40","𨆉𨆯𨈚𨌆𨌯𨎊㗊𨑨𨚪䣺揦𨥖砈鉕𨦸䏲𨧧䏟𨧨𨭆𨯔姸𨰉輋𨿅𩃬筑𩄐𩄼㷷𩅞𤫊运犏嚋𩓧𩗩𩖰𩖸𩜲𩣑𩥉𩥪𩧃𩨨𩬎𩵚𩶛纟𩻸𩼣䲤镇𪊓熢𪋿䶑递𪗋䶜𠲜达嗁"], +["9da1","辺𢒰边𤪓䔉繿潖檱仪㓤𨬬𧢝㜺躀𡟵𨀤𨭬𨮙𧨾𦚯㷫𧙕𣲷𥘵𥥖亚𥺁𦉘嚿𠹭踎孭𣺈𤲞揞拐𡟶𡡻攰嘭𥱊吚𥌑㷆𩶘䱽嘢嘞罉𥻘奵𣵀蝰东𠿪𠵉𣚺脗鵞贘瘻鱅癎瞹鍅吲腈苷嘥脲萘肽嗪祢噃吖𠺝㗎嘅嗱曱𨋢㘭甴嗰喺咗啲𠱁𠲖廐𥅈𠹶𢱢"], +["9e40","𠺢麫絚嗞𡁵抝靭咔賍燶酶揼掹揾啩𢭃鱲𢺳冚㓟𠶧冧呍唞唓癦踭𦢊疱肶蠄螆裇膶萜𡃁䓬猄𤜆宐茋𦢓噻𢛴𧴯𤆣𧵳𦻐𧊶酰𡇙鈈𣳼𪚩𠺬𠻹牦𡲢䝎𤿂𧿹𠿫䃺"], +["9ea1","鱝攟𢶠䣳𤟠𩵼𠿬𠸊恢𧖣𠿭"], +["9ead","𦁈𡆇熣纎鵐业丄㕷嬍沲卧㚬㧜卽㚥𤘘墚𤭮舭呋垪𥪕𠥹"], +["9ec5","㩒𢑥獴𩺬䴉鯭𣳾𩼰䱛𤾩𩖞𩿞葜𣶶𧊲𦞳𣜠挮紥𣻷𣸬㨪逈勌㹴㙺䗩𠒎癀嫰𠺶硺𧼮墧䂿噼鮋嵴癔𪐴麅䳡痹㟻愙𣃚𤏲"], +["9ef5","噝𡊩垧𤥣𩸆刴𧂮㖭汊鵼"], +["9f40","籖鬹埞𡝬屓擓𩓐𦌵𧅤蚭𠴨𦴢𤫢𠵱"], +["9f4f","凾𡼏嶎霃𡷑麁遌笟鬂峑箣扨挵髿篏鬪籾鬮籂粆鰕篼鬉鼗鰛𤤾齚啳寃俽麘俲剠㸆勑坧偖妷帒韈鶫轜呩鞴饀鞺匬愰"], +["9fa1","椬叚鰊鴂䰻陁榀傦畆𡝭駚剳"], +["9fae","酙隁酜"], +["9fb2","酑𨺗捿𦴣櫊嘑醎畺抅𠏼獏籰𥰡𣳽"], +["9fc1","𤤙盖鮝个𠳔莾衂"], +["9fc9","届槀僭坺刟巵从氱𠇲伹咜哚劚趂㗾弌㗳"], +["9fdb","歒酼龥鮗頮颴骺麨麄煺笔"], +["9fe7","毺蠘罸"], +["9feb","嘠𪙊蹷齓"], +["9ff0","跔蹏鸜踁抂𨍽踨蹵竓𤩷稾磘泪詧瘇"], +["a040","𨩚鼦泎蟖痃𪊲硓咢贌狢獱謭猂瓱賫𤪻蘯徺袠䒷"], +["a055","𡠻𦸅"], +["a058","詾𢔛"], +["a05b","惽癧髗鵄鍮鮏蟵"], +["a063","蠏賷猬霡鮰㗖犲䰇籑饊𦅙慙䰄麖慽"], +["a073","坟慯抦戹拎㩜懢厪𣏵捤栂㗒"], +["a0a1","嵗𨯂迚𨸹"], +["a0a6","僙𡵆礆匲阸𠼻䁥"], +["a0ae","矾"], +["a0b0","糂𥼚糚稭聦聣絍甅瓲覔舚朌聢𧒆聛瓰脃眤覉𦟌畓𦻑螩蟎臈螌詉貭譃眫瓸蓚㘵榲趦"], +["a0d4","覩瑨涹蟁𤀑瓧㷛煶悤憜㳑煢恷"], +["a0e2","罱𨬭牐惩䭾删㰘𣳇𥻗𧙖𥔱𡥄𡋾𩤃𦷜𧂭峁𦆭𨨏𣙷𠃮𦡆𤼎䕢嬟𦍌齐麦𦉫"], +["a3c0","␀",31,"␡"], +["c6a1","①",9,"⑴",9,"ⅰ",9,"丶丿亅亠冂冖冫勹匸卩厶夊宀巛⼳广廴彐彡攴无疒癶辵隶¨ˆヽヾゝゞ〃仝々〆〇ー[]✽ぁ",23], +["c740","す",58,"ァアィイ"], +["c7a1","ゥ",81,"А",5,"ЁЖ",4], +["c840","Л",26,"ёж",25,"⇧↸↹㇏𠃌乚𠂊刂䒑"], +["c8a1","龰冈龱𧘇"], +["c8cd","¬¦'"㈱№℡゛゜⺀⺄⺆⺇⺈⺊⺌⺍⺕⺜⺝⺥⺧⺪⺬⺮⺶⺼⺾⻆⻊⻌⻍⻏⻖⻗⻞⻣"], +["c8f5","ʃɐɛɔɵœøŋʊɪ"], +["f9fe","■"], +["fa40","𠕇鋛𠗟𣿅蕌䊵珯况㙉𤥂𨧤鍄𡧛苮𣳈砼杄拟𤤳𨦪𠊠𦮳𡌅侫𢓭倈𦴩𧪄𣘀𤪱𢔓倩𠍾徤𠎀𠍇滛𠐟偽儁㑺儎顬㝃萖𤦤𠒇兠𣎴兪𠯿𢃼𠋥𢔰𠖎𣈳𡦃宂蝽𠖳𣲙冲冸"], +["faa1","鴴凉减凑㳜凓𤪦决凢卂凭菍椾𣜭彻刋刦刼劵剗劔効勅簕蕂勠蘍𦬓包𨫞啉滙𣾀𠥔𣿬匳卄𠯢泋𡜦栛珕恊㺪㣌𡛨燝䒢卭却𨚫卾卿𡖖𡘓矦厓𨪛厠厫厮玧𥝲㽙玜叁叅汉义埾叙㪫𠮏叠𣿫𢶣叶𠱷吓灹唫晗浛呭𦭓𠵴啝咏咤䞦𡜍𠻝㶴𠵍"], +["fb40","𨦼𢚘啇䳭启琗喆喩嘅𡣗𤀺䕒𤐵暳𡂴嘷曍𣊊暤暭噍噏磱囱鞇叾圀囯园𨭦㘣𡉏坆𤆥汮炋坂㚱𦱾埦𡐖堃𡑔𤍣堦𤯵塜墪㕡壠壜𡈼壻寿坃𪅐𤉸鏓㖡够梦㛃湙"], +["fba1","𡘾娤啓𡚒蔅姉𠵎𦲁𦴪𡟜姙𡟻𡞲𦶦浱𡠨𡛕姹𦹅媫婣㛦𤦩婷㜈媖瑥嫓𦾡𢕔㶅𡤑㜲𡚸広勐孶斈孼𧨎䀄䡝𠈄寕慠𡨴𥧌𠖥寳宝䴐尅𡭄尓珎尔𡲥𦬨屉䣝岅峩峯嶋𡷹𡸷崐崘嵆𡺤岺巗苼㠭𤤁𢁉𢅳芇㠶㯂帮檊幵幺𤒼𠳓厦亷廐厨𡝱帉廴𨒂"], +["fc40","廹廻㢠廼栾鐛弍𠇁弢㫞䢮𡌺强𦢈𢏐彘𢑱彣鞽𦹮彲鍀𨨶徧嶶㵟𥉐𡽪𧃸𢙨釖𠊞𨨩怱暅𡡷㥣㷇㘹垐𢞴祱㹀悞悤悳𤦂𤦏𧩓璤僡媠慤萤慂慈𦻒憁凴𠙖憇宪𣾷"], +["fca1","𢡟懓𨮝𩥝懐㤲𢦀𢣁怣慜攞掋𠄘担𡝰拕𢸍捬𤧟㨗搸揸𡎎𡟼撐澊𢸶頔𤂌𥜝擡擥鑻㩦携㩗敍漖𤨨𤨣斅敭敟𣁾斵𤥀䬷旑䃘𡠩无旣忟𣐀昘𣇷𣇸晄𣆤𣆥晋𠹵晧𥇦晳晴𡸽𣈱𨗴𣇈𥌓矅𢣷馤朂𤎜𤨡㬫槺𣟂杞杧杢𤇍𩃭柗䓩栢湐鈼栁𣏦𦶠桝"], +["fd40","𣑯槡樋𨫟楳棃𣗍椁椀㴲㨁𣘼㮀枬楡𨩊䋼椶榘㮡𠏉荣傐槹𣙙𢄪橅𣜃檝㯳枱櫈𩆜㰍欝𠤣惞欵歴𢟍溵𣫛𠎵𡥘㝀吡𣭚毡𣻼毜氷𢒋𤣱𦭑汚舦汹𣶼䓅𣶽𤆤𤤌𤤀"], +["fda1","𣳉㛥㳫𠴲鮃𣇹𢒑羏样𦴥𦶡𦷫涖浜湼漄𤥿𤂅𦹲蔳𦽴凇沜渝萮𨬡港𣸯瑓𣾂秌湏媑𣁋濸㜍澝𣸰滺𡒗𤀽䕕鏰潄潜㵎潴𩅰㴻澟𤅄濓𤂑𤅕𤀹𣿰𣾴𤄿凟𤅖𤅗𤅀𦇝灋灾炧炁烌烕烖烟䄄㷨熴熖𤉷焫煅媈煊煮岜𤍥煏鍢𤋁焬𤑚𤨧𤨢熺𨯨炽爎"], +["fe40","鑂爕夑鑃爤鍁𥘅爮牀𤥴梽牕牗㹕𣁄栍漽犂猪猫𤠣𨠫䣭𨠄猨献珏玪𠰺𦨮珉瑉𤇢𡛧𤨤昣㛅𤦷𤦍𤧻珷琕椃𤨦琹𠗃㻗瑜𢢭瑠𨺲瑇珤瑶莹瑬㜰瑴鏱樬璂䥓𤪌"], +["fea1","𤅟𤩹𨮏孆𨰃𡢞瓈𡦈甎瓩甞𨻙𡩋寗𨺬鎅畍畊畧畮𤾂㼄𤴓疎瑝疞疴瘂瘬癑癏癯癶𦏵皐臯㟸𦤑𦤎皡皥皷盌𦾟葢𥂝𥅽𡸜眞眦着撯𥈠睘𣊬瞯𨥤𨥨𡛁矴砉𡍶𤨒棊碯磇磓隥礮𥗠磗礴碱𧘌辸袄𨬫𦂃𢘜禆褀椂禀𥡗禝𧬹礼禩渪𧄦㺨秆𩄍秔"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp936.json b/node_modules/iconv-lite/encodings/tables/cp936.json new file mode 100644 index 00000000..49ddb9a1 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp936.json @@ -0,0 +1,264 @@ +[ +["0","\u0000",127,"€"], +["8140","丂丄丅丆丏丒丗丟丠両丣並丩丮丯丱丳丵丷丼乀乁乂乄乆乊乑乕乗乚乛乢乣乤乥乧乨乪",5,"乲乴",9,"乿",6,"亇亊"], +["8180","亐亖亗亙亜亝亞亣亪亯亰亱亴亶亷亸亹亼亽亾仈仌仏仐仒仚仛仜仠仢仦仧仩仭仮仯仱仴仸仹仺仼仾伀伂",6,"伋伌伒",4,"伜伝伡伣伨伩伬伭伮伱伳伵伷伹伻伾",4,"佄佅佇",5,"佒佔佖佡佢佦佨佪佫佭佮佱佲併佷佸佹佺佽侀侁侂侅來侇侊侌侎侐侒侓侕侖侘侙侚侜侞侟価侢"], +["8240","侤侫侭侰",4,"侶",8,"俀俁係俆俇俈俉俋俌俍俒",4,"俙俛俠俢俤俥俧俫俬俰俲俴俵俶俷俹俻俼俽俿",11], +["8280","個倎倐們倓倕倖倗倛倝倞倠倢倣値倧倫倯",10,"倻倽倿偀偁偂偄偅偆偉偊偋偍偐",4,"偖偗偘偙偛偝",7,"偦",5,"偭",8,"偸偹偺偼偽傁傂傃傄傆傇傉傊傋傌傎",20,"傤傦傪傫傭",4,"傳",6,"傼"], +["8340","傽",17,"僐",5,"僗僘僙僛",10,"僨僩僪僫僯僰僱僲僴僶",4,"僼",9,"儈"], +["8380","儉儊儌",5,"儓",13,"儢",28,"兂兇兊兌兎兏児兒兓兗兘兙兛兝",4,"兣兤兦內兩兪兯兲兺兾兿冃冄円冇冊冋冎冏冐冑冓冔冘冚冝冞冟冡冣冦",4,"冭冮冴冸冹冺冾冿凁凂凃凅凈凊凍凎凐凒",5], +["8440","凘凙凚凜凞凟凢凣凥",5,"凬凮凱凲凴凷凾刄刅刉刋刌刏刐刓刔刕刜刞刟刡刢刣別刦刧刪刬刯刱刲刴刵刼刾剄",5,"剋剎剏剒剓剕剗剘"], +["8480","剙剚剛剝剟剠剢剣剤剦剨剫剬剭剮剰剱剳",9,"剾劀劃",4,"劉",6,"劑劒劔",6,"劜劤劥劦劧劮劯劰労",9,"勀勁勂勄勅勆勈勊勌勍勎勏勑勓勔動勗務",5,"勠勡勢勣勥",10,"勱",7,"勻勼勽匁匂匃匄匇匉匊匋匌匎"], +["8540","匑匒匓匔匘匛匜匞匟匢匤匥匧匨匩匫匬匭匯",9,"匼匽區卂卄卆卋卌卍卐協単卙卛卝卥卨卪卬卭卲卶卹卻卼卽卾厀厁厃厇厈厊厎厏"], +["8580","厐",4,"厖厗厙厛厜厞厠厡厤厧厪厫厬厭厯",6,"厷厸厹厺厼厽厾叀參",4,"収叏叐叒叓叕叚叜叝叞叡叢叧叴叺叾叿吀吂吅吇吋吔吘吙吚吜吢吤吥吪吰吳吶吷吺吽吿呁呂呄呅呇呉呌呍呎呏呑呚呝",4,"呣呥呧呩",7,"呴呹呺呾呿咁咃咅咇咈咉咊咍咑咓咗咘咜咞咟咠咡"], +["8640","咢咥咮咰咲咵咶咷咹咺咼咾哃哅哊哋哖哘哛哠",4,"哫哬哯哰哱哴",5,"哻哾唀唂唃唄唅唈唊",4,"唒唓唕",5,"唜唝唞唟唡唥唦"], +["8680","唨唩唫唭唲唴唵唶唸唹唺唻唽啀啂啅啇啈啋",4,"啑啒啓啔啗",4,"啝啞啟啠啢啣啨啩啫啯",5,"啹啺啽啿喅喆喌喍喎喐喒喓喕喖喗喚喛喞喠",6,"喨",8,"喲喴営喸喺喼喿",4,"嗆嗇嗈嗊嗋嗎嗏嗐嗕嗗",4,"嗞嗠嗢嗧嗩嗭嗮嗰嗱嗴嗶嗸",4,"嗿嘂嘃嘄嘅"], +["8740","嘆嘇嘊嘋嘍嘐",7,"嘙嘚嘜嘝嘠嘡嘢嘥嘦嘨嘩嘪嘫嘮嘯嘰嘳嘵嘷嘸嘺嘼嘽嘾噀",11,"噏",4,"噕噖噚噛噝",4], +["8780","噣噥噦噧噭噮噯噰噲噳噴噵噷噸噹噺噽",7,"嚇",6,"嚐嚑嚒嚔",14,"嚤",10,"嚰",6,"嚸嚹嚺嚻嚽",12,"囋",8,"囕囖囘囙囜団囥",5,"囬囮囯囲図囶囷囸囻囼圀圁圂圅圇國",6], +["8840","園",9,"圝圞圠圡圢圤圥圦圧圫圱圲圴",4,"圼圽圿坁坃坄坅坆坈坉坋坒",4,"坘坙坢坣坥坧坬坮坰坱坲坴坵坸坹坺坽坾坿垀"], +["8880","垁垇垈垉垊垍",4,"垔",6,"垜垝垞垟垥垨垪垬垯垰垱垳垵垶垷垹",8,"埄",6,"埌埍埐埑埓埖埗埛埜埞埡埢埣埥",7,"埮埰埱埲埳埵埶執埻埼埾埿堁堃堄堅堈堉堊堌堎堏堐堒堓堔堖堗堘堚堛堜堝堟堢堣堥",4,"堫",4,"報堲堳場堶",7], +["8940","堾",5,"塅",6,"塎塏塐塒塓塕塖塗塙",4,"塟",5,"塦",4,"塭",16,"塿墂墄墆墇墈墊墋墌"], +["8980","墍",4,"墔",4,"墛墜墝墠",7,"墪",17,"墽墾墿壀壂壃壄壆",10,"壒壓壔壖",13,"壥",5,"壭壯壱売壴壵壷壸壺",7,"夃夅夆夈",4,"夎夐夑夒夓夗夘夛夝夞夠夡夢夣夦夨夬夰夲夳夵夶夻"], +["8a40","夽夾夿奀奃奅奆奊奌奍奐奒奓奙奛",4,"奡奣奤奦",12,"奵奷奺奻奼奾奿妀妅妉妋妌妎妏妐妑妔妕妘妚妛妜妝妟妠妡妢妦"], +["8a80","妧妬妭妰妱妳",5,"妺妼妽妿",6,"姇姈姉姌姍姎姏姕姖姙姛姞",4,"姤姦姧姩姪姫姭",11,"姺姼姽姾娀娂娊娋娍娎娏娐娒娔娕娖娗娙娚娛娝娞娡娢娤娦娧娨娪",6,"娳娵娷",4,"娽娾娿婁",4,"婇婈婋",9,"婖婗婘婙婛",5], +["8b40","婡婣婤婥婦婨婩婫",8,"婸婹婻婼婽婾媀",17,"媓",6,"媜",13,"媫媬"], +["8b80","媭",4,"媴媶媷媹",4,"媿嫀嫃",5,"嫊嫋嫍",4,"嫓嫕嫗嫙嫚嫛嫝嫞嫟嫢嫤嫥嫧嫨嫪嫬",4,"嫲",22,"嬊",11,"嬘",25,"嬳嬵嬶嬸",7,"孁",6], +["8c40","孈",7,"孒孖孞孠孡孧孨孫孭孮孯孲孴孶孷學孹孻孼孾孿宂宆宊宍宎宐宑宒宔宖実宧宨宩宬宭宮宯宱宲宷宺宻宼寀寁寃寈寉寊寋寍寎寏"], +["8c80","寑寔",8,"寠寢寣實寧審",4,"寯寱",6,"寽対尀専尃尅將專尋尌對導尐尒尓尗尙尛尞尟尠尡尣尦尨尩尪尫尭尮尯尰尲尳尵尶尷屃屄屆屇屌屍屒屓屔屖屗屘屚屛屜屝屟屢層屧",6,"屰屲",6,"屻屼屽屾岀岃",4,"岉岊岋岎岏岒岓岕岝",4,"岤",4], +["8d40","岪岮岯岰岲岴岶岹岺岻岼岾峀峂峃峅",5,"峌",5,"峓",5,"峚",6,"峢峣峧峩峫峬峮峯峱",9,"峼",4], +["8d80","崁崄崅崈",5,"崏",4,"崕崗崘崙崚崜崝崟",4,"崥崨崪崫崬崯",4,"崵",7,"崿",7,"嵈嵉嵍",10,"嵙嵚嵜嵞",10,"嵪嵭嵮嵰嵱嵲嵳嵵",12,"嶃",21,"嶚嶛嶜嶞嶟嶠"], +["8e40","嶡",21,"嶸",12,"巆",6,"巎",12,"巜巟巠巣巤巪巬巭"], +["8e80","巰巵巶巸",4,"巿帀帄帇帉帊帋帍帎帒帓帗帞",7,"帨",4,"帯帰帲",4,"帹帺帾帿幀幁幃幆",5,"幍",6,"幖",4,"幜幝幟幠幣",14,"幵幷幹幾庁庂広庅庈庉庌庍庎庒庘庛庝庡庢庣庤庨",4,"庮",4,"庴庺庻庼庽庿",6], +["8f40","廆廇廈廋",5,"廔廕廗廘廙廚廜",11,"廩廫",8,"廵廸廹廻廼廽弅弆弇弉弌弍弎弐弒弔弖弙弚弜弝弞弡弢弣弤"], +["8f80","弨弫弬弮弰弲",6,"弻弽弾弿彁",14,"彑彔彙彚彛彜彞彟彠彣彥彧彨彫彮彯彲彴彵彶彸彺彽彾彿徃徆徍徎徏徑従徔徖徚徛徝從徟徠徢",5,"復徫徬徯",5,"徶徸徹徺徻徾",4,"忇忈忊忋忎忓忔忕忚忛応忞忟忢忣忥忦忨忩忬忯忰忲忳忴忶忷忹忺忼怇"], +["9040","怈怉怋怌怐怑怓怗怘怚怞怟怢怣怤怬怭怮怰",4,"怶",4,"怽怾恀恄",6,"恌恎恏恑恓恔恖恗恘恛恜恞恟恠恡恥恦恮恱恲恴恵恷恾悀"], +["9080","悁悂悅悆悇悈悊悋悎悏悐悑悓悕悗悘悙悜悞悡悢悤悥悧悩悪悮悰悳悵悶悷悹悺悽",7,"惇惈惉惌",4,"惒惓惔惖惗惙惛惞惡",4,"惪惱惲惵惷惸惻",4,"愂愃愄愅愇愊愋愌愐",4,"愖愗愘愙愛愜愝愞愡愢愥愨愩愪愬",18,"慀",6], +["9140","慇慉態慍慏慐慒慓慔慖",6,"慞慟慠慡慣慤慥慦慩",6,"慱慲慳慴慶慸",18,"憌憍憏",4,"憕"], +["9180","憖",6,"憞",8,"憪憫憭",9,"憸",5,"憿懀懁懃",4,"應懌",4,"懓懕",16,"懧",13,"懶",8,"戀",5,"戇戉戓戔戙戜戝戞戠戣戦戧戨戩戫戭戯戰戱戲戵戶戸",4,"扂扄扅扆扊"], +["9240","扏扐払扖扗扙扚扜",6,"扤扥扨扱扲扴扵扷扸扺扻扽抁抂抃抅抆抇抈抋",5,"抔抙抜抝択抣抦抧抩抪抭抮抯抰抲抳抴抶抷抸抺抾拀拁"], +["9280","拃拋拏拑拕拝拞拠拡拤拪拫拰拲拵拸拹拺拻挀挃挄挅挆挊挋挌挍挏挐挒挓挔挕挗挘挙挜挦挧挩挬挭挮挰挱挳",5,"挻挼挾挿捀捁捄捇捈捊捑捒捓捔捖",7,"捠捤捥捦捨捪捫捬捯捰捲捳捴捵捸捹捼捽捾捿掁掃掄掅掆掋掍掑掓掔掕掗掙",6,"採掤掦掫掯掱掲掵掶掹掻掽掿揀"], +["9340","揁揂揃揅揇揈揊揋揌揑揓揔揕揗",6,"揟揢揤",4,"揫揬揮揯揰揱揳揵揷揹揺揻揼揾搃搄搆",4,"損搎搑搒搕",5,"搝搟搢搣搤"], +["9380","搥搧搨搩搫搮",5,"搵",4,"搻搼搾摀摂摃摉摋",6,"摓摕摖摗摙",4,"摟",7,"摨摪摫摬摮",9,"摻",6,"撃撆撈",8,"撓撔撗撘撚撛撜撝撟",4,"撥撦撧撨撪撫撯撱撲撳撴撶撹撻撽撾撿擁擃擄擆",6,"擏擑擓擔擕擖擙據"], +["9440","擛擜擝擟擠擡擣擥擧",24,"攁",7,"攊",7,"攓",4,"攙",8], +["9480","攢攣攤攦",4,"攬攭攰攱攲攳攷攺攼攽敀",4,"敆敇敊敋敍敎敐敒敓敔敗敘敚敜敟敠敡敤敥敧敨敩敪敭敮敯敱敳敵敶數",14,"斈斉斊斍斎斏斒斔斕斖斘斚斝斞斠斢斣斦斨斪斬斮斱",7,"斺斻斾斿旀旂旇旈旉旊旍旐旑旓旔旕旘",7,"旡旣旤旪旫"], +["9540","旲旳旴旵旸旹旻",4,"昁昄昅昇昈昉昋昍昐昑昒昖昗昘昚昛昜昞昡昢昣昤昦昩昪昫昬昮昰昲昳昷",4,"昽昿晀時晄",6,"晍晎晐晑晘"], +["9580","晙晛晜晝晞晠晢晣晥晧晩",4,"晱晲晳晵晸晹晻晼晽晿暀暁暃暅暆暈暉暊暋暍暎暏暐暒暓暔暕暘",4,"暞",8,"暩",4,"暯",4,"暵暶暷暸暺暻暼暽暿",25,"曚曞",7,"曧曨曪",5,"曱曵曶書曺曻曽朁朂會"], +["9640","朄朅朆朇朌朎朏朑朒朓朖朘朙朚朜朞朠",5,"朧朩朮朰朲朳朶朷朸朹朻朼朾朿杁杄杅杇杊杋杍杒杔杕杗",4,"杝杢杣杤杦杧杫杬杮東杴杶"], +["9680","杸杹杺杻杽枀枂枃枅枆枈枊枌枍枎枏枑枒枓枔枖枙枛枟枠枡枤枦枩枬枮枱枲枴枹",7,"柂柅",9,"柕柖柗柛柟柡柣柤柦柧柨柪柫柭柮柲柵",7,"柾栁栂栃栄栆栍栐栒栔栕栘",4,"栞栟栠栢",6,"栫",6,"栴栵栶栺栻栿桇桋桍桏桒桖",5], +["9740","桜桝桞桟桪桬",7,"桵桸",8,"梂梄梇",7,"梐梑梒梔梕梖梘",9,"梣梤梥梩梪梫梬梮梱梲梴梶梷梸"], +["9780","梹",6,"棁棃",5,"棊棌棎棏棐棑棓棔棖棗棙棛",4,"棡棢棤",9,"棯棲棳棴棶棷棸棻棽棾棿椀椂椃椄椆",4,"椌椏椑椓",11,"椡椢椣椥",7,"椮椯椱椲椳椵椶椷椸椺椻椼椾楀楁楃",16,"楕楖楘楙楛楜楟"], +["9840","楡楢楤楥楧楨楩楪楬業楯楰楲",4,"楺楻楽楾楿榁榃榅榊榋榌榎",5,"榖榗榙榚榝",9,"榩榪榬榮榯榰榲榳榵榶榸榹榺榼榽"], +["9880","榾榿槀槂",7,"構槍槏槑槒槓槕",5,"槜槝槞槡",11,"槮槯槰槱槳",9,"槾樀",9,"樋",11,"標",5,"樠樢",5,"権樫樬樭樮樰樲樳樴樶",6,"樿",4,"橅橆橈",7,"橑",6,"橚"], +["9940","橜",4,"橢橣橤橦",10,"橲",6,"橺橻橽橾橿檁檂檃檅",8,"檏檒",4,"檘",7,"檡",5], +["9980","檧檨檪檭",114,"欥欦欨",6], +["9a40","欯欰欱欳欴欵欶欸欻欼欽欿歀歁歂歄歅歈歊歋歍",11,"歚",7,"歨歩歫",13,"歺歽歾歿殀殅殈"], +["9a80","殌殎殏殐殑殔殕殗殘殙殜",4,"殢",7,"殫",7,"殶殸",6,"毀毃毄毆",4,"毌毎毐毑毘毚毜",4,"毢",7,"毬毭毮毰毱毲毴毶毷毸毺毻毼毾",6,"氈",4,"氎氒気氜氝氞氠氣氥氫氬氭氱氳氶氷氹氺氻氼氾氿汃汄汅汈汋",4,"汑汒汓汖汘"], +["9b40","汙汚汢汣汥汦汧汫",4,"汱汳汵汷汸決汻汼汿沀沄沇沊沋沍沎沑沒沕沖沗沘沚沜沝沞沠沢沨沬沯沰沴沵沶沷沺泀況泂泃泆泇泈泋泍泎泏泑泒泘"], +["9b80","泙泚泜泝泟泤泦泧泩泬泭泲泴泹泿洀洂洃洅洆洈洉洊洍洏洐洑洓洔洕洖洘洜洝洟",5,"洦洨洩洬洭洯洰洴洶洷洸洺洿浀浂浄浉浌浐浕浖浗浘浛浝浟浡浢浤浥浧浨浫浬浭浰浱浲浳浵浶浹浺浻浽",4,"涃涄涆涇涊涋涍涏涐涒涖",4,"涜涢涥涬涭涰涱涳涴涶涷涹",5,"淁淂淃淈淉淊"], +["9c40","淍淎淏淐淒淓淔淕淗淚淛淜淟淢淣淥淧淨淩淪淭淯淰淲淴淵淶淸淺淽",7,"渆渇済渉渋渏渒渓渕渘渙減渜渞渟渢渦渧渨渪測渮渰渱渳渵"], +["9c80","渶渷渹渻",7,"湅",7,"湏湐湑湒湕湗湙湚湜湝湞湠",10,"湬湭湯",14,"満溁溂溄溇溈溊",4,"溑",6,"溙溚溛溝溞溠溡溣溤溦溨溩溫溬溭溮溰溳溵溸溹溼溾溿滀滃滄滅滆滈滉滊滌滍滎滐滒滖滘滙滛滜滝滣滧滪",5], +["9d40","滰滱滲滳滵滶滷滸滺",7,"漃漄漅漇漈漊",4,"漐漑漒漖",9,"漡漢漣漥漦漧漨漬漮漰漲漴漵漷",6,"漿潀潁潂"], +["9d80","潃潄潅潈潉潊潌潎",9,"潙潚潛潝潟潠潡潣潤潥潧",5,"潯潰潱潳潵潶潷潹潻潽",6,"澅澆澇澊澋澏",12,"澝澞澟澠澢",4,"澨",10,"澴澵澷澸澺",5,"濁濃",5,"濊",6,"濓",10,"濟濢濣濤濥"], +["9e40","濦",7,"濰",32,"瀒",7,"瀜",6,"瀤",6], +["9e80","瀫",9,"瀶瀷瀸瀺",17,"灍灎灐",13,"灟",11,"灮灱灲灳灴灷灹灺灻災炁炂炃炄炆炇炈炋炌炍炏炐炑炓炗炘炚炛炞",12,"炰炲炴炵炶為炾炿烄烅烆烇烉烋",12,"烚"], +["9f40","烜烝烞烠烡烢烣烥烪烮烰",6,"烸烺烻烼烾",10,"焋",4,"焑焒焔焗焛",10,"焧",7,"焲焳焴"], +["9f80","焵焷",13,"煆煇煈煉煋煍煏",12,"煝煟",4,"煥煩",4,"煯煰煱煴煵煶煷煹煻煼煾",5,"熅",4,"熋熌熍熎熐熑熒熓熕熖熗熚",4,"熡",6,"熩熪熫熭",5,"熴熶熷熸熺",8,"燄",9,"燏",4], +["a040","燖",9,"燡燢燣燤燦燨",5,"燯",9,"燺",11,"爇",19], +["a080","爛爜爞",9,"爩爫爭爮爯爲爳爴爺爼爾牀",6,"牉牊牋牎牏牐牑牓牔牕牗牘牚牜牞牠牣牤牥牨牪牫牬牭牰牱牳牴牶牷牸牻牼牽犂犃犅",4,"犌犎犐犑犓",11,"犠",11,"犮犱犲犳犵犺",6,"狅狆狇狉狊狋狌狏狑狓狔狕狖狘狚狛"], +["a1a1"," 、。·ˉˇ¨〃々—~‖…‘’“”〔〕〈",7,"〖〗【】±×÷∶∧∨∑∏∪∩∈∷√⊥∥∠⌒⊙∫∮≡≌≈∽∝≠≮≯≤≥∞∵∴♂♀°′″℃$¤¢£‰§№☆★○●◎◇◆□■△▲※→←↑↓〓"], +["a2a1","ⅰ",9], +["a2b1","⒈",19,"⑴",19,"①",9], +["a2e5","㈠",9], +["a2f1","Ⅰ",11], +["a3a1","!"#¥%",88," ̄"], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a6e0","︵︶︹︺︿﹀︽︾﹁﹂﹃﹄"], +["a6ee","︻︼︷︸︱"], +["a6f4","︳︴"], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a840","ˊˋ˙–―‥‵℅℉↖↗↘↙∕∟∣≒≦≧⊿═",35,"▁",6], +["a880","█",7,"▓▔▕▼▽◢◣◤◥☉⊕〒〝〞"], +["a8a1","āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜüêɑ"], +["a8bd","ńň"], +["a8c0","ɡ"], +["a8c5","ㄅ",36], +["a940","〡",8,"㊣㎎㎏㎜㎝㎞㎡㏄㏎㏑㏒㏕︰¬¦"], +["a959","℡㈱"], +["a95c","‐"], +["a960","ー゛゜ヽヾ〆ゝゞ﹉",9,"﹔﹕﹖﹗﹙",8], +["a980","﹢",4,"﹨﹩﹪﹫"], +["a996","〇"], +["a9a4","─",75], +["aa40","狜狝狟狢",5,"狪狫狵狶狹狽狾狿猀猂猄",5,"猋猌猍猏猐猑猒猔猘猙猚猟猠猣猤猦猧猨猭猯猰猲猳猵猶猺猻猼猽獀",8], +["aa80","獉獊獋獌獎獏獑獓獔獕獖獘",7,"獡",10,"獮獰獱"], +["ab40","獲",11,"獿",4,"玅玆玈玊玌玍玏玐玒玓玔玕玗玘玙玚玜玝玞玠玡玣",5,"玪玬玭玱玴玵玶玸玹玼玽玾玿珁珃",4], +["ab80","珋珌珎珒",6,"珚珛珜珝珟珡珢珣珤珦珨珪珫珬珮珯珰珱珳",4], +["ac40","珸",10,"琄琇琈琋琌琍琎琑",8,"琜",5,"琣琤琧琩琫琭琯琱琲琷",4,"琽琾琿瑀瑂",11], +["ac80","瑎",6,"瑖瑘瑝瑠",12,"瑮瑯瑱",4,"瑸瑹瑺"], +["ad40","瑻瑼瑽瑿璂璄璅璆璈璉璊璌璍璏璑",10,"璝璟",7,"璪",15,"璻",12], +["ad80","瓈",9,"瓓",8,"瓝瓟瓡瓥瓧",6,"瓰瓱瓲"], +["ae40","瓳瓵瓸",6,"甀甁甂甃甅",7,"甎甐甒甔甕甖甗甛甝甞甠",4,"甦甧甪甮甴甶甹甼甽甿畁畂畃畄畆畇畉畊畍畐畑畒畓畕畖畗畘"], +["ae80","畝",7,"畧畨畩畫",6,"畳畵當畷畺",4,"疀疁疂疄疅疇"], +["af40","疈疉疊疌疍疎疐疓疕疘疛疜疞疢疦",4,"疭疶疷疺疻疿痀痁痆痋痌痎痏痐痑痓痗痙痚痜痝痟痠痡痥痩痬痭痮痯痲痳痵痶痷痸痺痻痽痾瘂瘄瘆瘇"], +["af80","瘈瘉瘋瘍瘎瘏瘑瘒瘓瘔瘖瘚瘜瘝瘞瘡瘣瘧瘨瘬瘮瘯瘱瘲瘶瘷瘹瘺瘻瘽癁療癄"], +["b040","癅",6,"癎",5,"癕癗",4,"癝癟癠癡癢癤",6,"癬癭癮癰",7,"癹発發癿皀皁皃皅皉皊皌皍皏皐皒皔皕皗皘皚皛"], +["b080","皜",7,"皥",8,"皯皰皳皵",9,"盀盁盃啊阿埃挨哎唉哀皑癌蔼矮艾碍爱隘鞍氨安俺按暗岸胺案肮昂盎凹敖熬翱袄傲奥懊澳芭捌扒叭吧笆八疤巴拔跋靶把耙坝霸罢爸白柏百摆佰败拜稗斑班搬扳般颁板版扮拌伴瓣半办绊邦帮梆榜膀绑棒磅蚌镑傍谤苞胞包褒剥"], +["b140","盄盇盉盋盌盓盕盙盚盜盝盞盠",4,"盦",7,"盰盳盵盶盷盺盻盽盿眀眂眃眅眆眊県眎",10,"眛眜眝眞眡眣眤眥眧眪眫"], +["b180","眬眮眰",4,"眹眻眽眾眿睂睄睅睆睈",7,"睒",7,"睜薄雹保堡饱宝抱报暴豹鲍爆杯碑悲卑北辈背贝钡倍狈备惫焙被奔苯本笨崩绷甭泵蹦迸逼鼻比鄙笔彼碧蓖蔽毕毙毖币庇痹闭敝弊必辟壁臂避陛鞭边编贬扁便变卞辨辩辫遍标彪膘表鳖憋别瘪彬斌濒滨宾摈兵冰柄丙秉饼炳"], +["b240","睝睞睟睠睤睧睩睪睭",11,"睺睻睼瞁瞂瞃瞆",5,"瞏瞐瞓",11,"瞡瞣瞤瞦瞨瞫瞭瞮瞯瞱瞲瞴瞶",4], +["b280","瞼瞾矀",12,"矎",8,"矘矙矚矝",4,"矤病并玻菠播拨钵波博勃搏铂箔伯帛舶脖膊渤泊驳捕卜哺补埠不布步簿部怖擦猜裁材才财睬踩采彩菜蔡餐参蚕残惭惨灿苍舱仓沧藏操糙槽曹草厕策侧册测层蹭插叉茬茶查碴搽察岔差诧拆柴豺搀掺蝉馋谗缠铲产阐颤昌猖"], +["b340","矦矨矪矯矰矱矲矴矵矷矹矺矻矼砃",5,"砊砋砎砏砐砓砕砙砛砞砠砡砢砤砨砪砫砮砯砱砲砳砵砶砽砿硁硂硃硄硆硈硉硊硋硍硏硑硓硔硘硙硚"], +["b380","硛硜硞",11,"硯",7,"硸硹硺硻硽",6,"场尝常长偿肠厂敞畅唱倡超抄钞朝嘲潮巢吵炒车扯撤掣彻澈郴臣辰尘晨忱沉陈趁衬撑称城橙成呈乘程惩澄诚承逞骋秤吃痴持匙池迟弛驰耻齿侈尺赤翅斥炽充冲虫崇宠抽酬畴踌稠愁筹仇绸瞅丑臭初出橱厨躇锄雏滁除楚"], +["b440","碄碅碆碈碊碋碏碐碒碔碕碖碙碝碞碠碢碤碦碨",7,"碵碶碷碸確碻碼碽碿磀磂磃磄磆磇磈磌磍磎磏磑磒磓磖磗磘磚",9], +["b480","磤磥磦磧磩磪磫磭",4,"磳磵磶磸磹磻",5,"礂礃礄礆",6,"础储矗搐触处揣川穿椽传船喘串疮窗幢床闯创吹炊捶锤垂春椿醇唇淳纯蠢戳绰疵茨磁雌辞慈瓷词此刺赐次聪葱囱匆从丛凑粗醋簇促蹿篡窜摧崔催脆瘁粹淬翠村存寸磋撮搓措挫错搭达答瘩打大呆歹傣戴带殆代贷袋待逮"], +["b540","礍",5,"礔",9,"礟",4,"礥",14,"礵",4,"礽礿祂祃祄祅祇祊",8,"祔祕祘祙祡祣"], +["b580","祤祦祩祪祫祬祮祰",6,"祹祻",4,"禂禃禆禇禈禉禋禌禍禎禐禑禒怠耽担丹单郸掸胆旦氮但惮淡诞弹蛋当挡党荡档刀捣蹈倒岛祷导到稻悼道盗德得的蹬灯登等瞪凳邓堤低滴迪敌笛狄涤翟嫡抵底地蒂第帝弟递缔颠掂滇碘点典靛垫电佃甸店惦奠淀殿碉叼雕凋刁掉吊钓调跌爹碟蝶迭谍叠"], +["b640","禓",6,"禛",11,"禨",10,"禴",4,"禼禿秂秄秅秇秈秊秌秎秏秐秓秔秖秗秙",5,"秠秡秢秥秨秪"], +["b680","秬秮秱",6,"秹秺秼秾秿稁稄稅稇稈稉稊稌稏",4,"稕稖稘稙稛稜丁盯叮钉顶鼎锭定订丢东冬董懂动栋侗恫冻洞兜抖斗陡豆逗痘都督毒犊独读堵睹赌杜镀肚度渡妒端短锻段断缎堆兑队对墩吨蹲敦顿囤钝盾遁掇哆多夺垛躲朵跺舵剁惰堕蛾峨鹅俄额讹娥恶厄扼遏鄂饿恩而儿耳尔饵洱二"], +["b740","稝稟稡稢稤",14,"稴稵稶稸稺稾穀",5,"穇",9,"穒",4,"穘",16], +["b780","穩",6,"穱穲穳穵穻穼穽穾窂窅窇窉窊窋窌窎窏窐窓窔窙窚窛窞窡窢贰发罚筏伐乏阀法珐藩帆番翻樊矾钒繁凡烦反返范贩犯饭泛坊芳方肪房防妨仿访纺放菲非啡飞肥匪诽吠肺废沸费芬酚吩氛分纷坟焚汾粉奋份忿愤粪丰封枫蜂峰锋风疯烽逢冯缝讽奉凤佛否夫敷肤孵扶拂辐幅氟符伏俘服"], +["b840","窣窤窧窩窪窫窮",4,"窴",10,"竀",10,"竌",9,"竗竘竚竛竜竝竡竢竤竧",5,"竮竰竱竲竳"], +["b880","竴",4,"竻竼竾笀笁笂笅笇笉笌笍笎笐笒笓笖笗笘笚笜笝笟笡笢笣笧笩笭浮涪福袱弗甫抚辅俯釜斧脯腑府腐赴副覆赋复傅付阜父腹负富讣附妇缚咐噶嘎该改概钙盖溉干甘杆柑竿肝赶感秆敢赣冈刚钢缸肛纲岗港杠篙皋高膏羔糕搞镐稿告哥歌搁戈鸽胳疙割革葛格蛤阁隔铬个各给根跟耕更庚羹"], +["b940","笯笰笲笴笵笶笷笹笻笽笿",5,"筆筈筊筍筎筓筕筗筙筜筞筟筡筣",10,"筯筰筳筴筶筸筺筼筽筿箁箂箃箄箆",6,"箎箏"], +["b980","箑箒箓箖箘箙箚箛箞箟箠箣箤箥箮箯箰箲箳箵箶箷箹",7,"篂篃範埂耿梗工攻功恭龚供躬公宫弓巩汞拱贡共钩勾沟苟狗垢构购够辜菇咕箍估沽孤姑鼓古蛊骨谷股故顾固雇刮瓜剐寡挂褂乖拐怪棺关官冠观管馆罐惯灌贯光广逛瑰规圭硅归龟闺轨鬼诡癸桂柜跪贵刽辊滚棍锅郭国果裹过哈"], +["ba40","篅篈築篊篋篍篎篏篐篒篔",4,"篛篜篞篟篠篢篣篤篧篨篩篫篬篭篯篰篲",4,"篸篹篺篻篽篿",7,"簈簉簊簍簎簐",5,"簗簘簙"], +["ba80","簚",4,"簠",5,"簨簩簫",12,"簹",5,"籂骸孩海氦亥害骇酣憨邯韩含涵寒函喊罕翰撼捍旱憾悍焊汗汉夯杭航壕嚎豪毫郝好耗号浩呵喝荷菏核禾和何合盒貉阂河涸赫褐鹤贺嘿黑痕很狠恨哼亨横衡恒轰哄烘虹鸿洪宏弘红喉侯猴吼厚候后呼乎忽瑚壶葫胡蝴狐糊湖"], +["bb40","籃",9,"籎",36,"籵",5,"籾",9], +["bb80","粈粊",6,"粓粔粖粙粚粛粠粡粣粦粧粨粩粫粬粭粯粰粴",4,"粺粻弧虎唬护互沪户花哗华猾滑画划化话槐徊怀淮坏欢环桓还缓换患唤痪豢焕涣宦幻荒慌黄磺蝗簧皇凰惶煌晃幌恍谎灰挥辉徽恢蛔回毁悔慧卉惠晦贿秽会烩汇讳诲绘荤昏婚魂浑混豁活伙火获或惑霍货祸击圾基机畸稽积箕"], +["bc40","粿糀糂糃糄糆糉糋糎",6,"糘糚糛糝糞糡",6,"糩",5,"糰",7,"糹糺糼",13,"紋",5], +["bc80","紑",14,"紡紣紤紥紦紨紩紪紬紭紮細",6,"肌饥迹激讥鸡姬绩缉吉极棘辑籍集及急疾汲即嫉级挤几脊己蓟技冀季伎祭剂悸济寄寂计记既忌际妓继纪嘉枷夹佳家加荚颊贾甲钾假稼价架驾嫁歼监坚尖笺间煎兼肩艰奸缄茧检柬碱硷拣捡简俭剪减荐槛鉴践贱见键箭件"], +["bd40","紷",54,"絯",7], +["bd80","絸",32,"健舰剑饯渐溅涧建僵姜将浆江疆蒋桨奖讲匠酱降蕉椒礁焦胶交郊浇骄娇嚼搅铰矫侥脚狡角饺缴绞剿教酵轿较叫窖揭接皆秸街阶截劫节桔杰捷睫竭洁结解姐戒藉芥界借介疥诫届巾筋斤金今津襟紧锦仅谨进靳晋禁近烬浸"], +["be40","継",12,"綧",6,"綯",42], +["be80","線",32,"尽劲荆兢茎睛晶鲸京惊精粳经井警景颈静境敬镜径痉靖竟竞净炯窘揪究纠玖韭久灸九酒厩救旧臼舅咎就疚鞠拘狙疽居驹菊局咀矩举沮聚拒据巨具距踞锯俱句惧炬剧捐鹃娟倦眷卷绢撅攫抉掘倔爵觉决诀绝均菌钧军君峻"], +["bf40","緻",62], +["bf80","縺縼",4,"繂",4,"繈",21,"俊竣浚郡骏喀咖卡咯开揩楷凯慨刊堪勘坎砍看康慷糠扛抗亢炕考拷烤靠坷苛柯棵磕颗科壳咳可渴克刻客课肯啃垦恳坑吭空恐孔控抠口扣寇枯哭窟苦酷库裤夸垮挎跨胯块筷侩快宽款匡筐狂框矿眶旷况亏盔岿窥葵奎魁傀"], +["c040","繞",35,"纃",23,"纜纝纞"], +["c080","纮纴纻纼绖绤绬绹缊缐缞缷缹缻",6,"罃罆",9,"罒罓馈愧溃坤昆捆困括扩廓阔垃拉喇蜡腊辣啦莱来赖蓝婪栏拦篮阑兰澜谰揽览懒缆烂滥琅榔狼廊郎朗浪捞劳牢老佬姥酪烙涝勒乐雷镭蕾磊累儡垒擂肋类泪棱楞冷厘梨犁黎篱狸离漓理李里鲤礼莉荔吏栗丽厉励砾历利傈例俐"], +["c140","罖罙罛罜罝罞罠罣",4,"罫罬罭罯罰罳罵罶罷罸罺罻罼罽罿羀羂",7,"羋羍羏",4,"羕",4,"羛羜羠羢羣羥羦羨",6,"羱"], +["c180","羳",4,"羺羻羾翀翂翃翄翆翇翈翉翋翍翏",4,"翖翗翙",5,"翢翣痢立粒沥隶力璃哩俩联莲连镰廉怜涟帘敛脸链恋炼练粮凉梁粱良两辆量晾亮谅撩聊僚疗燎寥辽潦了撂镣廖料列裂烈劣猎琳林磷霖临邻鳞淋凛赁吝拎玲菱零龄铃伶羚凌灵陵岭领另令溜琉榴硫馏留刘瘤流柳六龙聋咙笼窿"], +["c240","翤翧翨翪翫翬翭翯翲翴",6,"翽翾翿耂耇耈耉耊耎耏耑耓耚耛耝耞耟耡耣耤耫",5,"耲耴耹耺耼耾聀聁聄聅聇聈聉聎聏聐聑聓聕聖聗"], +["c280","聙聛",13,"聫",5,"聲",11,"隆垄拢陇楼娄搂篓漏陋芦卢颅庐炉掳卤虏鲁麓碌露路赂鹿潞禄录陆戮驴吕铝侣旅履屡缕虑氯律率滤绿峦挛孪滦卵乱掠略抡轮伦仑沦纶论萝螺罗逻锣箩骡裸落洛骆络妈麻玛码蚂马骂嘛吗埋买麦卖迈脉瞒馒蛮满蔓曼慢漫"], +["c340","聾肁肂肅肈肊肍",5,"肔肕肗肙肞肣肦肧肨肬肰肳肵肶肸肹肻胅胇",4,"胏",6,"胘胟胠胢胣胦胮胵胷胹胻胾胿脀脁脃脄脅脇脈脋"], +["c380","脌脕脗脙脛脜脝脟",12,"脭脮脰脳脴脵脷脹",4,"脿谩芒茫盲氓忙莽猫茅锚毛矛铆卯茂冒帽貌贸么玫枚梅酶霉煤没眉媒镁每美昧寐妹媚门闷们萌蒙檬盟锰猛梦孟眯醚靡糜迷谜弥米秘觅泌蜜密幂棉眠绵冕免勉娩缅面苗描瞄藐秒渺庙妙蔑灭民抿皿敏悯闽明螟鸣铭名命谬摸"], +["c440","腀",5,"腇腉腍腎腏腒腖腗腘腛",4,"腡腢腣腤腦腨腪腫腬腯腲腳腵腶腷腸膁膃",4,"膉膋膌膍膎膐膒",5,"膙膚膞",4,"膤膥"], +["c480","膧膩膫",7,"膴",5,"膼膽膾膿臄臅臇臈臉臋臍",6,"摹蘑模膜磨摩魔抹末莫墨默沫漠寞陌谋牟某拇牡亩姆母墓暮幕募慕木目睦牧穆拿哪呐钠那娜纳氖乃奶耐奈南男难囊挠脑恼闹淖呢馁内嫩能妮霓倪泥尼拟你匿腻逆溺蔫拈年碾撵捻念娘酿鸟尿捏聂孽啮镊镍涅您柠狞凝宁"], +["c540","臔",14,"臤臥臦臨臩臫臮",4,"臵",5,"臽臿舃與",4,"舎舏舑舓舕",5,"舝舠舤舥舦舧舩舮舲舺舼舽舿"], +["c580","艀艁艂艃艅艆艈艊艌艍艎艐",7,"艙艛艜艝艞艠",7,"艩拧泞牛扭钮纽脓浓农弄奴努怒女暖虐疟挪懦糯诺哦欧鸥殴藕呕偶沤啪趴爬帕怕琶拍排牌徘湃派攀潘盘磐盼畔判叛乓庞旁耪胖抛咆刨炮袍跑泡呸胚培裴赔陪配佩沛喷盆砰抨烹澎彭蓬棚硼篷膨朋鹏捧碰坯砒霹批披劈琵毗"], +["c640","艪艫艬艭艱艵艶艷艸艻艼芀芁芃芅芆芇芉芌芐芓芔芕芖芚芛芞芠芢芣芧芲芵芶芺芻芼芿苀苂苃苅苆苉苐苖苙苚苝苢苧苨苩苪苬苭苮苰苲苳苵苶苸"], +["c680","苺苼",4,"茊茋茍茐茒茓茖茘茙茝",9,"茩茪茮茰茲茷茻茽啤脾疲皮匹痞僻屁譬篇偏片骗飘漂瓢票撇瞥拼频贫品聘乒坪苹萍平凭瓶评屏坡泼颇婆破魄迫粕剖扑铺仆莆葡菩蒲埔朴圃普浦谱曝瀑期欺栖戚妻七凄漆柒沏其棋奇歧畦崎脐齐旗祈祁骑起岂乞企启契砌器气迄弃汽泣讫掐"], +["c740","茾茿荁荂荄荅荈荊",4,"荓荕",4,"荝荢荰",6,"荹荺荾",6,"莇莈莊莋莌莍莏莐莑莔莕莖莗莙莚莝莟莡",6,"莬莭莮"], +["c780","莯莵莻莾莿菂菃菄菆菈菉菋菍菎菐菑菒菓菕菗菙菚菛菞菢菣菤菦菧菨菫菬菭恰洽牵扦钎铅千迁签仟谦乾黔钱钳前潜遣浅谴堑嵌欠歉枪呛腔羌墙蔷强抢橇锹敲悄桥瞧乔侨巧鞘撬翘峭俏窍切茄且怯窃钦侵亲秦琴勤芹擒禽寝沁青轻氢倾卿清擎晴氰情顷请庆琼穷秋丘邱球求囚酋泅趋区蛆曲躯屈驱渠"], +["c840","菮華菳",4,"菺菻菼菾菿萀萂萅萇萈萉萊萐萒",5,"萙萚萛萞",5,"萩",7,"萲",5,"萹萺萻萾",7,"葇葈葉"], +["c880","葊",6,"葒",4,"葘葝葞葟葠葢葤",4,"葪葮葯葰葲葴葷葹葻葼取娶龋趣去圈颧权醛泉全痊拳犬券劝缺炔瘸却鹊榷确雀裙群然燃冉染瓤壤攘嚷让饶扰绕惹热壬仁人忍韧任认刃妊纫扔仍日戎茸蓉荣融熔溶容绒冗揉柔肉茹蠕儒孺如辱乳汝入褥软阮蕊瑞锐闰润若弱撒洒萨腮鳃塞赛三叁"], +["c940","葽",4,"蒃蒄蒅蒆蒊蒍蒏",7,"蒘蒚蒛蒝蒞蒟蒠蒢",12,"蒰蒱蒳蒵蒶蒷蒻蒼蒾蓀蓂蓃蓅蓆蓇蓈蓋蓌蓎蓏蓒蓔蓕蓗"], +["c980","蓘",4,"蓞蓡蓢蓤蓧",4,"蓭蓮蓯蓱",10,"蓽蓾蔀蔁蔂伞散桑嗓丧搔骚扫嫂瑟色涩森僧莎砂杀刹沙纱傻啥煞筛晒珊苫杉山删煽衫闪陕擅赡膳善汕扇缮墒伤商赏晌上尚裳梢捎稍烧芍勺韶少哨邵绍奢赊蛇舌舍赦摄射慑涉社设砷申呻伸身深娠绅神沈审婶甚肾慎渗声生甥牲升绳"], +["ca40","蔃",8,"蔍蔎蔏蔐蔒蔔蔕蔖蔘蔙蔛蔜蔝蔞蔠蔢",8,"蔭",9,"蔾",4,"蕄蕅蕆蕇蕋",10], +["ca80","蕗蕘蕚蕛蕜蕝蕟",4,"蕥蕦蕧蕩",8,"蕳蕵蕶蕷蕸蕼蕽蕿薀薁省盛剩胜圣师失狮施湿诗尸虱十石拾时什食蚀实识史矢使屎驶始式示士世柿事拭誓逝势是嗜噬适仕侍释饰氏市恃室视试收手首守寿授售受瘦兽蔬枢梳殊抒输叔舒淑疏书赎孰熟薯暑曙署蜀黍鼠属术述树束戍竖墅庶数漱"], +["cb40","薂薃薆薈",6,"薐",10,"薝",6,"薥薦薧薩薫薬薭薱",5,"薸薺",6,"藂",6,"藊",4,"藑藒"], +["cb80","藔藖",5,"藝",6,"藥藦藧藨藪",14,"恕刷耍摔衰甩帅栓拴霜双爽谁水睡税吮瞬顺舜说硕朔烁斯撕嘶思私司丝死肆寺嗣四伺似饲巳松耸怂颂送宋讼诵搜艘擞嗽苏酥俗素速粟僳塑溯宿诉肃酸蒜算虽隋随绥髓碎岁穗遂隧祟孙损笋蓑梭唆缩琐索锁所塌他它她塔"], +["cc40","藹藺藼藽藾蘀",4,"蘆",10,"蘒蘓蘔蘕蘗",15,"蘨蘪",13,"蘹蘺蘻蘽蘾蘿虀"], +["cc80","虁",11,"虒虓處",4,"虛虜虝號虠虡虣",7,"獭挞蹋踏胎苔抬台泰酞太态汰坍摊贪瘫滩坛檀痰潭谭谈坦毯袒碳探叹炭汤塘搪堂棠膛唐糖倘躺淌趟烫掏涛滔绦萄桃逃淘陶讨套特藤腾疼誊梯剔踢锑提题蹄啼体替嚏惕涕剃屉天添填田甜恬舔腆挑条迢眺跳贴铁帖厅听烃"], +["cd40","虭虯虰虲",6,"蚃",6,"蚎",4,"蚔蚖",5,"蚞",4,"蚥蚦蚫蚭蚮蚲蚳蚷蚸蚹蚻",4,"蛁蛂蛃蛅蛈蛌蛍蛒蛓蛕蛖蛗蛚蛜"], +["cd80","蛝蛠蛡蛢蛣蛥蛦蛧蛨蛪蛫蛬蛯蛵蛶蛷蛺蛻蛼蛽蛿蜁蜄蜅蜆蜋蜌蜎蜏蜐蜑蜔蜖汀廷停亭庭挺艇通桐酮瞳同铜彤童桶捅筒统痛偷投头透凸秃突图徒途涂屠土吐兔湍团推颓腿蜕褪退吞屯臀拖托脱鸵陀驮驼椭妥拓唾挖哇蛙洼娃瓦袜歪外豌弯湾玩顽丸烷完碗挽晚皖惋宛婉万腕汪王亡枉网往旺望忘妄威"], +["ce40","蜙蜛蜝蜟蜠蜤蜦蜧蜨蜪蜫蜬蜭蜯蜰蜲蜳蜵蜶蜸蜹蜺蜼蜽蝀",6,"蝊蝋蝍蝏蝐蝑蝒蝔蝕蝖蝘蝚",5,"蝡蝢蝦",7,"蝯蝱蝲蝳蝵"], +["ce80","蝷蝸蝹蝺蝿螀螁螄螆螇螉螊螌螎",4,"螔螕螖螘",6,"螠",4,"巍微危韦违桅围唯惟为潍维苇萎委伟伪尾纬未蔚味畏胃喂魏位渭谓尉慰卫瘟温蚊文闻纹吻稳紊问嗡翁瓮挝蜗涡窝我斡卧握沃巫呜钨乌污诬屋无芜梧吾吴毋武五捂午舞伍侮坞戊雾晤物勿务悟误昔熙析西硒矽晰嘻吸锡牺"], +["cf40","螥螦螧螩螪螮螰螱螲螴螶螷螸螹螻螼螾螿蟁",4,"蟇蟈蟉蟌",4,"蟔",6,"蟜蟝蟞蟟蟡蟢蟣蟤蟦蟧蟨蟩蟫蟬蟭蟯",9], +["cf80","蟺蟻蟼蟽蟿蠀蠁蠂蠄",5,"蠋",7,"蠔蠗蠘蠙蠚蠜",4,"蠣稀息希悉膝夕惜熄烯溪汐犀檄袭席习媳喜铣洗系隙戏细瞎虾匣霞辖暇峡侠狭下厦夏吓掀锨先仙鲜纤咸贤衔舷闲涎弦嫌显险现献县腺馅羡宪陷限线相厢镶香箱襄湘乡翔祥详想响享项巷橡像向象萧硝霄削哮嚣销消宵淆晓"], +["d040","蠤",13,"蠳",5,"蠺蠻蠽蠾蠿衁衂衃衆",5,"衎",5,"衕衖衘衚",6,"衦衧衪衭衯衱衳衴衵衶衸衹衺"], +["d080","衻衼袀袃袆袇袉袊袌袎袏袐袑袓袔袕袗",4,"袝",4,"袣袥",5,"小孝校肖啸笑效楔些歇蝎鞋协挟携邪斜胁谐写械卸蟹懈泄泻谢屑薪芯锌欣辛新忻心信衅星腥猩惺兴刑型形邢行醒幸杏性姓兄凶胸匈汹雄熊休修羞朽嗅锈秀袖绣墟戌需虚嘘须徐许蓄酗叙旭序畜恤絮婿绪续轩喧宣悬旋玄"], +["d140","袬袮袯袰袲",4,"袸袹袺袻袽袾袿裀裃裄裇裈裊裋裌裍裏裐裑裓裖裗裚",4,"裠裡裦裧裩",6,"裲裵裶裷裺裻製裿褀褁褃",5], +["d180","褉褋",4,"褑褔",4,"褜",4,"褢褣褤褦褧褨褩褬褭褮褯褱褲褳褵褷选癣眩绚靴薛学穴雪血勋熏循旬询寻驯巡殉汛训讯逊迅压押鸦鸭呀丫芽牙蚜崖衙涯雅哑亚讶焉咽阉烟淹盐严研蜒岩延言颜阎炎沿奄掩眼衍演艳堰燕厌砚雁唁彦焰宴谚验殃央鸯秧杨扬佯疡羊洋阳氧仰痒养样漾邀腰妖瑶"], +["d240","褸",8,"襂襃襅",24,"襠",5,"襧",19,"襼"], +["d280","襽襾覀覂覄覅覇",26,"摇尧遥窑谣姚咬舀药要耀椰噎耶爷野冶也页掖业叶曳腋夜液一壹医揖铱依伊衣颐夷遗移仪胰疑沂宜姨彝椅蚁倚已乙矣以艺抑易邑屹亿役臆逸肄疫亦裔意毅忆义益溢诣议谊译异翼翌绎茵荫因殷音阴姻吟银淫寅饮尹引隐"], +["d340","覢",30,"觃觍觓觔觕觗觘觙觛觝觟觠觡觢觤觧觨觩觪觬觭觮觰觱觲觴",6], +["d380","觻",4,"訁",5,"計",21,"印英樱婴鹰应缨莹萤营荧蝇迎赢盈影颖硬映哟拥佣臃痈庸雍踊蛹咏泳涌永恿勇用幽优悠忧尤由邮铀犹油游酉有友右佑釉诱又幼迂淤于盂榆虞愚舆余俞逾鱼愉渝渔隅予娱雨与屿禹宇语羽玉域芋郁吁遇喻峪御愈欲狱育誉"], +["d440","訞",31,"訿",8,"詉",21], +["d480","詟",25,"詺",6,"浴寓裕预豫驭鸳渊冤元垣袁原援辕园员圆猿源缘远苑愿怨院曰约越跃钥岳粤月悦阅耘云郧匀陨允运蕴酝晕韵孕匝砸杂栽哉灾宰载再在咱攒暂赞赃脏葬遭糟凿藻枣早澡蚤躁噪造皂灶燥责择则泽贼怎增憎曾赠扎喳渣札轧"], +["d540","誁",7,"誋",7,"誔",46], +["d580","諃",32,"铡闸眨栅榨咋乍炸诈摘斋宅窄债寨瞻毡詹粘沾盏斩辗崭展蘸栈占战站湛绽樟章彰漳张掌涨杖丈帐账仗胀瘴障招昭找沼赵照罩兆肇召遮折哲蛰辙者锗蔗这浙珍斟真甄砧臻贞针侦枕疹诊震振镇阵蒸挣睁征狰争怔整拯正政"], +["d640","諤",34,"謈",27], +["d680","謤謥謧",30,"帧症郑证芝枝支吱蜘知肢脂汁之织职直植殖执值侄址指止趾只旨纸志挚掷至致置帜峙制智秩稚质炙痔滞治窒中盅忠钟衷终种肿重仲众舟周州洲诌粥轴肘帚咒皱宙昼骤珠株蛛朱猪诸诛逐竹烛煮拄瞩嘱主著柱助蛀贮铸筑"], +["d740","譆",31,"譧",4,"譭",25], +["d780","讇",24,"讬讱讻诇诐诪谉谞住注祝驻抓爪拽专砖转撰赚篆桩庄装妆撞壮状椎锥追赘坠缀谆准捉拙卓桌琢茁酌啄着灼浊兹咨资姿滋淄孜紫仔籽滓子自渍字鬃棕踪宗综总纵邹走奏揍租足卒族祖诅阻组钻纂嘴醉最罪尊遵昨左佐柞做作坐座"], +["d840","谸",8,"豂豃豄豅豈豊豋豍",7,"豖豗豘豙豛",5,"豣",6,"豬",6,"豴豵豶豷豻",6,"貃貄貆貇"], +["d880","貈貋貍",6,"貕貖貗貙",20,"亍丌兀丐廿卅丕亘丞鬲孬噩丨禺丿匕乇夭爻卮氐囟胤馗毓睾鼗丶亟鼐乜乩亓芈孛啬嘏仄厍厝厣厥厮靥赝匚叵匦匮匾赜卦卣刂刈刎刭刳刿剀剌剞剡剜蒯剽劂劁劐劓冂罔亻仃仉仂仨仡仫仞伛仳伢佤仵伥伧伉伫佞佧攸佚佝"], +["d940","貮",62], +["d980","賭",32,"佟佗伲伽佶佴侑侉侃侏佾佻侪佼侬侔俦俨俪俅俚俣俜俑俟俸倩偌俳倬倏倮倭俾倜倌倥倨偾偃偕偈偎偬偻傥傧傩傺僖儆僭僬僦僮儇儋仝氽佘佥俎龠汆籴兮巽黉馘冁夔勹匍訇匐凫夙兕亠兖亳衮袤亵脔裒禀嬴蠃羸冫冱冽冼"], +["da40","贎",14,"贠赑赒赗赟赥赨赩赪赬赮赯赱赲赸",8,"趂趃趆趇趈趉趌",4,"趒趓趕",9,"趠趡"], +["da80","趢趤",12,"趲趶趷趹趻趽跀跁跂跅跇跈跉跊跍跐跒跓跔凇冖冢冥讠讦讧讪讴讵讷诂诃诋诏诎诒诓诔诖诘诙诜诟诠诤诨诩诮诰诳诶诹诼诿谀谂谄谇谌谏谑谒谔谕谖谙谛谘谝谟谠谡谥谧谪谫谮谯谲谳谵谶卩卺阝阢阡阱阪阽阼陂陉陔陟陧陬陲陴隈隍隗隰邗邛邝邙邬邡邴邳邶邺"], +["db40","跕跘跙跜跠跡跢跥跦跧跩跭跮跰跱跲跴跶跼跾",6,"踆踇踈踋踍踎踐踑踒踓踕",7,"踠踡踤",4,"踫踭踰踲踳踴踶踷踸踻踼踾"], +["db80","踿蹃蹅蹆蹌",4,"蹓",5,"蹚",11,"蹧蹨蹪蹫蹮蹱邸邰郏郅邾郐郄郇郓郦郢郜郗郛郫郯郾鄄鄢鄞鄣鄱鄯鄹酃酆刍奂劢劬劭劾哿勐勖勰叟燮矍廴凵凼鬯厶弁畚巯坌垩垡塾墼壅壑圩圬圪圳圹圮圯坜圻坂坩垅坫垆坼坻坨坭坶坳垭垤垌垲埏垧垴垓垠埕埘埚埙埒垸埴埯埸埤埝"], +["dc40","蹳蹵蹷",4,"蹽蹾躀躂躃躄躆躈",6,"躑躒躓躕",6,"躝躟",11,"躭躮躰躱躳",6,"躻",7], +["dc80","軃",10,"軏",21,"堋堍埽埭堀堞堙塄堠塥塬墁墉墚墀馨鼙懿艹艽艿芏芊芨芄芎芑芗芙芫芸芾芰苈苊苣芘芷芮苋苌苁芩芴芡芪芟苄苎芤苡茉苷苤茏茇苜苴苒苘茌苻苓茑茚茆茔茕苠苕茜荑荛荜茈莒茼茴茱莛荞茯荏荇荃荟荀茗荠茭茺茳荦荥"], +["dd40","軥",62], +["dd80","輤",32,"荨茛荩荬荪荭荮莰荸莳莴莠莪莓莜莅荼莶莩荽莸荻莘莞莨莺莼菁萁菥菘堇萘萋菝菽菖萜萸萑萆菔菟萏萃菸菹菪菅菀萦菰菡葜葑葚葙葳蒇蒈葺蒉葸萼葆葩葶蒌蒎萱葭蓁蓍蓐蓦蒽蓓蓊蒿蒺蓠蒡蒹蒴蒗蓥蓣蔌甍蔸蓰蔹蔟蔺"], +["de40","轅",32,"轪辀辌辒辝辠辡辢辤辥辦辧辪辬辭辮辯農辳辴辵辷辸辺辻込辿迀迃迆"], +["de80","迉",4,"迏迒迖迗迚迠迡迣迧迬迯迱迲迴迵迶迺迻迼迾迿逇逈逌逎逓逕逘蕖蔻蓿蓼蕙蕈蕨蕤蕞蕺瞢蕃蕲蕻薤薨薇薏蕹薮薜薅薹薷薰藓藁藜藿蘧蘅蘩蘖蘼廾弈夼奁耷奕奚奘匏尢尥尬尴扌扪抟抻拊拚拗拮挢拶挹捋捃掭揶捱捺掎掴捭掬掊捩掮掼揲揸揠揿揄揞揎摒揆掾摅摁搋搛搠搌搦搡摞撄摭撖"], +["df40","這逜連逤逥逧",5,"逰",4,"逷逹逺逽逿遀遃遅遆遈",4,"過達違遖遙遚遜",5,"遤遦遧適遪遫遬遯",4,"遶",6,"遾邁"], +["df80","還邅邆邇邉邊邌",4,"邒邔邖邘邚邜邞邟邠邤邥邧邨邩邫邭邲邷邼邽邿郀摺撷撸撙撺擀擐擗擤擢攉攥攮弋忒甙弑卟叱叽叩叨叻吒吖吆呋呒呓呔呖呃吡呗呙吣吲咂咔呷呱呤咚咛咄呶呦咝哐咭哂咴哒咧咦哓哔呲咣哕咻咿哌哙哚哜咩咪咤哝哏哞唛哧唠哽唔哳唢唣唏唑唧唪啧喏喵啉啭啁啕唿啐唼"], +["e040","郂郃郆郈郉郋郌郍郒郔郕郖郘郙郚郞郟郠郣郤郥郩郪郬郮郰郱郲郳郵郶郷郹郺郻郼郿鄀鄁鄃鄅",19,"鄚鄛鄜"], +["e080","鄝鄟鄠鄡鄤",10,"鄰鄲",6,"鄺",8,"酄唷啖啵啶啷唳唰啜喋嗒喃喱喹喈喁喟啾嗖喑啻嗟喽喾喔喙嗪嗷嗉嘟嗑嗫嗬嗔嗦嗝嗄嗯嗥嗲嗳嗌嗍嗨嗵嗤辔嘞嘈嘌嘁嘤嘣嗾嘀嘧嘭噘嘹噗嘬噍噢噙噜噌噔嚆噤噱噫噻噼嚅嚓嚯囔囗囝囡囵囫囹囿圄圊圉圜帏帙帔帑帱帻帼"], +["e140","酅酇酈酑酓酔酕酖酘酙酛酜酟酠酦酧酨酫酭酳酺酻酼醀",4,"醆醈醊醎醏醓",6,"醜",5,"醤",5,"醫醬醰醱醲醳醶醷醸醹醻"], +["e180","醼",10,"釈釋釐釒",9,"針",8,"帷幄幔幛幞幡岌屺岍岐岖岈岘岙岑岚岜岵岢岽岬岫岱岣峁岷峄峒峤峋峥崂崃崧崦崮崤崞崆崛嵘崾崴崽嵬嵛嵯嵝嵫嵋嵊嵩嵴嶂嶙嶝豳嶷巅彳彷徂徇徉後徕徙徜徨徭徵徼衢彡犭犰犴犷犸狃狁狎狍狒狨狯狩狲狴狷猁狳猃狺"], +["e240","釦",62], +["e280","鈥",32,"狻猗猓猡猊猞猝猕猢猹猥猬猸猱獐獍獗獠獬獯獾舛夥飧夤夂饣饧",5,"饴饷饽馀馄馇馊馍馐馑馓馔馕庀庑庋庖庥庠庹庵庾庳赓廒廑廛廨廪膺忄忉忖忏怃忮怄忡忤忾怅怆忪忭忸怙怵怦怛怏怍怩怫怊怿怡恸恹恻恺恂"], +["e340","鉆",45,"鉵",16], +["e380","銆",7,"銏",24,"恪恽悖悚悭悝悃悒悌悛惬悻悱惝惘惆惚悴愠愦愕愣惴愀愎愫慊慵憬憔憧憷懔懵忝隳闩闫闱闳闵闶闼闾阃阄阆阈阊阋阌阍阏阒阕阖阗阙阚丬爿戕氵汔汜汊沣沅沐沔沌汨汩汴汶沆沩泐泔沭泷泸泱泗沲泠泖泺泫泮沱泓泯泾"], +["e440","銨",5,"銯",24,"鋉",31], +["e480","鋩",32,"洹洧洌浃浈洇洄洙洎洫浍洮洵洚浏浒浔洳涑浯涞涠浞涓涔浜浠浼浣渚淇淅淞渎涿淠渑淦淝淙渖涫渌涮渫湮湎湫溲湟溆湓湔渲渥湄滟溱溘滠漭滢溥溧溽溻溷滗溴滏溏滂溟潢潆潇漤漕滹漯漶潋潴漪漉漩澉澍澌潸潲潼潺濑"], +["e540","錊",51,"錿",10], +["e580","鍊",31,"鍫濉澧澹澶濂濡濮濞濠濯瀚瀣瀛瀹瀵灏灞宀宄宕宓宥宸甯骞搴寤寮褰寰蹇謇辶迓迕迥迮迤迩迦迳迨逅逄逋逦逑逍逖逡逵逶逭逯遄遑遒遐遨遘遢遛暹遴遽邂邈邃邋彐彗彖彘尻咫屐屙孱屣屦羼弪弩弭艴弼鬻屮妁妃妍妩妪妣"], +["e640","鍬",34,"鎐",27], +["e680","鎬",29,"鏋鏌鏍妗姊妫妞妤姒妲妯姗妾娅娆姝娈姣姘姹娌娉娲娴娑娣娓婀婧婊婕娼婢婵胬媪媛婷婺媾嫫媲嫒嫔媸嫠嫣嫱嫖嫦嫘嫜嬉嬗嬖嬲嬷孀尕尜孚孥孳孑孓孢驵驷驸驺驿驽骀骁骅骈骊骐骒骓骖骘骛骜骝骟骠骢骣骥骧纟纡纣纥纨纩"], +["e740","鏎",7,"鏗",54], +["e780","鐎",32,"纭纰纾绀绁绂绉绋绌绐绔绗绛绠绡绨绫绮绯绱绲缍绶绺绻绾缁缂缃缇缈缋缌缏缑缒缗缙缜缛缟缡",6,"缪缫缬缭缯",4,"缵幺畿巛甾邕玎玑玮玢玟珏珂珑玷玳珀珉珈珥珙顼琊珩珧珞玺珲琏琪瑛琦琥琨琰琮琬"], +["e840","鐯",14,"鐿",43,"鑬鑭鑮鑯"], +["e880","鑰",20,"钑钖钘铇铏铓铔铚铦铻锜锠琛琚瑁瑜瑗瑕瑙瑷瑭瑾璜璎璀璁璇璋璞璨璩璐璧瓒璺韪韫韬杌杓杞杈杩枥枇杪杳枘枧杵枨枞枭枋杷杼柰栉柘栊柩枰栌柙枵柚枳柝栀柃枸柢栎柁柽栲栳桠桡桎桢桄桤梃栝桕桦桁桧桀栾桊桉栩梵梏桴桷梓桫棂楮棼椟椠棹"], +["e940","锧锳锽镃镈镋镕镚镠镮镴镵長",7,"門",42], +["e980","閫",32,"椤棰椋椁楗棣椐楱椹楠楂楝榄楫榀榘楸椴槌榇榈槎榉楦楣楹榛榧榻榫榭槔榱槁槊槟榕槠榍槿樯槭樗樘橥槲橄樾檠橐橛樵檎橹樽樨橘橼檑檐檩檗檫猷獒殁殂殇殄殒殓殍殚殛殡殪轫轭轱轲轳轵轶轸轷轹轺轼轾辁辂辄辇辋"], +["ea40","闌",27,"闬闿阇阓阘阛阞阠阣",6,"阫阬阭阯阰阷阸阹阺阾陁陃陊陎陏陑陒陓陖陗"], +["ea80","陘陙陚陜陝陞陠陣陥陦陫陭",4,"陳陸",12,"隇隉隊辍辎辏辘辚軎戋戗戛戟戢戡戥戤戬臧瓯瓴瓿甏甑甓攴旮旯旰昊昙杲昃昕昀炅曷昝昴昱昶昵耆晟晔晁晏晖晡晗晷暄暌暧暝暾曛曜曦曩贲贳贶贻贽赀赅赆赈赉赇赍赕赙觇觊觋觌觎觏觐觑牮犟牝牦牯牾牿犄犋犍犏犒挈挲掰"], +["eb40","隌階隑隒隓隕隖隚際隝",9,"隨",7,"隱隲隴隵隷隸隺隻隿雂雃雈雊雋雐雑雓雔雖",9,"雡",6,"雫"], +["eb80","雬雭雮雰雱雲雴雵雸雺電雼雽雿霂霃霅霊霋霌霐霑霒霔霕霗",4,"霝霟霠搿擘耄毪毳毽毵毹氅氇氆氍氕氘氙氚氡氩氤氪氲攵敕敫牍牒牖爰虢刖肟肜肓肼朊肽肱肫肭肴肷胧胨胩胪胛胂胄胙胍胗朐胝胫胱胴胭脍脎胲胼朕脒豚脶脞脬脘脲腈腌腓腴腙腚腱腠腩腼腽腭腧塍媵膈膂膑滕膣膪臌朦臊膻"], +["ec40","霡",8,"霫霬霮霯霱霳",4,"霺霻霼霽霿",18,"靔靕靗靘靚靜靝靟靣靤靦靧靨靪",7], +["ec80","靲靵靷",4,"靽",7,"鞆",4,"鞌鞎鞏鞐鞓鞕鞖鞗鞙",4,"臁膦欤欷欹歃歆歙飑飒飓飕飙飚殳彀毂觳斐齑斓於旆旄旃旌旎旒旖炀炜炖炝炻烀炷炫炱烨烊焐焓焖焯焱煳煜煨煅煲煊煸煺熘熳熵熨熠燠燔燧燹爝爨灬焘煦熹戾戽扃扈扉礻祀祆祉祛祜祓祚祢祗祠祯祧祺禅禊禚禧禳忑忐"], +["ed40","鞞鞟鞡鞢鞤",6,"鞬鞮鞰鞱鞳鞵",46], +["ed80","韤韥韨韮",4,"韴韷",23,"怼恝恚恧恁恙恣悫愆愍慝憩憝懋懑戆肀聿沓泶淼矶矸砀砉砗砘砑斫砭砜砝砹砺砻砟砼砥砬砣砩硎硭硖硗砦硐硇硌硪碛碓碚碇碜碡碣碲碹碥磔磙磉磬磲礅磴礓礤礞礴龛黹黻黼盱眄眍盹眇眈眚眢眙眭眦眵眸睐睑睇睃睚睨"], +["ee40","頏",62], +["ee80","顎",32,"睢睥睿瞍睽瞀瞌瞑瞟瞠瞰瞵瞽町畀畎畋畈畛畲畹疃罘罡罟詈罨罴罱罹羁罾盍盥蠲钅钆钇钋钊钌钍钏钐钔钗钕钚钛钜钣钤钫钪钭钬钯钰钲钴钶",4,"钼钽钿铄铈",6,"铐铑铒铕铖铗铙铘铛铞铟铠铢铤铥铧铨铪"], +["ef40","顯",5,"颋颎颒颕颙颣風",37,"飏飐飔飖飗飛飜飝飠",4], +["ef80","飥飦飩",30,"铩铫铮铯铳铴铵铷铹铼铽铿锃锂锆锇锉锊锍锎锏锒",4,"锘锛锝锞锟锢锪锫锩锬锱锲锴锶锷锸锼锾锿镂锵镄镅镆镉镌镎镏镒镓镔镖镗镘镙镛镞镟镝镡镢镤",8,"镯镱镲镳锺矧矬雉秕秭秣秫稆嵇稃稂稞稔"], +["f040","餈",4,"餎餏餑",28,"餯",26], +["f080","饊",9,"饖",12,"饤饦饳饸饹饻饾馂馃馉稹稷穑黏馥穰皈皎皓皙皤瓞瓠甬鸠鸢鸨",4,"鸲鸱鸶鸸鸷鸹鸺鸾鹁鹂鹄鹆鹇鹈鹉鹋鹌鹎鹑鹕鹗鹚鹛鹜鹞鹣鹦",6,"鹱鹭鹳疒疔疖疠疝疬疣疳疴疸痄疱疰痃痂痖痍痣痨痦痤痫痧瘃痱痼痿瘐瘀瘅瘌瘗瘊瘥瘘瘕瘙"], +["f140","馌馎馚",10,"馦馧馩",47], +["f180","駙",32,"瘛瘼瘢瘠癀瘭瘰瘿瘵癃瘾瘳癍癞癔癜癖癫癯翊竦穸穹窀窆窈窕窦窠窬窨窭窳衤衩衲衽衿袂袢裆袷袼裉裢裎裣裥裱褚裼裨裾裰褡褙褓褛褊褴褫褶襁襦襻疋胥皲皴矜耒耔耖耜耠耢耥耦耧耩耨耱耋耵聃聆聍聒聩聱覃顸颀颃"], +["f240","駺",62], +["f280","騹",32,"颉颌颍颏颔颚颛颞颟颡颢颥颦虍虔虬虮虿虺虼虻蚨蚍蚋蚬蚝蚧蚣蚪蚓蚩蚶蛄蚵蛎蚰蚺蚱蚯蛉蛏蚴蛩蛱蛲蛭蛳蛐蜓蛞蛴蛟蛘蛑蜃蜇蛸蜈蜊蜍蜉蜣蜻蜞蜥蜮蜚蜾蝈蜴蜱蜩蜷蜿螂蜢蝽蝾蝻蝠蝰蝌蝮螋蝓蝣蝼蝤蝙蝥螓螯螨蟒"], +["f340","驚",17,"驲骃骉骍骎骔骕骙骦骩",6,"骲骳骴骵骹骻骽骾骿髃髄髆",4,"髍髎髏髐髒體髕髖髗髙髚髛髜"], +["f380","髝髞髠髢髣髤髥髧髨髩髪髬髮髰",8,"髺髼",6,"鬄鬅鬆蟆螈螅螭螗螃螫蟥螬螵螳蟋蟓螽蟑蟀蟊蟛蟪蟠蟮蠖蠓蟾蠊蠛蠡蠹蠼缶罂罄罅舐竺竽笈笃笄笕笊笫笏筇笸笪笙笮笱笠笥笤笳笾笞筘筚筅筵筌筝筠筮筻筢筲筱箐箦箧箸箬箝箨箅箪箜箢箫箴篑篁篌篝篚篥篦篪簌篾篼簏簖簋"], +["f440","鬇鬉",5,"鬐鬑鬒鬔",10,"鬠鬡鬢鬤",10,"鬰鬱鬳",7,"鬽鬾鬿魀魆魊魋魌魎魐魒魓魕",5], +["f480","魛",32,"簟簪簦簸籁籀臾舁舂舄臬衄舡舢舣舭舯舨舫舸舻舳舴舾艄艉艋艏艚艟艨衾袅袈裘裟襞羝羟羧羯羰羲籼敉粑粝粜粞粢粲粼粽糁糇糌糍糈糅糗糨艮暨羿翎翕翥翡翦翩翮翳糸絷綦綮繇纛麸麴赳趄趔趑趱赧赭豇豉酊酐酎酏酤"], +["f540","魼",62], +["f580","鮻",32,"酢酡酰酩酯酽酾酲酴酹醌醅醐醍醑醢醣醪醭醮醯醵醴醺豕鹾趸跫踅蹙蹩趵趿趼趺跄跖跗跚跞跎跏跛跆跬跷跸跣跹跻跤踉跽踔踝踟踬踮踣踯踺蹀踹踵踽踱蹉蹁蹂蹑蹒蹊蹰蹶蹼蹯蹴躅躏躔躐躜躞豸貂貊貅貘貔斛觖觞觚觜"], +["f640","鯜",62], +["f680","鰛",32,"觥觫觯訾謦靓雩雳雯霆霁霈霏霎霪霭霰霾龀龃龅",5,"龌黾鼋鼍隹隼隽雎雒瞿雠銎銮鋈錾鍪鏊鎏鐾鑫鱿鲂鲅鲆鲇鲈稣鲋鲎鲐鲑鲒鲔鲕鲚鲛鲞",5,"鲥",4,"鲫鲭鲮鲰",7,"鲺鲻鲼鲽鳄鳅鳆鳇鳊鳋"], +["f740","鰼",62], +["f780","鱻鱽鱾鲀鲃鲄鲉鲊鲌鲏鲓鲖鲗鲘鲙鲝鲪鲬鲯鲹鲾",4,"鳈鳉鳑鳒鳚鳛鳠鳡鳌",4,"鳓鳔鳕鳗鳘鳙鳜鳝鳟鳢靼鞅鞑鞒鞔鞯鞫鞣鞲鞴骱骰骷鹘骶骺骼髁髀髅髂髋髌髑魅魃魇魉魈魍魑飨餍餮饕饔髟髡髦髯髫髻髭髹鬈鬏鬓鬟鬣麽麾縻麂麇麈麋麒鏖麝麟黛黜黝黠黟黢黩黧黥黪黯鼢鼬鼯鼹鼷鼽鼾齄"], +["f840","鳣",62], +["f880","鴢",32], +["f940","鵃",62], +["f980","鶂",32], +["fa40","鶣",62], +["fa80","鷢",32], +["fb40","鸃",27,"鸤鸧鸮鸰鸴鸻鸼鹀鹍鹐鹒鹓鹔鹖鹙鹝鹟鹠鹡鹢鹥鹮鹯鹲鹴",9,"麀"], +["fb80","麁麃麄麅麆麉麊麌",5,"麔",8,"麞麠",5,"麧麨麩麪"], +["fc40","麫",8,"麵麶麷麹麺麼麿",4,"黅黆黇黈黊黋黌黐黒黓黕黖黗黙黚點黡黣黤黦黨黫黬黭黮黰",8,"黺黽黿",6], +["fc80","鼆",4,"鼌鼏鼑鼒鼔鼕鼖鼘鼚",5,"鼡鼣",8,"鼭鼮鼰鼱"], +["fd40","鼲",4,"鼸鼺鼼鼿",4,"齅",10,"齒",38], +["fd80","齹",5,"龁龂龍",11,"龜龝龞龡",4,"郎凉秊裏隣"], +["fe40","兀嗀﨎﨏﨑﨓﨔礼﨟蘒﨡﨣﨤﨧﨨﨩"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp949.json b/node_modules/iconv-lite/encodings/tables/cp949.json new file mode 100644 index 00000000..2022a007 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp949.json @@ -0,0 +1,273 @@ +[ +["0","\u0000",127], +["8141","갂갃갅갆갋",4,"갘갞갟갡갢갣갥",6,"갮갲갳갴"], +["8161","갵갶갷갺갻갽갾갿걁",9,"걌걎",5,"걕"], +["8181","걖걗걙걚걛걝",18,"걲걳걵걶걹걻",4,"겂겇겈겍겎겏겑겒겓겕",6,"겞겢",5,"겫겭겮겱",6,"겺겾겿곀곂곃곅곆곇곉곊곋곍",7,"곖곘",7,"곢곣곥곦곩곫곭곮곲곴곷",4,"곾곿괁괂괃괅괇",4,"괎괐괒괓"], +["8241","괔괕괖괗괙괚괛괝괞괟괡",7,"괪괫괮",5], +["8261","괶괷괹괺괻괽",6,"굆굈굊",5,"굑굒굓굕굖굗"], +["8281","굙",7,"굢굤",7,"굮굯굱굲굷굸굹굺굾궀궃",4,"궊궋궍궎궏궑",10,"궞",5,"궥",17,"궸",7,"귂귃귅귆귇귉",6,"귒귔",7,"귝귞귟귡귢귣귥",18], +["8341","귺귻귽귾긂",5,"긊긌긎",5,"긕",7], +["8361","긝",18,"긲긳긵긶긹긻긼"], +["8381","긽긾긿깂깄깇깈깉깋깏깑깒깓깕깗",4,"깞깢깣깤깦깧깪깫깭깮깯깱",6,"깺깾",5,"꺆",5,"꺍",46,"꺿껁껂껃껅",6,"껎껒",5,"껚껛껝",8], +["8441","껦껧껩껪껬껮",5,"껵껶껷껹껺껻껽",8], +["8461","꼆꼉꼊꼋꼌꼎꼏꼑",18], +["8481","꼤",7,"꼮꼯꼱꼳꼵",6,"꼾꽀꽄꽅꽆꽇꽊",5,"꽑",10,"꽞",5,"꽦",18,"꽺",5,"꾁꾂꾃꾅꾆꾇꾉",6,"꾒꾓꾔꾖",5,"꾝",26,"꾺꾻꾽꾾"], +["8541","꾿꿁",5,"꿊꿌꿏",4,"꿕",6,"꿝",4], +["8561","꿢",5,"꿪",5,"꿲꿳꿵꿶꿷꿹",6,"뀂뀃"], +["8581","뀅",6,"뀍뀎뀏뀑뀒뀓뀕",6,"뀞",9,"뀩",26,"끆끇끉끋끍끏끐끑끒끖끘끚끛끜끞",29,"끾끿낁낂낃낅",6,"낎낐낒",5,"낛낝낞낣낤"], +["8641","낥낦낧낪낰낲낶낷낹낺낻낽",6,"냆냊",5,"냒"], +["8661","냓냕냖냗냙",6,"냡냢냣냤냦",10], +["8681","냱",22,"넊넍넎넏넑넔넕넖넗넚넞",4,"넦넧넩넪넫넭",6,"넶넺",5,"녂녃녅녆녇녉",6,"녒녓녖녗녙녚녛녝녞녟녡",22,"녺녻녽녾녿놁놃",4,"놊놌놎놏놐놑놕놖놗놙놚놛놝"], +["8741","놞",9,"놩",15], +["8761","놹",18,"뇍뇎뇏뇑뇒뇓뇕"], +["8781","뇖",5,"뇞뇠",7,"뇪뇫뇭뇮뇯뇱",7,"뇺뇼뇾",5,"눆눇눉눊눍",6,"눖눘눚",5,"눡",18,"눵",6,"눽",26,"뉙뉚뉛뉝뉞뉟뉡",6,"뉪",4], +["8841","뉯",4,"뉶",5,"뉽",6,"늆늇늈늊",4], +["8861","늏늒늓늕늖늗늛",4,"늢늤늧늨늩늫늭늮늯늱늲늳늵늶늷"], +["8881","늸",15,"닊닋닍닎닏닑닓",4,"닚닜닞닟닠닡닣닧닩닪닰닱닲닶닼닽닾댂댃댅댆댇댉",6,"댒댖",5,"댝",54,"덗덙덚덝덠덡덢덣"], +["8941","덦덨덪덬덭덯덲덳덵덶덷덹",6,"뎂뎆",5,"뎍"], +["8961","뎎뎏뎑뎒뎓뎕",10,"뎢",5,"뎩뎪뎫뎭"], +["8981","뎮",21,"돆돇돉돊돍돏돑돒돓돖돘돚돜돞돟돡돢돣돥돦돧돩",18,"돽",18,"됑",6,"됙됚됛됝됞됟됡",6,"됪됬",7,"됵",15], +["8a41","둅",10,"둒둓둕둖둗둙",6,"둢둤둦"], +["8a61","둧",4,"둭",18,"뒁뒂"], +["8a81","뒃",4,"뒉",19,"뒞",5,"뒥뒦뒧뒩뒪뒫뒭",7,"뒶뒸뒺",5,"듁듂듃듅듆듇듉",6,"듑듒듓듔듖",5,"듞듟듡듢듥듧",4,"듮듰듲",5,"듹",26,"딖딗딙딚딝"], +["8b41","딞",5,"딦딫",4,"딲딳딵딶딷딹",6,"땂땆"], +["8b61","땇땈땉땊땎땏땑땒땓땕",6,"땞땢",8], +["8b81","땫",52,"떢떣떥떦떧떩떬떭떮떯떲떶",4,"떾떿뗁뗂뗃뗅",6,"뗎뗒",5,"뗙",18,"뗭",18], +["8c41","똀",15,"똒똓똕똖똗똙",4], +["8c61","똞",6,"똦",5,"똭",6,"똵",5], +["8c81","똻",12,"뙉",26,"뙥뙦뙧뙩",50,"뚞뚟뚡뚢뚣뚥",5,"뚭뚮뚯뚰뚲",16], +["8d41","뛃",16,"뛕",8], +["8d61","뛞",17,"뛱뛲뛳뛵뛶뛷뛹뛺"], +["8d81","뛻",4,"뜂뜃뜄뜆",33,"뜪뜫뜭뜮뜱",6,"뜺뜼",7,"띅띆띇띉띊띋띍",6,"띖",9,"띡띢띣띥띦띧띩",6,"띲띴띶",5,"띾띿랁랂랃랅",6,"랎랓랔랕랚랛랝랞"], +["8e41","랟랡",6,"랪랮",5,"랶랷랹",8], +["8e61","럂",4,"럈럊",19], +["8e81","럞",13,"럮럯럱럲럳럵",6,"럾렂",4,"렊렋렍렎렏렑",6,"렚렜렞",5,"렦렧렩렪렫렭",6,"렶렺",5,"롁롂롃롅",11,"롒롔",7,"롞롟롡롢롣롥",6,"롮롰롲",5,"롹롺롻롽",7], +["8f41","뢅",7,"뢎",17], +["8f61","뢠",7,"뢩",6,"뢱뢲뢳뢵뢶뢷뢹",4], +["8f81","뢾뢿룂룄룆",5,"룍룎룏룑룒룓룕",7,"룞룠룢",5,"룪룫룭룮룯룱",6,"룺룼룾",5,"뤅",18,"뤙",6,"뤡",26,"뤾뤿륁륂륃륅",6,"륍륎륐륒",5], +["9041","륚륛륝륞륟륡",6,"륪륬륮",5,"륶륷륹륺륻륽"], +["9061","륾",5,"릆릈릋릌릏",15], +["9081","릟",12,"릮릯릱릲릳릵",6,"릾맀맂",5,"맊맋맍맓",4,"맚맜맟맠맢맦맧맩맪맫맭",6,"맶맻",4,"먂",5,"먉",11,"먖",33,"먺먻먽먾먿멁멃멄멅멆"], +["9141","멇멊멌멏멐멑멒멖멗멙멚멛멝",6,"멦멪",5], +["9161","멲멳멵멶멷멹",9,"몆몈몉몊몋몍",5], +["9181","몓",20,"몪몭몮몯몱몳",4,"몺몼몾",5,"뫅뫆뫇뫉",14,"뫚",33,"뫽뫾뫿묁묂묃묅",7,"묎묐묒",5,"묙묚묛묝묞묟묡",6], +["9241","묨묪묬",7,"묷묹묺묿",4,"뭆뭈뭊뭋뭌뭎뭑뭒"], +["9261","뭓뭕뭖뭗뭙",7,"뭢뭤",7,"뭭",4], +["9281","뭲",21,"뮉뮊뮋뮍뮎뮏뮑",18,"뮥뮦뮧뮩뮪뮫뮭",6,"뮵뮶뮸",7,"믁믂믃믅믆믇믉",6,"믑믒믔",35,"믺믻믽믾밁"], +["9341","밃",4,"밊밎밐밒밓밙밚밠밡밢밣밦밨밪밫밬밮밯밲밳밵"], +["9361","밶밷밹",6,"뱂뱆뱇뱈뱊뱋뱎뱏뱑",8], +["9381","뱚뱛뱜뱞",37,"벆벇벉벊벍벏",4,"벖벘벛",4,"벢벣벥벦벩",6,"벲벶",5,"벾벿볁볂볃볅",7,"볎볒볓볔볖볗볙볚볛볝",22,"볷볹볺볻볽"], +["9441","볾",5,"봆봈봊",5,"봑봒봓봕",8], +["9461","봞",5,"봥",6,"봭",12], +["9481","봺",5,"뵁",6,"뵊뵋뵍뵎뵏뵑",6,"뵚",9,"뵥뵦뵧뵩",22,"붂붃붅붆붋",4,"붒붔붖붗붘붛붝",6,"붥",10,"붱",6,"붹",24], +["9541","뷒뷓뷖뷗뷙뷚뷛뷝",11,"뷪",5,"뷱"], +["9561","뷲뷳뷵뷶뷷뷹",6,"븁븂븄븆",5,"븎븏븑븒븓"], +["9581","븕",6,"븞븠",35,"빆빇빉빊빋빍빏",4,"빖빘빜빝빞빟빢빣빥빦빧빩빫",4,"빲빶",4,"빾빿뺁뺂뺃뺅",6,"뺎뺒",5,"뺚",13,"뺩",14], +["9641","뺸",23,"뻒뻓"], +["9661","뻕뻖뻙",6,"뻡뻢뻦",5,"뻭",8], +["9681","뻶",10,"뼂",5,"뼊",13,"뼚뼞",33,"뽂뽃뽅뽆뽇뽉",6,"뽒뽓뽔뽖",44], +["9741","뾃",16,"뾕",8], +["9761","뾞",17,"뾱",7], +["9781","뾹",11,"뿆",5,"뿎뿏뿑뿒뿓뿕",6,"뿝뿞뿠뿢",89,"쀽쀾쀿"], +["9841","쁀",16,"쁒",5,"쁙쁚쁛"], +["9861","쁝쁞쁟쁡",6,"쁪",15], +["9881","쁺",21,"삒삓삕삖삗삙",6,"삢삤삦",5,"삮삱삲삷",4,"삾샂샃샄샆샇샊샋샍샎샏샑",6,"샚샞",5,"샦샧샩샪샫샭",6,"샶샸샺",5,"섁섂섃섅섆섇섉",6,"섑섒섓섔섖",5,"섡섢섥섨섩섪섫섮"], +["9941","섲섳섴섵섷섺섻섽섾섿셁",6,"셊셎",5,"셖셗"], +["9961","셙셚셛셝",6,"셦셪",5,"셱셲셳셵셶셷셹셺셻"], +["9981","셼",8,"솆",5,"솏솑솒솓솕솗",4,"솞솠솢솣솤솦솧솪솫솭솮솯솱",11,"솾",5,"쇅쇆쇇쇉쇊쇋쇍",6,"쇕쇖쇙",6,"쇡쇢쇣쇥쇦쇧쇩",6,"쇲쇴",7,"쇾쇿숁숂숃숅",6,"숎숐숒",5,"숚숛숝숞숡숢숣"], +["9a41","숤숥숦숧숪숬숮숰숳숵",16], +["9a61","쉆쉇쉉",6,"쉒쉓쉕쉖쉗쉙",6,"쉡쉢쉣쉤쉦"], +["9a81","쉧",4,"쉮쉯쉱쉲쉳쉵",6,"쉾슀슂",5,"슊",5,"슑",6,"슙슚슜슞",5,"슦슧슩슪슫슮",5,"슶슸슺",33,"싞싟싡싢싥",5,"싮싰싲싳싴싵싷싺싽싾싿쌁",6,"쌊쌋쌎쌏"], +["9b41","쌐쌑쌒쌖쌗쌙쌚쌛쌝",6,"쌦쌧쌪",8], +["9b61","쌳",17,"썆",7], +["9b81","썎",25,"썪썫썭썮썯썱썳",4,"썺썻썾",5,"쎅쎆쎇쎉쎊쎋쎍",50,"쏁",22,"쏚"], +["9c41","쏛쏝쏞쏡쏣",4,"쏪쏫쏬쏮",5,"쏶쏷쏹",5], +["9c61","쏿",8,"쐉",6,"쐑",9], +["9c81","쐛",8,"쐥",6,"쐭쐮쐯쐱쐲쐳쐵",6,"쐾",9,"쑉",26,"쑦쑧쑩쑪쑫쑭",6,"쑶쑷쑸쑺",5,"쒁",18,"쒕",6,"쒝",12], +["9d41","쒪",13,"쒹쒺쒻쒽",8], +["9d61","쓆",25], +["9d81","쓠",8,"쓪",5,"쓲쓳쓵쓶쓷쓹쓻쓼쓽쓾씂",9,"씍씎씏씑씒씓씕",6,"씝",10,"씪씫씭씮씯씱",6,"씺씼씾",5,"앆앇앋앏앐앑앒앖앚앛앜앟앢앣앥앦앧앩",6,"앲앶",5,"앾앿얁얂얃얅얆얈얉얊얋얎얐얒얓얔"], +["9e41","얖얙얚얛얝얞얟얡",7,"얪",9,"얶"], +["9e61","얷얺얿",4,"엋엍엏엒엓엕엖엗엙",6,"엢엤엦엧"], +["9e81","엨엩엪엫엯엱엲엳엵엸엹엺엻옂옃옄옉옊옋옍옎옏옑",6,"옚옝",6,"옦옧옩옪옫옯옱옲옶옸옺옼옽옾옿왂왃왅왆왇왉",6,"왒왖",5,"왞왟왡",10,"왭왮왰왲",5,"왺왻왽왾왿욁",6,"욊욌욎",5,"욖욗욙욚욛욝",6,"욦"], +["9f41","욨욪",5,"욲욳욵욶욷욻",4,"웂웄웆",5,"웎"], +["9f61","웏웑웒웓웕",6,"웞웟웢",5,"웪웫웭웮웯웱웲"], +["9f81","웳",4,"웺웻웼웾",5,"윆윇윉윊윋윍",6,"윖윘윚",5,"윢윣윥윦윧윩",6,"윲윴윶윸윹윺윻윾윿읁읂읃읅",4,"읋읎읐읙읚읛읝읞읟읡",6,"읩읪읬",7,"읶읷읹읺읻읿잀잁잂잆잋잌잍잏잒잓잕잙잛",4,"잢잧",4,"잮잯잱잲잳잵잶잷"], +["a041","잸잹잺잻잾쟂",5,"쟊쟋쟍쟏쟑",6,"쟙쟚쟛쟜"], +["a061","쟞",5,"쟥쟦쟧쟩쟪쟫쟭",13], +["a081","쟻",4,"젂젃젅젆젇젉젋",4,"젒젔젗",4,"젞젟젡젢젣젥",6,"젮젰젲",5,"젹젺젻젽젾젿졁",6,"졊졋졎",5,"졕",26,"졲졳졵졶졷졹졻",4,"좂좄좈좉좊좎",5,"좕",7,"좞좠좢좣좤"], +["a141","좥좦좧좩",18,"좾좿죀죁"], +["a161","죂죃죅죆죇죉죊죋죍",6,"죖죘죚",5,"죢죣죥"], +["a181","죦",14,"죶",5,"죾죿줁줂줃줇",4,"줎 、。·‥…¨〃­―∥\∼‘’“”〔〕〈",9,"±×÷≠≤≥∞∴°′″℃Å¢£¥♂♀∠⊥⌒∂∇≡≒§※☆★○●◎◇◆□■△▲▽▼→←↑↓↔〓≪≫√∽∝∵∫∬∈∋⊆⊇⊂⊃∪∩∧∨¬"], +["a241","줐줒",5,"줙",18], +["a261","줭",6,"줵",18], +["a281","쥈",7,"쥒쥓쥕쥖쥗쥙",6,"쥢쥤",7,"쥭쥮쥯⇒⇔∀∃´~ˇ˘˝˚˙¸˛¡¿ː∮∑∏¤℉‰◁◀▷▶♤♠♡♥♧♣⊙◈▣◐◑▒▤▥▨▧▦▩♨☏☎☜☞¶†‡↕↗↙↖↘♭♩♪♬㉿㈜№㏇™㏂㏘℡€®"], +["a341","쥱쥲쥳쥵",6,"쥽",10,"즊즋즍즎즏"], +["a361","즑",6,"즚즜즞",16], +["a381","즯",16,"짂짃짅짆짉짋",4,"짒짔짗짘짛!",58,"₩]",32," ̄"], +["a441","짞짟짡짣짥짦짨짩짪짫짮짲",5,"짺짻짽짾짿쨁쨂쨃쨄"], +["a461","쨅쨆쨇쨊쨎",5,"쨕쨖쨗쨙",12], +["a481","쨦쨧쨨쨪",28,"ㄱ",93], +["a541","쩇",4,"쩎쩏쩑쩒쩓쩕",6,"쩞쩢",5,"쩩쩪"], +["a561","쩫",17,"쩾",5,"쪅쪆"], +["a581","쪇",16,"쪙",14,"ⅰ",9], +["a5b0","Ⅰ",9], +["a5c1","Α",16,"Σ",6], +["a5e1","α",16,"σ",6], +["a641","쪨",19,"쪾쪿쫁쫂쫃쫅"], +["a661","쫆",5,"쫎쫐쫒쫔쫕쫖쫗쫚",5,"쫡",6], +["a681","쫨쫩쫪쫫쫭",6,"쫵",18,"쬉쬊─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂┒┑┚┙┖┕┎┍┞┟┡┢┦┧┩┪┭┮┱┲┵┶┹┺┽┾╀╁╃",7], +["a741","쬋",4,"쬑쬒쬓쬕쬖쬗쬙",6,"쬢",7], +["a761","쬪",22,"쭂쭃쭄"], +["a781","쭅쭆쭇쭊쭋쭍쭎쭏쭑",6,"쭚쭛쭜쭞",5,"쭥",7,"㎕㎖㎗ℓ㎘㏄㎣㎤㎥㎦㎙",9,"㏊㎍㎎㎏㏏㎈㎉㏈㎧㎨㎰",9,"㎀",4,"㎺",5,"㎐",4,"Ω㏀㏁㎊㎋㎌㏖㏅㎭㎮㎯㏛㎩㎪㎫㎬㏝㏐㏓㏃㏉㏜㏆"], +["a841","쭭",10,"쭺",14], +["a861","쮉",18,"쮝",6], +["a881","쮤",19,"쮹",11,"ÆÐªĦ"], +["a8a6","IJ"], +["a8a8","ĿŁØŒºÞŦŊ"], +["a8b1","㉠",27,"ⓐ",25,"①",14,"½⅓⅔¼¾⅛⅜⅝⅞"], +["a941","쯅",14,"쯕",10], +["a961","쯠쯡쯢쯣쯥쯦쯨쯪",18], +["a981","쯽",14,"찎찏찑찒찓찕",6,"찞찟찠찣찤æđðħıijĸŀłøœßþŧŋʼn㈀",27,"⒜",25,"⑴",14,"¹²³⁴ⁿ₁₂₃₄"], +["aa41","찥찦찪찫찭찯찱",6,"찺찿",4,"챆챇챉챊챋챍챎"], +["aa61","챏",4,"챖챚",5,"챡챢챣챥챧챩",6,"챱챲"], +["aa81","챳챴챶",29,"ぁ",82], +["ab41","첔첕첖첗첚첛첝첞첟첡",6,"첪첮",5,"첶첷첹"], +["ab61","첺첻첽",6,"쳆쳈쳊",5,"쳑쳒쳓쳕",5], +["ab81","쳛",8,"쳥",6,"쳭쳮쳯쳱",12,"ァ",85], +["ac41","쳾쳿촀촂",5,"촊촋촍촎촏촑",6,"촚촜촞촟촠"], +["ac61","촡촢촣촥촦촧촩촪촫촭",11,"촺",4], +["ac81","촿",28,"쵝쵞쵟А",5,"ЁЖ",25], +["acd1","а",5,"ёж",25], +["ad41","쵡쵢쵣쵥",6,"쵮쵰쵲",5,"쵹",7], +["ad61","춁",6,"춉",10,"춖춗춙춚춛춝춞춟"], +["ad81","춠춡춢춣춦춨춪",5,"춱",18,"췅"], +["ae41","췆",5,"췍췎췏췑",16], +["ae61","췢",5,"췩췪췫췭췮췯췱",6,"췺췼췾",4], +["ae81","츃츅츆츇츉츊츋츍",6,"츕츖츗츘츚",5,"츢츣츥츦츧츩츪츫"], +["af41","츬츭츮츯츲츴츶",19], +["af61","칊",13,"칚칛칝칞칢",5,"칪칬"], +["af81","칮",5,"칶칷칹칺칻칽",6,"캆캈캊",5,"캒캓캕캖캗캙"], +["b041","캚",5,"캢캦",5,"캮",12], +["b061","캻",5,"컂",19], +["b081","컖",13,"컦컧컩컪컭",6,"컶컺",5,"가각간갇갈갉갊감",7,"같",4,"갠갤갬갭갯갰갱갸갹갼걀걋걍걔걘걜거걱건걷걸걺검겁것겄겅겆겉겊겋게겐겔겜겝겟겠겡겨격겪견겯결겸겹겻겼경곁계곈곌곕곗고곡곤곧골곪곬곯곰곱곳공곶과곽관괄괆"], +["b141","켂켃켅켆켇켉",6,"켒켔켖",5,"켝켞켟켡켢켣"], +["b161","켥",6,"켮켲",5,"켹",11], +["b181","콅",14,"콖콗콙콚콛콝",6,"콦콨콪콫콬괌괍괏광괘괜괠괩괬괭괴괵괸괼굄굅굇굉교굔굘굡굣구국군굳굴굵굶굻굼굽굿궁궂궈궉권궐궜궝궤궷귀귁귄귈귐귑귓규균귤그극근귿글긁금급긋긍긔기긱긴긷길긺김깁깃깅깆깊까깍깎깐깔깖깜깝깟깠깡깥깨깩깬깰깸"], +["b241","콭콮콯콲콳콵콶콷콹",6,"쾁쾂쾃쾄쾆",5,"쾍"], +["b261","쾎",18,"쾢",5,"쾩"], +["b281","쾪",5,"쾱",18,"쿅",6,"깹깻깼깽꺄꺅꺌꺼꺽꺾껀껄껌껍껏껐껑께껙껜껨껫껭껴껸껼꼇꼈꼍꼐꼬꼭꼰꼲꼴꼼꼽꼿꽁꽂꽃꽈꽉꽐꽜꽝꽤꽥꽹꾀꾄꾈꾐꾑꾕꾜꾸꾹꾼꿀꿇꿈꿉꿋꿍꿎꿔꿜꿨꿩꿰꿱꿴꿸뀀뀁뀄뀌뀐뀔뀜뀝뀨끄끅끈끊끌끎끓끔끕끗끙"], +["b341","쿌",19,"쿢쿣쿥쿦쿧쿩"], +["b361","쿪",5,"쿲쿴쿶",5,"쿽쿾쿿퀁퀂퀃퀅",5], +["b381","퀋",5,"퀒",5,"퀙",19,"끝끼끽낀낄낌낍낏낑나낙낚난낟날낡낢남납낫",4,"낱낳내낵낸낼냄냅냇냈냉냐냑냔냘냠냥너넉넋넌널넒넓넘넙넛넜넝넣네넥넨넬넴넵넷넸넹녀녁년녈념녑녔녕녘녜녠노녹논놀놂놈놉놋농높놓놔놘놜놨뇌뇐뇔뇜뇝"], +["b441","퀮",5,"퀶퀷퀹퀺퀻퀽",6,"큆큈큊",5], +["b461","큑큒큓큕큖큗큙",6,"큡",10,"큮큯"], +["b481","큱큲큳큵",6,"큾큿킀킂",18,"뇟뇨뇩뇬뇰뇹뇻뇽누눅눈눋눌눔눕눗눙눠눴눼뉘뉜뉠뉨뉩뉴뉵뉼늄늅늉느늑는늘늙늚늠늡늣능늦늪늬늰늴니닉닌닐닒님닙닛닝닢다닥닦단닫",4,"닳담답닷",4,"닿대댁댄댈댐댑댓댔댕댜더덕덖던덛덜덞덟덤덥"], +["b541","킕",14,"킦킧킩킪킫킭",5], +["b561","킳킶킸킺",5,"탂탃탅탆탇탊",5,"탒탖",4], +["b581","탛탞탟탡탢탣탥",6,"탮탲",5,"탹",11,"덧덩덫덮데덱덴델뎀뎁뎃뎄뎅뎌뎐뎔뎠뎡뎨뎬도독돈돋돌돎돐돔돕돗동돛돝돠돤돨돼됐되된될됨됩됫됴두둑둔둘둠둡둣둥둬뒀뒈뒝뒤뒨뒬뒵뒷뒹듀듄듈듐듕드득든듣들듦듬듭듯등듸디딕딘딛딜딤딥딧딨딩딪따딱딴딸"], +["b641","턅",7,"턎",17], +["b661","턠",15,"턲턳턵턶턷턹턻턼턽턾"], +["b681","턿텂텆",5,"텎텏텑텒텓텕",6,"텞텠텢",5,"텩텪텫텭땀땁땃땄땅땋때땍땐땔땜땝땟땠땡떠떡떤떨떪떫떰떱떳떴떵떻떼떽뗀뗄뗌뗍뗏뗐뗑뗘뗬또똑똔똘똥똬똴뙈뙤뙨뚜뚝뚠뚤뚫뚬뚱뛔뛰뛴뛸뜀뜁뜅뜨뜩뜬뜯뜰뜸뜹뜻띄띈띌띔띕띠띤띨띰띱띳띵라락란랄람랍랏랐랑랒랖랗"], +["b741","텮",13,"텽",6,"톅톆톇톉톊"], +["b761","톋",20,"톢톣톥톦톧"], +["b781","톩",6,"톲톴톶톷톸톹톻톽톾톿퇁",14,"래랙랜랠램랩랫랬랭랴략랸럇량러럭런럴럼럽럿렀렁렇레렉렌렐렘렙렛렝려력련렬렴렵렷렸령례롄롑롓로록론롤롬롭롯롱롸롼뢍뢨뢰뢴뢸룀룁룃룅료룐룔룝룟룡루룩룬룰룸룹룻룽뤄뤘뤠뤼뤽륀륄륌륏륑류륙륜률륨륩"], +["b841","퇐",7,"퇙",17], +["b861","퇫",8,"퇵퇶퇷퇹",13], +["b881","툈툊",5,"툑",24,"륫륭르륵른를름릅릇릉릊릍릎리릭린릴림립릿링마막만많",4,"맘맙맛망맞맡맣매맥맨맬맴맵맷맸맹맺먀먁먈먕머먹먼멀멂멈멉멋멍멎멓메멕멘멜멤멥멧멨멩며멱면멸몃몄명몇몌모목몫몬몰몲몸몹못몽뫄뫈뫘뫙뫼"], +["b941","툪툫툮툯툱툲툳툵",6,"툾퉀퉂",5,"퉉퉊퉋퉌"], +["b961","퉍",14,"퉝",6,"퉥퉦퉧퉨"], +["b981","퉩",22,"튂튃튅튆튇튉튊튋튌묀묄묍묏묑묘묜묠묩묫무묵묶문묻물묽묾뭄뭅뭇뭉뭍뭏뭐뭔뭘뭡뭣뭬뮈뮌뮐뮤뮨뮬뮴뮷므믄믈믐믓미믹민믿밀밂밈밉밋밌밍및밑바",4,"받",4,"밤밥밧방밭배백밴밸뱀뱁뱃뱄뱅뱉뱌뱍뱐뱝버벅번벋벌벎범법벗"], +["ba41","튍튎튏튒튓튔튖",5,"튝튞튟튡튢튣튥",6,"튭"], +["ba61","튮튯튰튲",5,"튺튻튽튾틁틃",4,"틊틌",5], +["ba81","틒틓틕틖틗틙틚틛틝",6,"틦",9,"틲틳틵틶틷틹틺벙벚베벡벤벧벨벰벱벳벴벵벼벽변별볍볏볐병볕볘볜보복볶본볼봄봅봇봉봐봔봤봬뵀뵈뵉뵌뵐뵘뵙뵤뵨부북분붇불붉붊붐붑붓붕붙붚붜붤붰붸뷔뷕뷘뷜뷩뷰뷴뷸븀븃븅브븍븐블븜븝븟비빅빈빌빎빔빕빗빙빚빛빠빡빤"], +["bb41","틻",4,"팂팄팆",5,"팏팑팒팓팕팗",4,"팞팢팣"], +["bb61","팤팦팧팪팫팭팮팯팱",6,"팺팾",5,"퍆퍇퍈퍉"], +["bb81","퍊",31,"빨빪빰빱빳빴빵빻빼빽뺀뺄뺌뺍뺏뺐뺑뺘뺙뺨뻐뻑뻔뻗뻘뻠뻣뻤뻥뻬뼁뼈뼉뼘뼙뼛뼜뼝뽀뽁뽄뽈뽐뽑뽕뾔뾰뿅뿌뿍뿐뿔뿜뿟뿡쀼쁑쁘쁜쁠쁨쁩삐삑삔삘삠삡삣삥사삭삯산삳살삵삶삼삽삿샀상샅새색샌샐샘샙샛샜생샤"], +["bc41","퍪",17,"퍾퍿펁펂펃펅펆펇"], +["bc61","펈펉펊펋펎펒",5,"펚펛펝펞펟펡",6,"펪펬펮"], +["bc81","펯",4,"펵펶펷펹펺펻펽",6,"폆폇폊",5,"폑",5,"샥샨샬샴샵샷샹섀섄섈섐섕서",4,"섣설섦섧섬섭섯섰성섶세섹센셀셈셉셋셌셍셔셕션셜셤셥셧셨셩셰셴셸솅소속솎손솔솖솜솝솟송솥솨솩솬솰솽쇄쇈쇌쇔쇗쇘쇠쇤쇨쇰쇱쇳쇼쇽숀숄숌숍숏숑수숙순숟술숨숩숫숭"], +["bd41","폗폙",7,"폢폤",7,"폮폯폱폲폳폵폶폷"], +["bd61","폸폹폺폻폾퐀퐂",5,"퐉",13], +["bd81","퐗",5,"퐞",25,"숯숱숲숴쉈쉐쉑쉔쉘쉠쉥쉬쉭쉰쉴쉼쉽쉿슁슈슉슐슘슛슝스슥슨슬슭슴습슷승시식신싣실싫심십싯싱싶싸싹싻싼쌀쌈쌉쌌쌍쌓쌔쌕쌘쌜쌤쌥쌨쌩썅써썩썬썰썲썸썹썼썽쎄쎈쎌쏀쏘쏙쏜쏟쏠쏢쏨쏩쏭쏴쏵쏸쐈쐐쐤쐬쐰"], +["be41","퐸",7,"푁푂푃푅",14], +["be61","푔",7,"푝푞푟푡푢푣푥",7,"푮푰푱푲"], +["be81","푳",4,"푺푻푽푾풁풃",4,"풊풌풎",5,"풕",8,"쐴쐼쐽쑈쑤쑥쑨쑬쑴쑵쑹쒀쒔쒜쒸쒼쓩쓰쓱쓴쓸쓺쓿씀씁씌씐씔씜씨씩씬씰씸씹씻씽아악안앉않알앍앎앓암압앗았앙앝앞애액앤앨앰앱앳앴앵야약얀얄얇얌얍얏양얕얗얘얜얠얩어억언얹얻얼얽얾엄",6,"엌엎"], +["bf41","풞",10,"풪",14], +["bf61","풹",18,"퓍퓎퓏퓑퓒퓓퓕"], +["bf81","퓖",5,"퓝퓞퓠",7,"퓩퓪퓫퓭퓮퓯퓱",6,"퓹퓺퓼에엑엔엘엠엡엣엥여역엮연열엶엷염",5,"옅옆옇예옌옐옘옙옛옜오옥온올옭옮옰옳옴옵옷옹옻와왁완왈왐왑왓왔왕왜왝왠왬왯왱외왹왼욀욈욉욋욍요욕욘욜욤욥욧용우욱운울욹욺움웁웃웅워웍원월웜웝웠웡웨"], +["c041","퓾",5,"픅픆픇픉픊픋픍",6,"픖픘",5], +["c061","픞",25], +["c081","픸픹픺픻픾픿핁핂핃핅",6,"핎핐핒",5,"핚핛핝핞핟핡핢핣웩웬웰웸웹웽위윅윈윌윔윕윗윙유육윤율윰윱윳융윷으윽은을읊음읍읏응",7,"읜읠읨읫이익인일읽읾잃임입잇있잉잊잎자작잔잖잗잘잚잠잡잣잤장잦재잭잰잴잼잽잿쟀쟁쟈쟉쟌쟎쟐쟘쟝쟤쟨쟬저적전절젊"], +["c141","핤핦핧핪핬핮",5,"핶핷핹핺핻핽",6,"햆햊햋"], +["c161","햌햍햎햏햑",19,"햦햧"], +["c181","햨",31,"점접젓정젖제젝젠젤젬젭젯젱져젼졀졈졉졌졍졔조족존졸졺좀좁좃종좆좇좋좌좍좔좝좟좡좨좼좽죄죈죌죔죕죗죙죠죡죤죵주죽준줄줅줆줌줍줏중줘줬줴쥐쥑쥔쥘쥠쥡쥣쥬쥰쥴쥼즈즉즌즐즘즙즛증지직진짇질짊짐집짓"], +["c241","헊헋헍헎헏헑헓",4,"헚헜헞",5,"헦헧헩헪헫헭헮"], +["c261","헯",4,"헶헸헺",5,"혂혃혅혆혇혉",6,"혒"], +["c281","혖",5,"혝혞혟혡혢혣혥",7,"혮",9,"혺혻징짖짙짚짜짝짠짢짤짧짬짭짯짰짱째짹짼쨀쨈쨉쨋쨌쨍쨔쨘쨩쩌쩍쩐쩔쩜쩝쩟쩠쩡쩨쩽쪄쪘쪼쪽쫀쫄쫌쫍쫏쫑쫓쫘쫙쫠쫬쫴쬈쬐쬔쬘쬠쬡쭁쭈쭉쭌쭐쭘쭙쭝쭤쭸쭹쮜쮸쯔쯤쯧쯩찌찍찐찔찜찝찡찢찧차착찬찮찰참찹찻"], +["c341","혽혾혿홁홂홃홄홆홇홊홌홎홏홐홒홓홖홗홙홚홛홝",4], +["c361","홢",4,"홨홪",5,"홲홳홵",11], +["c381","횁횂횄횆",5,"횎횏횑횒횓횕",7,"횞횠횢",5,"횩횪찼창찾채책챈챌챔챕챗챘챙챠챤챦챨챰챵처척천철첨첩첫첬청체첵첸첼쳄쳅쳇쳉쳐쳔쳤쳬쳰촁초촉촌촐촘촙촛총촤촨촬촹최쵠쵤쵬쵭쵯쵱쵸춈추축춘출춤춥춧충춰췄췌췐취췬췰췸췹췻췽츄츈츌츔츙츠측츤츨츰츱츳층"], +["c441","횫횭횮횯횱",7,"횺횼",7,"훆훇훉훊훋"], +["c461","훍훎훏훐훒훓훕훖훘훚",5,"훡훢훣훥훦훧훩",4], +["c481","훮훯훱훲훳훴훶",5,"훾훿휁휂휃휅",11,"휒휓휔치칙친칟칠칡침칩칫칭카칵칸칼캄캅캇캉캐캑캔캘캠캡캣캤캥캬캭컁커컥컨컫컬컴컵컷컸컹케켁켄켈켐켑켓켕켜켠켤켬켭켯켰켱켸코콕콘콜콤콥콧콩콰콱콴콸쾀쾅쾌쾡쾨쾰쿄쿠쿡쿤쿨쿰쿱쿳쿵쿼퀀퀄퀑퀘퀭퀴퀵퀸퀼"], +["c541","휕휖휗휚휛휝휞휟휡",6,"휪휬휮",5,"휶휷휹"], +["c561","휺휻휽",6,"흅흆흈흊",5,"흒흓흕흚",4], +["c581","흟흢흤흦흧흨흪흫흭흮흯흱흲흳흵",6,"흾흿힀힂",5,"힊힋큄큅큇큉큐큔큘큠크큭큰클큼큽킁키킥킨킬킴킵킷킹타탁탄탈탉탐탑탓탔탕태택탠탤탬탭탯탰탱탸턍터턱턴털턺텀텁텃텄텅테텍텐텔템텝텟텡텨텬텼톄톈토톡톤톨톰톱톳통톺톼퇀퇘퇴퇸툇툉툐투툭툰툴툼툽툿퉁퉈퉜"], +["c641","힍힎힏힑",6,"힚힜힞",5], +["c6a1","퉤튀튁튄튈튐튑튕튜튠튤튬튱트특튼튿틀틂틈틉틋틔틘틜틤틥티틱틴틸팀팁팃팅파팍팎판팔팖팜팝팟팠팡팥패팩팬팰팸팹팻팼팽퍄퍅퍼퍽펀펄펌펍펏펐펑페펙펜펠펨펩펫펭펴편펼폄폅폈평폐폘폡폣포폭폰폴폼폽폿퐁"], +["c7a1","퐈퐝푀푄표푠푤푭푯푸푹푼푿풀풂품풉풋풍풔풩퓌퓐퓔퓜퓟퓨퓬퓰퓸퓻퓽프픈플픔픕픗피픽핀필핌핍핏핑하학한할핥함합핫항해핵핸핼햄햅햇했행햐향허헉헌헐헒험헙헛헝헤헥헨헬헴헵헷헹혀혁현혈혐협혓혔형혜혠"], +["c8a1","혤혭호혹혼홀홅홈홉홋홍홑화확환활홧황홰홱홴횃횅회획횐횔횝횟횡효횬횰횹횻후훅훈훌훑훔훗훙훠훤훨훰훵훼훽휀휄휑휘휙휜휠휨휩휫휭휴휵휸휼흄흇흉흐흑흔흖흗흘흙흠흡흣흥흩희흰흴흼흽힁히힉힌힐힘힙힛힝"], +["caa1","伽佳假價加可呵哥嘉嫁家暇架枷柯歌珂痂稼苛茄街袈訶賈跏軻迦駕刻却各恪慤殼珏脚覺角閣侃刊墾奸姦干幹懇揀杆柬桿澗癎看磵稈竿簡肝艮艱諫間乫喝曷渴碣竭葛褐蝎鞨勘坎堪嵌感憾戡敢柑橄減甘疳監瞰紺邯鑑鑒龕"], +["cba1","匣岬甲胛鉀閘剛堈姜岡崗康强彊慷江畺疆糠絳綱羌腔舡薑襁講鋼降鱇介价個凱塏愷愾慨改槪漑疥皆盖箇芥蓋豈鎧開喀客坑更粳羹醵倨去居巨拒据據擧渠炬祛距踞車遽鉅鋸乾件健巾建愆楗腱虔蹇鍵騫乞傑杰桀儉劍劒檢"], +["cca1","瞼鈐黔劫怯迲偈憩揭擊格檄激膈覡隔堅牽犬甄絹繭肩見譴遣鵑抉決潔結缺訣兼慊箝謙鉗鎌京俓倞傾儆勁勍卿坰境庚徑慶憬擎敬景暻更梗涇炅烱璟璥瓊痙硬磬竟競絅經耕耿脛莖警輕逕鏡頃頸驚鯨係啓堺契季屆悸戒桂械"], +["cda1","棨溪界癸磎稽系繫繼計誡谿階鷄古叩告呱固姑孤尻庫拷攷故敲暠枯槁沽痼皐睾稿羔考股膏苦苽菰藁蠱袴誥賈辜錮雇顧高鼓哭斛曲梏穀谷鵠困坤崑昆梱棍滾琨袞鯤汨滑骨供公共功孔工恐恭拱控攻珙空蚣貢鞏串寡戈果瓜"], +["cea1","科菓誇課跨過鍋顆廓槨藿郭串冠官寬慣棺款灌琯瓘管罐菅觀貫關館刮恝括适侊光匡壙廣曠洸炚狂珖筐胱鑛卦掛罫乖傀塊壞怪愧拐槐魁宏紘肱轟交僑咬喬嬌嶠巧攪敎校橋狡皎矯絞翹膠蕎蛟較轎郊餃驕鮫丘久九仇俱具勾"], +["cfa1","區口句咎嘔坵垢寇嶇廐懼拘救枸柩構歐毆毬求溝灸狗玖球瞿矩究絿耉臼舅舊苟衢謳購軀逑邱鉤銶駒驅鳩鷗龜國局菊鞠鞫麴君窘群裙軍郡堀屈掘窟宮弓穹窮芎躬倦券勸卷圈拳捲權淃眷厥獗蕨蹶闕机櫃潰詭軌饋句晷歸貴"], +["d0a1","鬼龜叫圭奎揆槻珪硅窺竅糾葵規赳逵閨勻均畇筠菌鈞龜橘克剋劇戟棘極隙僅劤勤懃斤根槿瑾筋芹菫覲謹近饉契今妗擒昑檎琴禁禽芩衾衿襟金錦伋及急扱汲級給亘兢矜肯企伎其冀嗜器圻基埼夔奇妓寄岐崎己幾忌技旗旣"], +["d1a1","朞期杞棋棄機欺氣汽沂淇玘琦琪璂璣畸畿碁磯祁祇祈祺箕紀綺羈耆耭肌記譏豈起錡錤飢饑騎騏驥麒緊佶吉拮桔金喫儺喇奈娜懦懶拏拿癩",5,"那樂",4,"諾酪駱亂卵暖欄煖爛蘭難鸞捏捺南嵐枏楠湳濫男藍襤拉"], +["d2a1","納臘蠟衲囊娘廊",4,"乃來內奈柰耐冷女年撚秊念恬拈捻寧寗努勞奴弩怒擄櫓爐瑙盧",5,"駑魯",10,"濃籠聾膿農惱牢磊腦賂雷尿壘",7,"嫩訥杻紐勒",5,"能菱陵尼泥匿溺多茶"], +["d3a1","丹亶但單團壇彖斷旦檀段湍短端簞緞蛋袒鄲鍛撻澾獺疸達啖坍憺擔曇淡湛潭澹痰聃膽蕁覃談譚錟沓畓答踏遝唐堂塘幢戇撞棠當糖螳黨代垈坮大對岱帶待戴擡玳臺袋貸隊黛宅德悳倒刀到圖堵塗導屠島嶋度徒悼挑掉搗桃"], +["d4a1","棹櫂淘渡滔濤燾盜睹禱稻萄覩賭跳蹈逃途道都鍍陶韜毒瀆牘犢獨督禿篤纛讀墩惇敦旽暾沌焞燉豚頓乭突仝冬凍動同憧東桐棟洞潼疼瞳童胴董銅兜斗杜枓痘竇荳讀豆逗頭屯臀芚遁遯鈍得嶝橙燈登等藤謄鄧騰喇懶拏癩羅"], +["d5a1","蘿螺裸邏樂洛烙珞絡落諾酪駱丹亂卵欄欒瀾爛蘭鸞剌辣嵐擥攬欖濫籃纜藍襤覽拉臘蠟廊朗浪狼琅瑯螂郞來崍徠萊冷掠略亮倆兩凉梁樑粮粱糧良諒輛量侶儷勵呂廬慮戾旅櫚濾礪藜蠣閭驢驪麗黎力曆歷瀝礫轢靂憐戀攣漣"], +["d6a1","煉璉練聯蓮輦連鍊冽列劣洌烈裂廉斂殮濂簾獵令伶囹寧岺嶺怜玲笭羚翎聆逞鈴零靈領齡例澧禮醴隷勞怒撈擄櫓潞瀘爐盧老蘆虜路輅露魯鷺鹵碌祿綠菉錄鹿麓論壟弄朧瀧瓏籠聾儡瀨牢磊賂賚賴雷了僚寮廖料燎療瞭聊蓼"], +["d7a1","遼鬧龍壘婁屢樓淚漏瘻累縷蔞褸鏤陋劉旒柳榴流溜瀏琉瑠留瘤硫謬類六戮陸侖倫崙淪綸輪律慄栗率隆勒肋凜凌楞稜綾菱陵俚利厘吏唎履悧李梨浬犁狸理璃異痢籬罹羸莉裏裡里釐離鯉吝潾燐璘藺躪隣鱗麟林淋琳臨霖砬"], +["d8a1","立笠粒摩瑪痲碼磨馬魔麻寞幕漠膜莫邈万卍娩巒彎慢挽晩曼滿漫灣瞞萬蔓蠻輓饅鰻唜抹末沫茉襪靺亡妄忘忙望網罔芒茫莽輞邙埋妹媒寐昧枚梅每煤罵買賣邁魅脈貊陌驀麥孟氓猛盲盟萌冪覓免冕勉棉沔眄眠綿緬面麵滅"], +["d9a1","蔑冥名命明暝椧溟皿瞑茗蓂螟酩銘鳴袂侮冒募姆帽慕摸摹暮某模母毛牟牡瑁眸矛耗芼茅謀謨貌木沐牧目睦穆鶩歿沒夢朦蒙卯墓妙廟描昴杳渺猫竗苗錨務巫憮懋戊拇撫无楙武毋無珷畝繆舞茂蕪誣貿霧鵡墨默們刎吻問文"], +["daa1","汶紊紋聞蚊門雯勿沕物味媚尾嵋彌微未梶楣渼湄眉米美薇謎迷靡黴岷悶愍憫敏旻旼民泯玟珉緡閔密蜜謐剝博拍搏撲朴樸泊珀璞箔粕縛膊舶薄迫雹駁伴半反叛拌搬攀斑槃泮潘班畔瘢盤盼磐磻礬絆般蟠返頒飯勃拔撥渤潑"], +["dba1","發跋醱鉢髮魃倣傍坊妨尨幇彷房放方旁昉枋榜滂磅紡肪膀舫芳蒡蚌訪謗邦防龐倍俳北培徘拜排杯湃焙盃背胚裴裵褙賠輩配陪伯佰帛柏栢白百魄幡樊煩燔番磻繁蕃藩飜伐筏罰閥凡帆梵氾汎泛犯範范法琺僻劈壁擘檗璧癖"], +["dca1","碧蘗闢霹便卞弁變辨辯邊別瞥鱉鼈丙倂兵屛幷昞昺柄棅炳甁病秉竝輧餠騈保堡報寶普步洑湺潽珤甫菩補褓譜輔伏僕匐卜宓復服福腹茯蔔複覆輹輻馥鰒本乶俸奉封峯峰捧棒烽熢琫縫蓬蜂逢鋒鳳不付俯傅剖副否咐埠夫婦"], +["dda1","孚孵富府復扶敷斧浮溥父符簿缶腐腑膚艀芙莩訃負賦賻赴趺部釜阜附駙鳧北分吩噴墳奔奮忿憤扮昐汾焚盆粉糞紛芬賁雰不佛弗彿拂崩朋棚硼繃鵬丕備匕匪卑妃婢庇悲憊扉批斐枇榧比毖毗毘沸泌琵痺砒碑秕秘粃緋翡肥"], +["dea1","脾臂菲蜚裨誹譬費鄙非飛鼻嚬嬪彬斌檳殯浜濱瀕牝玭貧賓頻憑氷聘騁乍事些仕伺似使俟僿史司唆嗣四士奢娑寫寺射巳師徙思捨斜斯柶査梭死沙泗渣瀉獅砂社祀祠私篩紗絲肆舍莎蓑蛇裟詐詞謝賜赦辭邪飼駟麝削數朔索"], +["dfa1","傘刪山散汕珊産疝算蒜酸霰乷撒殺煞薩三參杉森渗芟蔘衫揷澁鈒颯上傷像償商喪嘗孀尙峠常床庠廂想桑橡湘爽牀狀相祥箱翔裳觴詳象賞霜塞璽賽嗇塞穡索色牲生甥省笙墅壻嶼序庶徐恕抒捿敍暑曙書栖棲犀瑞筮絮緖署"], +["e0a1","胥舒薯西誓逝鋤黍鼠夕奭席惜昔晳析汐淅潟石碩蓆釋錫仙僊先善嬋宣扇敾旋渲煽琁瑄璇璿癬禪線繕羨腺膳船蘚蟬詵跣選銑鐥饍鮮卨屑楔泄洩渫舌薛褻設說雪齧剡暹殲纖蟾贍閃陝攝涉燮葉城姓宬性惺成星晟猩珹盛省筬"], +["e1a1","聖聲腥誠醒世勢歲洗稅笹細說貰召嘯塑宵小少巢所掃搔昭梳沼消溯瀟炤燒甦疏疎瘙笑篠簫素紹蔬蕭蘇訴逍遡邵銷韶騷俗屬束涑粟續謖贖速孫巽損蓀遜飡率宋悚松淞訟誦送頌刷殺灑碎鎖衰釗修受嗽囚垂壽嫂守岫峀帥愁"], +["e2a1","戍手授搜收數樹殊水洙漱燧狩獸琇璲瘦睡秀穗竪粹綏綬繡羞脩茱蒐蓚藪袖誰讐輸遂邃酬銖銹隋隧隨雖需須首髓鬚叔塾夙孰宿淑潚熟琡璹肅菽巡徇循恂旬栒楯橓殉洵淳珣盾瞬筍純脣舜荀蓴蕣詢諄醇錞順馴戌術述鉥崇崧"], +["e3a1","嵩瑟膝蝨濕拾習褶襲丞乘僧勝升承昇繩蠅陞侍匙嘶始媤尸屎屍市弑恃施是時枾柴猜矢示翅蒔蓍視試詩諡豕豺埴寔式息拭植殖湜熄篒蝕識軾食飾伸侁信呻娠宸愼新晨燼申神紳腎臣莘薪藎蜃訊身辛辰迅失室實悉審尋心沁"], +["e4a1","沈深瀋甚芯諶什十拾雙氏亞俄兒啞娥峨我牙芽莪蛾衙訝阿雅餓鴉鵝堊岳嶽幄惡愕握樂渥鄂鍔顎鰐齷安岸按晏案眼雁鞍顔鮟斡謁軋閼唵岩巖庵暗癌菴闇壓押狎鴨仰央怏昻殃秧鴦厓哀埃崖愛曖涯碍艾隘靄厄扼掖液縊腋額"], +["e5a1","櫻罌鶯鸚也倻冶夜惹揶椰爺耶若野弱掠略約若葯蒻藥躍亮佯兩凉壤孃恙揚攘敭暘梁楊樣洋瀁煬痒瘍禳穰糧羊良襄諒讓釀陽量養圄御於漁瘀禦語馭魚齬億憶抑檍臆偃堰彦焉言諺孼蘖俺儼嚴奄掩淹嶪業円予余勵呂女如廬"], +["e6a1","旅歟汝濾璵礖礪與艅茹輿轝閭餘驪麗黎亦力域役易曆歷疫繹譯轢逆驛嚥堧姸娟宴年延憐戀捐挻撚椽沇沿涎涓淵演漣烟然煙煉燃燕璉硏硯秊筵緣練縯聯衍軟輦蓮連鉛鍊鳶列劣咽悅涅烈熱裂說閱厭廉念捻染殮炎焰琰艶苒"], +["e7a1","簾閻髥鹽曄獵燁葉令囹塋寧嶺嶸影怜映暎楹榮永泳渶潁濚瀛瀯煐營獰玲瑛瑩瓔盈穎纓羚聆英詠迎鈴鍈零霙靈領乂倪例刈叡曳汭濊猊睿穢芮藝蘂禮裔詣譽豫醴銳隸霓預五伍俉傲午吾吳嗚塢墺奧娛寤悟惡懊敖旿晤梧汚澳"], +["e8a1","烏熬獒筽蜈誤鰲鼇屋沃獄玉鈺溫瑥瘟穩縕蘊兀壅擁瓮甕癰翁邕雍饔渦瓦窩窪臥蛙蝸訛婉完宛梡椀浣玩琓琬碗緩翫脘腕莞豌阮頑曰往旺枉汪王倭娃歪矮外嵬巍猥畏了僚僥凹堯夭妖姚寥寮尿嶢拗搖撓擾料曜樂橈燎燿瑤療"], +["e9a1","窈窯繇繞耀腰蓼蟯要謠遙遼邀饒慾欲浴縟褥辱俑傭冗勇埇墉容庸慂榕涌湧溶熔瑢用甬聳茸蓉踊鎔鏞龍于佑偶優又友右宇寓尤愚憂旴牛玗瑀盂祐禑禹紆羽芋藕虞迂遇郵釪隅雨雩勖彧旭昱栯煜稶郁頊云暈橒殞澐熉耘芸蕓"], +["eaa1","運隕雲韻蔚鬱亐熊雄元原員圓園垣媛嫄寃怨愿援沅洹湲源爰猿瑗苑袁轅遠阮院願鴛月越鉞位偉僞危圍委威尉慰暐渭爲瑋緯胃萎葦蔿蝟衛褘謂違韋魏乳侑儒兪劉唯喩孺宥幼幽庾悠惟愈愉揄攸有杻柔柚柳楡楢油洧流游溜"], +["eba1","濡猶猷琉瑜由留癒硫紐維臾萸裕誘諛諭踰蹂遊逾遺酉釉鍮類六堉戮毓肉育陸倫允奫尹崙淪潤玧胤贇輪鈗閏律慄栗率聿戎瀜絨融隆垠恩慇殷誾銀隱乙吟淫蔭陰音飮揖泣邑凝應膺鷹依倚儀宜意懿擬椅毅疑矣義艤薏蟻衣誼"], +["eca1","議醫二以伊利吏夷姨履已弛彛怡易李梨泥爾珥理異痍痢移罹而耳肄苡荑裏裡貽貳邇里離飴餌匿溺瀷益翊翌翼謚人仁刃印吝咽因姻寅引忍湮燐璘絪茵藺蚓認隣靭靷鱗麟一佚佾壹日溢逸鎰馹任壬妊姙恁林淋稔臨荏賃入卄"], +["eda1","立笠粒仍剩孕芿仔刺咨姉姿子字孜恣慈滋炙煮玆瓷疵磁紫者自茨蔗藉諮資雌作勺嚼斫昨灼炸爵綽芍酌雀鵲孱棧殘潺盞岑暫潛箴簪蠶雜丈仗匠場墻壯奬將帳庄張掌暲杖樟檣欌漿牆狀獐璋章粧腸臟臧莊葬蔣薔藏裝贓醬長"], +["eea1","障再哉在宰才材栽梓渽滓災縡裁財載齋齎爭箏諍錚佇低儲咀姐底抵杵楮樗沮渚狙猪疽箸紵苧菹著藷詛貯躇這邸雎齟勣吊嫡寂摘敵滴狄炙的積笛籍績翟荻謫賊赤跡蹟迪迹適鏑佃佺傳全典前剪塡塼奠專展廛悛戰栓殿氈澱"], +["efa1","煎琠田甸畑癲筌箋箭篆纏詮輾轉鈿銓錢鐫電顚顫餞切截折浙癤竊節絶占岾店漸点粘霑鮎點接摺蝶丁井亭停偵呈姃定幀庭廷征情挺政整旌晶晸柾楨檉正汀淀淨渟湞瀞炡玎珽町睛碇禎程穽精綎艇訂諪貞鄭酊釘鉦鋌錠霆靖"], +["f0a1","靜頂鼎制劑啼堤帝弟悌提梯濟祭第臍薺製諸蹄醍除際霽題齊俎兆凋助嘲弔彫措操早晁曺曹朝條棗槽漕潮照燥爪璪眺祖祚租稠窕粗糟組繰肇藻蚤詔調趙躁造遭釣阻雕鳥族簇足鏃存尊卒拙猝倧宗從悰慫棕淙琮種終綜縱腫"], +["f1a1","踪踵鍾鐘佐坐左座挫罪主住侏做姝胄呪周嗾奏宙州廚晝朱柱株注洲湊澍炷珠疇籌紂紬綢舟蛛註誅走躊輳週酎酒鑄駐竹粥俊儁准埈寯峻晙樽浚準濬焌畯竣蠢逡遵雋駿茁中仲衆重卽櫛楫汁葺增憎曾拯烝甑症繒蒸證贈之只"], +["f2a1","咫地址志持指摯支旨智枝枳止池沚漬知砥祉祗紙肢脂至芝芷蜘誌識贄趾遲直稙稷織職唇嗔塵振搢晉晋桭榛殄津溱珍瑨璡畛疹盡眞瞋秦縉縝臻蔯袗診賑軫辰進鎭陣陳震侄叱姪嫉帙桎瓆疾秩窒膣蛭質跌迭斟朕什執潗緝輯"], +["f3a1","鏶集徵懲澄且侘借叉嗟嵯差次此磋箚茶蹉車遮捉搾着窄錯鑿齪撰澯燦璨瓚竄簒纂粲纘讚贊鑽餐饌刹察擦札紮僭參塹慘慙懺斬站讒讖倉倡創唱娼廠彰愴敞昌昶暢槍滄漲猖瘡窓脹艙菖蒼債埰寀寨彩採砦綵菜蔡采釵冊柵策"], +["f4a1","責凄妻悽處倜刺剔尺慽戚拓擲斥滌瘠脊蹠陟隻仟千喘天川擅泉淺玔穿舛薦賤踐遷釧闡阡韆凸哲喆徹撤澈綴輟轍鐵僉尖沾添甛瞻簽籤詹諂堞妾帖捷牒疊睫諜貼輒廳晴淸聽菁請靑鯖切剃替涕滯締諦逮遞體初剿哨憔抄招梢"], +["f5a1","椒楚樵炒焦硝礁礎秒稍肖艸苕草蕉貂超酢醋醮促囑燭矗蜀觸寸忖村邨叢塚寵悤憁摠總聰蔥銃撮催崔最墜抽推椎楸樞湫皺秋芻萩諏趨追鄒酋醜錐錘鎚雛騶鰍丑畜祝竺筑築縮蓄蹙蹴軸逐春椿瑃出朮黜充忠沖蟲衝衷悴膵萃"], +["f6a1","贅取吹嘴娶就炊翠聚脆臭趣醉驟鷲側仄厠惻測層侈値嗤峙幟恥梔治淄熾痔痴癡稚穉緇緻置致蚩輜雉馳齒則勅飭親七柒漆侵寢枕沈浸琛砧針鍼蟄秤稱快他咤唾墮妥惰打拖朶楕舵陀馱駝倬卓啄坼度托拓擢晫柝濁濯琢琸託"], +["f7a1","鐸呑嘆坦彈憚歎灘炭綻誕奪脫探眈耽貪塔搭榻宕帑湯糖蕩兌台太怠態殆汰泰笞胎苔跆邰颱宅擇澤撑攄兎吐土討慟桶洞痛筒統通堆槌腿褪退頹偸套妬投透鬪慝特闖坡婆巴把播擺杷波派爬琶破罷芭跛頗判坂板版瓣販辦鈑"], +["f8a1","阪八叭捌佩唄悖敗沛浿牌狽稗覇貝彭澎烹膨愎便偏扁片篇編翩遍鞭騙貶坪平枰萍評吠嬖幣廢弊斃肺蔽閉陛佈包匍匏咆哺圃布怖抛抱捕暴泡浦疱砲胞脯苞葡蒲袍褒逋鋪飽鮑幅暴曝瀑爆輻俵剽彪慓杓標漂瓢票表豹飇飄驃"], +["f9a1","品稟楓諷豊風馮彼披疲皮被避陂匹弼必泌珌畢疋筆苾馝乏逼下何厦夏廈昰河瑕荷蝦賀遐霞鰕壑學虐謔鶴寒恨悍旱汗漢澣瀚罕翰閑閒限韓割轄函含咸啣喊檻涵緘艦銜陷鹹合哈盒蛤閤闔陜亢伉姮嫦巷恒抗杭桁沆港缸肛航"], +["faa1","行降項亥偕咳垓奚孩害懈楷海瀣蟹解該諧邂駭骸劾核倖幸杏荇行享向嚮珦鄕響餉饗香噓墟虛許憲櫶獻軒歇險驗奕爀赫革俔峴弦懸晛泫炫玄玹現眩睍絃絢縣舷衒見賢鉉顯孑穴血頁嫌俠協夾峽挾浹狹脅脇莢鋏頰亨兄刑型"], +["fba1","形泂滎瀅灐炯熒珩瑩荊螢衡逈邢鎣馨兮彗惠慧暳蕙蹊醯鞋乎互呼壕壺好岵弧戶扈昊晧毫浩淏湖滸澔濠濩灝狐琥瑚瓠皓祜糊縞胡芦葫蒿虎號蝴護豪鎬頀顥惑或酷婚昏混渾琿魂忽惚笏哄弘汞泓洪烘紅虹訌鴻化和嬅樺火畵"], +["fca1","禍禾花華話譁貨靴廓擴攫確碻穫丸喚奐宦幻患換歡晥桓渙煥環紈還驩鰥活滑猾豁闊凰幌徨恍惶愰慌晃晄榥況湟滉潢煌璜皇篁簧荒蝗遑隍黃匯回廻徊恢悔懷晦會檜淮澮灰獪繪膾茴蛔誨賄劃獲宖橫鐄哮嚆孝效斅曉梟涍淆"], +["fda1","爻肴酵驍侯候厚后吼喉嗅帿後朽煦珝逅勛勳塤壎焄熏燻薰訓暈薨喧暄煊萱卉喙毁彙徽揮暉煇諱輝麾休携烋畦虧恤譎鷸兇凶匈洶胸黑昕欣炘痕吃屹紇訖欠欽歆吸恰洽翕興僖凞喜噫囍姬嬉希憙憘戱晞曦熙熹熺犧禧稀羲詰"] +] diff --git a/node_modules/iconv-lite/encodings/tables/cp950.json b/node_modules/iconv-lite/encodings/tables/cp950.json new file mode 100644 index 00000000..d8bc8717 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/cp950.json @@ -0,0 +1,177 @@ +[ +["0","\u0000",127], +["a140"," ,、。.‧;:?!︰…‥﹐﹑﹒·﹔﹕﹖﹗|–︱—︳╴︴﹏()︵︶{}︷︸〔〕︹︺【】︻︼《》︽︾〈〉︿﹀「」﹁﹂『』﹃﹄﹙﹚"], +["a1a1","﹛﹜﹝﹞‘’“”〝〞‵′#&*※§〃○●△▲◎☆★◇◆□■▽▼㊣℅¯ ̄_ˍ﹉﹊﹍﹎﹋﹌﹟﹠﹡+-×÷±√<>=≦≧≠∞≒≡﹢",4,"~∩∪⊥∠∟⊿㏒㏑∫∮∵∴♀♂⊕⊙↑↓←→↖↗↙↘∥∣/"], +["a240","\∕﹨$¥〒¢£%@℃℉﹩﹪﹫㏕㎜㎝㎞㏎㎡㎎㎏㏄°兙兛兞兝兡兣嗧瓩糎▁",7,"▏▎▍▌▋▊▉┼┴┬┤├▔─│▕┌┐└┘╭"], +["a2a1","╮╰╯═╞╪╡◢◣◥◤╱╲╳0",9,"Ⅰ",9,"〡",8,"十卄卅A",25,"a",21], +["a340","wxyzΑ",16,"Σ",6,"α",16,"σ",6,"ㄅ",10], +["a3a1","ㄐ",25,"˙ˉˊˇˋ"], +["a3e1","€"], +["a440","一乙丁七乃九了二人儿入八几刀刁力匕十卜又三下丈上丫丸凡久么也乞于亡兀刃勺千叉口土士夕大女子孑孓寸小尢尸山川工己已巳巾干廾弋弓才"], +["a4a1","丑丐不中丰丹之尹予云井互五亢仁什仃仆仇仍今介仄元允內六兮公冗凶分切刈勻勾勿化匹午升卅卞厄友及反壬天夫太夭孔少尤尺屯巴幻廿弔引心戈戶手扎支文斗斤方日曰月木欠止歹毋比毛氏水火爪父爻片牙牛犬王丙"], +["a540","世丕且丘主乍乏乎以付仔仕他仗代令仙仞充兄冉冊冬凹出凸刊加功包匆北匝仟半卉卡占卯卮去可古右召叮叩叨叼司叵叫另只史叱台句叭叻四囚外"], +["a5a1","央失奴奶孕它尼巨巧左市布平幼弁弘弗必戊打扔扒扑斥旦朮本未末札正母民氐永汁汀氾犯玄玉瓜瓦甘生用甩田由甲申疋白皮皿目矛矢石示禾穴立丞丟乒乓乩亙交亦亥仿伉伙伊伕伍伐休伏仲件任仰仳份企伋光兇兆先全"], +["a640","共再冰列刑划刎刖劣匈匡匠印危吉吏同吊吐吁吋各向名合吃后吆吒因回囝圳地在圭圬圯圩夙多夷夸妄奸妃好她如妁字存宇守宅安寺尖屹州帆并年"], +["a6a1","式弛忙忖戎戌戍成扣扛托收早旨旬旭曲曳有朽朴朱朵次此死氖汝汗汙江池汐汕污汛汍汎灰牟牝百竹米糸缶羊羽老考而耒耳聿肉肋肌臣自至臼舌舛舟艮色艾虫血行衣西阡串亨位住佇佗佞伴佛何估佐佑伽伺伸佃佔似但佣"], +["a740","作你伯低伶余佝佈佚兌克免兵冶冷別判利刪刨劫助努劬匣即卵吝吭吞吾否呎吧呆呃吳呈呂君吩告吹吻吸吮吵吶吠吼呀吱含吟听囪困囤囫坊坑址坍"], +["a7a1","均坎圾坐坏圻壯夾妝妒妨妞妣妙妖妍妤妓妊妥孝孜孚孛完宋宏尬局屁尿尾岐岑岔岌巫希序庇床廷弄弟彤形彷役忘忌志忍忱快忸忪戒我抄抗抖技扶抉扭把扼找批扳抒扯折扮投抓抑抆改攻攸旱更束李杏材村杜杖杞杉杆杠"], +["a840","杓杗步每求汞沙沁沈沉沅沛汪決沐汰沌汨沖沒汽沃汲汾汴沆汶沍沔沘沂灶灼災灸牢牡牠狄狂玖甬甫男甸皂盯矣私秀禿究系罕肖肓肝肘肛肚育良芒"], +["a8a1","芋芍見角言谷豆豕貝赤走足身車辛辰迂迆迅迄巡邑邢邪邦那酉釆里防阮阱阪阬並乖乳事些亞享京佯依侍佳使佬供例來侃佰併侈佩佻侖佾侏侑佺兔兒兕兩具其典冽函刻券刷刺到刮制剁劾劻卒協卓卑卦卷卸卹取叔受味呵"], +["a940","咖呸咕咀呻呷咄咒咆呼咐呱呶和咚呢周咋命咎固垃坷坪坩坡坦坤坼夜奉奇奈奄奔妾妻委妹妮姑姆姐姍始姓姊妯妳姒姅孟孤季宗定官宜宙宛尚屈居"], +["a9a1","屆岷岡岸岩岫岱岳帘帚帖帕帛帑幸庚店府底庖延弦弧弩往征彿彼忝忠忽念忿怏怔怯怵怖怪怕怡性怩怫怛或戕房戾所承拉拌拄抿拂抹拒招披拓拔拋拈抨抽押拐拙拇拍抵拚抱拘拖拗拆抬拎放斧於旺昔易昌昆昂明昀昏昕昊"], +["aa40","昇服朋杭枋枕東果杳杷枇枝林杯杰板枉松析杵枚枓杼杪杲欣武歧歿氓氛泣注泳沱泌泥河沽沾沼波沫法泓沸泄油況沮泗泅泱沿治泡泛泊沬泯泜泖泠"], +["aaa1","炕炎炒炊炙爬爭爸版牧物狀狎狙狗狐玩玨玟玫玥甽疝疙疚的盂盲直知矽社祀祁秉秈空穹竺糾罔羌羋者肺肥肢肱股肫肩肴肪肯臥臾舍芳芝芙芭芽芟芹花芬芥芯芸芣芰芾芷虎虱初表軋迎返近邵邸邱邶采金長門阜陀阿阻附"], +["ab40","陂隹雨青非亟亭亮信侵侯便俠俑俏保促侶俘俟俊俗侮俐俄係俚俎俞侷兗冒冑冠剎剃削前剌剋則勇勉勃勁匍南卻厚叛咬哀咨哎哉咸咦咳哇哂咽咪品"], +["aba1","哄哈咯咫咱咻咩咧咿囿垂型垠垣垢城垮垓奕契奏奎奐姜姘姿姣姨娃姥姪姚姦威姻孩宣宦室客宥封屎屏屍屋峙峒巷帝帥帟幽庠度建弈弭彥很待徊律徇後徉怒思怠急怎怨恍恰恨恢恆恃恬恫恪恤扁拜挖按拼拭持拮拽指拱拷"], +["ac40","拯括拾拴挑挂政故斫施既春昭映昧是星昨昱昤曷柿染柱柔某柬架枯柵柩柯柄柑枴柚查枸柏柞柳枰柙柢柝柒歪殃殆段毒毗氟泉洋洲洪流津洌洱洞洗"], +["aca1","活洽派洶洛泵洹洧洸洩洮洵洎洫炫為炳炬炯炭炸炮炤爰牲牯牴狩狠狡玷珊玻玲珍珀玳甚甭畏界畎畋疫疤疥疢疣癸皆皇皈盈盆盃盅省盹相眉看盾盼眇矜砂研砌砍祆祉祈祇禹禺科秒秋穿突竿竽籽紂紅紀紉紇約紆缸美羿耄"], +["ad40","耐耍耑耶胖胥胚胃胄背胡胛胎胞胤胝致舢苧范茅苣苛苦茄若茂茉苒苗英茁苜苔苑苞苓苟苯茆虐虹虻虺衍衫要觔計訂訃貞負赴赳趴軍軌述迦迢迪迥"], +["ada1","迭迫迤迨郊郎郁郃酋酊重閂限陋陌降面革韋韭音頁風飛食首香乘亳倌倍倣俯倦倥俸倩倖倆值借倚倒們俺倀倔倨俱倡個候倘俳修倭倪俾倫倉兼冤冥冢凍凌准凋剖剜剔剛剝匪卿原厝叟哨唐唁唷哼哥哲唆哺唔哩哭員唉哮哪"], +["ae40","哦唧唇哽唏圃圄埂埔埋埃堉夏套奘奚娑娘娜娟娛娓姬娠娣娩娥娌娉孫屘宰害家宴宮宵容宸射屑展屐峭峽峻峪峨峰島崁峴差席師庫庭座弱徒徑徐恙"], +["aea1","恣恥恐恕恭恩息悄悟悚悍悔悌悅悖扇拳挈拿捎挾振捕捂捆捏捉挺捐挽挪挫挨捍捌效敉料旁旅時晉晏晃晒晌晅晁書朔朕朗校核案框桓根桂桔栩梳栗桌桑栽柴桐桀格桃株桅栓栘桁殊殉殷氣氧氨氦氤泰浪涕消涇浦浸海浙涓"], +["af40","浬涉浮浚浴浩涌涊浹涅浥涔烊烘烤烙烈烏爹特狼狹狽狸狷玆班琉珮珠珪珞畔畝畜畚留疾病症疲疳疽疼疹痂疸皋皰益盍盎眩真眠眨矩砰砧砸砝破砷"], +["afa1","砥砭砠砟砲祕祐祠祟祖神祝祗祚秤秣秧租秦秩秘窄窈站笆笑粉紡紗紋紊素索純紐紕級紜納紙紛缺罟羔翅翁耆耘耕耙耗耽耿胱脂胰脅胭胴脆胸胳脈能脊胼胯臭臬舀舐航舫舨般芻茫荒荔荊茸荐草茵茴荏茲茹茶茗荀茱茨荃"], +["b040","虔蚊蚪蚓蚤蚩蚌蚣蚜衰衷袁袂衽衹記訐討訌訕訊託訓訖訏訑豈豺豹財貢起躬軒軔軏辱送逆迷退迺迴逃追逅迸邕郡郝郢酒配酌釘針釗釜釙閃院陣陡"], +["b0a1","陛陝除陘陞隻飢馬骨高鬥鬲鬼乾偺偽停假偃偌做偉健偶偎偕偵側偷偏倏偯偭兜冕凰剪副勒務勘動匐匏匙匿區匾參曼商啪啦啄啞啡啃啊唱啖問啕唯啤唸售啜唬啣唳啁啗圈國圉域堅堊堆埠埤基堂堵執培夠奢娶婁婉婦婪婀"], +["b140","娼婢婚婆婊孰寇寅寄寂宿密尉專將屠屜屝崇崆崎崛崖崢崑崩崔崙崤崧崗巢常帶帳帷康庸庶庵庾張強彗彬彩彫得徙從徘御徠徜恿患悉悠您惋悴惦悽"], +["b1a1","情悻悵惜悼惘惕惆惟悸惚惇戚戛扈掠控捲掖探接捷捧掘措捱掩掉掃掛捫推掄授掙採掬排掏掀捻捩捨捺敝敖救教敗啟敏敘敕敔斜斛斬族旋旌旎晝晚晤晨晦晞曹勗望梁梯梢梓梵桿桶梱梧梗械梃棄梭梆梅梔條梨梟梡梂欲殺"], +["b240","毫毬氫涎涼淳淙液淡淌淤添淺清淇淋涯淑涮淞淹涸混淵淅淒渚涵淚淫淘淪深淮淨淆淄涪淬涿淦烹焉焊烽烯爽牽犁猜猛猖猓猙率琅琊球理現琍瓠瓶"], +["b2a1","瓷甜產略畦畢異疏痔痕疵痊痍皎盔盒盛眷眾眼眶眸眺硫硃硎祥票祭移窒窕笠笨笛第符笙笞笮粒粗粕絆絃統紮紹紼絀細紳組累終紲紱缽羞羚翌翎習耜聊聆脯脖脣脫脩脰脤舂舵舷舶船莎莞莘荸莢莖莽莫莒莊莓莉莠荷荻荼"], +["b340","莆莧處彪蛇蛀蚶蛄蚵蛆蛋蚱蚯蛉術袞袈被袒袖袍袋覓規訪訝訣訥許設訟訛訢豉豚販責貫貨貪貧赧赦趾趺軛軟這逍通逗連速逝逐逕逞造透逢逖逛途"], +["b3a1","部郭都酗野釵釦釣釧釭釩閉陪陵陳陸陰陴陶陷陬雀雪雩章竟頂頃魚鳥鹵鹿麥麻傢傍傅備傑傀傖傘傚最凱割剴創剩勞勝勛博厥啻喀喧啼喊喝喘喂喜喪喔喇喋喃喳單喟唾喲喚喻喬喱啾喉喫喙圍堯堪場堤堰報堡堝堠壹壺奠"], +["b440","婷媚婿媒媛媧孳孱寒富寓寐尊尋就嵌嵐崴嵇巽幅帽幀幃幾廊廁廂廄弼彭復循徨惑惡悲悶惠愜愣惺愕惰惻惴慨惱愎惶愉愀愒戟扉掣掌描揀揩揉揆揍"], +["b4a1","插揣提握揖揭揮捶援揪換摒揚揹敞敦敢散斑斐斯普晰晴晶景暑智晾晷曾替期朝棺棕棠棘棗椅棟棵森棧棹棒棲棣棋棍植椒椎棉棚楮棻款欺欽殘殖殼毯氮氯氬港游湔渡渲湧湊渠渥渣減湛湘渤湖湮渭渦湯渴湍渺測湃渝渾滋"], +["b540","溉渙湎湣湄湲湩湟焙焚焦焰無然煮焜牌犄犀猶猥猴猩琺琪琳琢琥琵琶琴琯琛琦琨甥甦畫番痢痛痣痙痘痞痠登發皖皓皴盜睏短硝硬硯稍稈程稅稀窘"], +["b5a1","窗窖童竣等策筆筐筒答筍筋筏筑粟粥絞結絨絕紫絮絲絡給絢絰絳善翔翕耋聒肅腕腔腋腑腎脹腆脾腌腓腴舒舜菩萃菸萍菠菅萋菁華菱菴著萊菰萌菌菽菲菊萸萎萄菜萇菔菟虛蛟蛙蛭蛔蛛蛤蛐蛞街裁裂袱覃視註詠評詞証詁"], +["b640","詔詛詐詆訴診訶詖象貂貯貼貳貽賁費賀貴買貶貿貸越超趁跎距跋跚跑跌跛跆軻軸軼辜逮逵週逸進逶鄂郵鄉郾酣酥量鈔鈕鈣鈉鈞鈍鈐鈇鈑閔閏開閑"], +["b6a1","間閒閎隊階隋陽隅隆隍陲隄雁雅雄集雇雯雲韌項順須飧飪飯飩飲飭馮馭黃黍黑亂傭債傲傳僅傾催傷傻傯僇剿剷剽募勦勤勢勣匯嗟嗨嗓嗦嗎嗜嗇嗑嗣嗤嗯嗚嗡嗅嗆嗥嗉園圓塞塑塘塗塚塔填塌塭塊塢塒塋奧嫁嫉嫌媾媽媼"], +["b740","媳嫂媲嵩嵯幌幹廉廈弒彙徬微愚意慈感想愛惹愁愈慎慌慄慍愾愴愧愍愆愷戡戢搓搾搞搪搭搽搬搏搜搔損搶搖搗搆敬斟新暗暉暇暈暖暄暘暍會榔業"], +["b7a1","楚楷楠楔極椰概楊楨楫楞楓楹榆楝楣楛歇歲毀殿毓毽溢溯滓溶滂源溝滇滅溥溘溼溺溫滑準溜滄滔溪溧溴煎煙煩煤煉照煜煬煦煌煥煞煆煨煖爺牒猷獅猿猾瑯瑚瑕瑟瑞瑁琿瑙瑛瑜當畸瘀痰瘁痲痱痺痿痴痳盞盟睛睫睦睞督"], +["b840","睹睪睬睜睥睨睢矮碎碰碗碘碌碉硼碑碓硿祺祿禁萬禽稜稚稠稔稟稞窟窠筷節筠筮筧粱粳粵經絹綑綁綏絛置罩罪署義羨群聖聘肆肄腱腰腸腥腮腳腫"], +["b8a1","腹腺腦舅艇蒂葷落萱葵葦葫葉葬葛萼萵葡董葩葭葆虞虜號蛹蜓蜈蜇蜀蛾蛻蜂蜃蜆蜊衙裟裔裙補裘裝裡裊裕裒覜解詫該詳試詩詰誇詼詣誠話誅詭詢詮詬詹詻訾詨豢貊貉賊資賈賄貲賃賂賅跡跟跨路跳跺跪跤跦躲較載軾輊"], +["b940","辟農運遊道遂達逼違遐遇遏過遍遑逾遁鄒鄗酬酪酩釉鈷鉗鈸鈽鉀鈾鉛鉋鉤鉑鈴鉉鉍鉅鈹鈿鉚閘隘隔隕雍雋雉雊雷電雹零靖靴靶預頑頓頊頒頌飼飴"], +["b9a1","飽飾馳馱馴髡鳩麂鼎鼓鼠僧僮僥僖僭僚僕像僑僱僎僩兢凳劃劂匱厭嗾嘀嘛嘗嗽嘔嘆嘉嘍嘎嗷嘖嘟嘈嘐嗶團圖塵塾境墓墊塹墅塽壽夥夢夤奪奩嫡嫦嫩嫗嫖嫘嫣孵寞寧寡寥實寨寢寤察對屢嶄嶇幛幣幕幗幔廓廖弊彆彰徹慇"], +["ba40","愿態慷慢慣慟慚慘慵截撇摘摔撤摸摟摺摑摧搴摭摻敲斡旗旖暢暨暝榜榨榕槁榮槓構榛榷榻榫榴槐槍榭槌榦槃榣歉歌氳漳演滾漓滴漩漾漠漬漏漂漢"], +["baa1","滿滯漆漱漸漲漣漕漫漯澈漪滬漁滲滌滷熔熙煽熊熄熒爾犒犖獄獐瑤瑣瑪瑰瑭甄疑瘧瘍瘋瘉瘓盡監瞄睽睿睡磁碟碧碳碩碣禎福禍種稱窪窩竭端管箕箋筵算箝箔箏箸箇箄粹粽精綻綰綜綽綾綠緊綴網綱綺綢綿綵綸維緒緇綬"], +["bb40","罰翠翡翟聞聚肇腐膀膏膈膊腿膂臧臺與舔舞艋蓉蒿蓆蓄蒙蒞蒲蒜蓋蒸蓀蓓蒐蒼蓑蓊蜿蜜蜻蜢蜥蜴蜘蝕蜷蜩裳褂裴裹裸製裨褚裯誦誌語誣認誡誓誤"], +["bba1","說誥誨誘誑誚誧豪貍貌賓賑賒赫趙趕跼輔輒輕輓辣遠遘遜遣遙遞遢遝遛鄙鄘鄞酵酸酷酴鉸銀銅銘銖鉻銓銜銨鉼銑閡閨閩閣閥閤隙障際雌雒需靼鞅韶頗領颯颱餃餅餌餉駁骯骰髦魁魂鳴鳶鳳麼鼻齊億儀僻僵價儂儈儉儅凜"], +["bc40","劇劈劉劍劊勰厲嘮嘻嘹嘲嘿嘴嘩噓噎噗噴嘶嘯嘰墀墟增墳墜墮墩墦奭嬉嫻嬋嫵嬌嬈寮寬審寫層履嶝嶔幢幟幡廢廚廟廝廣廠彈影德徵慶慧慮慝慕憂"], +["bca1","慼慰慫慾憧憐憫憎憬憚憤憔憮戮摩摯摹撞撲撈撐撰撥撓撕撩撒撮播撫撚撬撙撢撳敵敷數暮暫暴暱樣樟槨樁樞標槽模樓樊槳樂樅槭樑歐歎殤毅毆漿潼澄潑潦潔澆潭潛潸潮澎潺潰潤澗潘滕潯潠潟熟熬熱熨牖犛獎獗瑩璋璃"], +["bd40","瑾璀畿瘠瘩瘟瘤瘦瘡瘢皚皺盤瞎瞇瞌瞑瞋磋磅確磊碾磕碼磐稿稼穀稽稷稻窯窮箭箱範箴篆篇篁箠篌糊締練緯緻緘緬緝編緣線緞緩綞緙緲緹罵罷羯"], +["bda1","翩耦膛膜膝膠膚膘蔗蔽蔚蓮蔬蔭蔓蔑蔣蔡蔔蓬蔥蓿蔆螂蝴蝶蝠蝦蝸蝨蝙蝗蝌蝓衛衝褐複褒褓褕褊誼諒談諄誕請諸課諉諂調誰論諍誶誹諛豌豎豬賠賞賦賤賬賭賢賣賜質賡赭趟趣踫踐踝踢踏踩踟踡踞躺輝輛輟輩輦輪輜輞"], +["be40","輥適遮遨遭遷鄰鄭鄧鄱醇醉醋醃鋅銻銷鋪銬鋤鋁銳銼鋒鋇鋰銲閭閱霄霆震霉靠鞍鞋鞏頡頫頜颳養餓餒餘駝駐駟駛駑駕駒駙骷髮髯鬧魅魄魷魯鴆鴉"], +["bea1","鴃麩麾黎墨齒儒儘儔儐儕冀冪凝劑劓勳噙噫噹噩噤噸噪器噥噱噯噬噢噶壁墾壇壅奮嬝嬴學寰導彊憲憑憩憊懍憶憾懊懈戰擅擁擋撻撼據擄擇擂操撿擒擔撾整曆曉暹曄曇暸樽樸樺橙橫橘樹橄橢橡橋橇樵機橈歙歷氅濂澱澡"], +["bf40","濃澤濁澧澳激澹澶澦澠澴熾燉燐燒燈燕熹燎燙燜燃燄獨璜璣璘璟璞瓢甌甍瘴瘸瘺盧盥瞠瞞瞟瞥磨磚磬磧禦積穎穆穌穋窺篙簑築篤篛篡篩篦糕糖縊"], +["bfa1","縑縈縛縣縞縝縉縐罹羲翰翱翮耨膳膩膨臻興艘艙蕊蕙蕈蕨蕩蕃蕉蕭蕪蕞螃螟螞螢融衡褪褲褥褫褡親覦諦諺諫諱謀諜諧諮諾謁謂諷諭諳諶諼豫豭貓賴蹄踱踴蹂踹踵輻輯輸輳辨辦遵遴選遲遼遺鄴醒錠錶鋸錳錯錢鋼錫錄錚"], +["c040","錐錦錡錕錮錙閻隧隨險雕霎霑霖霍霓霏靛靜靦鞘頰頸頻頷頭頹頤餐館餞餛餡餚駭駢駱骸骼髻髭鬨鮑鴕鴣鴦鴨鴒鴛默黔龍龜優償儡儲勵嚎嚀嚐嚅嚇"], +["c0a1","嚏壕壓壑壎嬰嬪嬤孺尷屨嶼嶺嶽嶸幫彌徽應懂懇懦懋戲戴擎擊擘擠擰擦擬擱擢擭斂斃曙曖檀檔檄檢檜櫛檣橾檗檐檠歜殮毚氈濘濱濟濠濛濤濫濯澀濬濡濩濕濮濰燧營燮燦燥燭燬燴燠爵牆獰獲璩環璦璨癆療癌盪瞳瞪瞰瞬"], +["c140","瞧瞭矯磷磺磴磯礁禧禪穗窿簇簍篾篷簌篠糠糜糞糢糟糙糝縮績繆縷縲繃縫總縱繅繁縴縹繈縵縿縯罄翳翼聱聲聰聯聳臆臃膺臂臀膿膽臉膾臨舉艱薪"], +["c1a1","薄蕾薜薑薔薯薛薇薨薊虧蟀蟑螳蟒蟆螫螻螺蟈蟋褻褶襄褸褽覬謎謗謙講謊謠謝謄謐豁谿豳賺賽購賸賻趨蹉蹋蹈蹊轄輾轂轅輿避遽還邁邂邀鄹醣醞醜鍍鎂錨鍵鍊鍥鍋錘鍾鍬鍛鍰鍚鍔闊闋闌闈闆隱隸雖霜霞鞠韓顆颶餵騁"], +["c240","駿鮮鮫鮪鮭鴻鴿麋黏點黜黝黛鼾齋叢嚕嚮壙壘嬸彝懣戳擴擲擾攆擺擻擷斷曜朦檳檬櫃檻檸櫂檮檯歟歸殯瀉瀋濾瀆濺瀑瀏燻燼燾燸獷獵璧璿甕癖癘"], +["c2a1","癒瞽瞿瞻瞼礎禮穡穢穠竄竅簫簧簪簞簣簡糧織繕繞繚繡繒繙罈翹翻職聶臍臏舊藏薩藍藐藉薰薺薹薦蟯蟬蟲蟠覆覲觴謨謹謬謫豐贅蹙蹣蹦蹤蹟蹕軀轉轍邇邃邈醫醬釐鎔鎊鎖鎢鎳鎮鎬鎰鎘鎚鎗闔闖闐闕離雜雙雛雞霤鞣鞦"], +["c340","鞭韹額顏題顎顓颺餾餿餽餮馥騎髁鬃鬆魏魎魍鯊鯉鯽鯈鯀鵑鵝鵠黠鼕鼬儳嚥壞壟壢寵龐廬懲懷懶懵攀攏曠曝櫥櫝櫚櫓瀛瀟瀨瀚瀝瀕瀘爆爍牘犢獸"], +["c3a1","獺璽瓊瓣疇疆癟癡矇礙禱穫穩簾簿簸簽簷籀繫繭繹繩繪羅繳羶羹羸臘藩藝藪藕藤藥藷蟻蠅蠍蟹蟾襠襟襖襞譁譜識證譚譎譏譆譙贈贊蹼蹲躇蹶蹬蹺蹴轔轎辭邊邋醱醮鏡鏑鏟鏃鏈鏜鏝鏖鏢鏍鏘鏤鏗鏨關隴難霪霧靡韜韻類"], +["c440","願顛颼饅饉騖騙鬍鯨鯧鯖鯛鶉鵡鵲鵪鵬麒麗麓麴勸嚨嚷嚶嚴嚼壤孀孃孽寶巉懸懺攘攔攙曦朧櫬瀾瀰瀲爐獻瓏癢癥礦礪礬礫竇競籌籃籍糯糰辮繽繼"], +["c4a1","纂罌耀臚艦藻藹蘑藺蘆蘋蘇蘊蠔蠕襤覺觸議譬警譯譟譫贏贍躉躁躅躂醴釋鐘鐃鏽闡霰飄饒饑馨騫騰騷騵鰓鰍鹹麵黨鼯齟齣齡儷儸囁囀囂夔屬巍懼懾攝攜斕曩櫻欄櫺殲灌爛犧瓖瓔癩矓籐纏續羼蘗蘭蘚蠣蠢蠡蠟襪襬覽譴"], +["c540","護譽贓躊躍躋轟辯醺鐮鐳鐵鐺鐸鐲鐫闢霸霹露響顧顥饗驅驃驀騾髏魔魑鰭鰥鶯鶴鷂鶸麝黯鼙齜齦齧儼儻囈囊囉孿巔巒彎懿攤權歡灑灘玀瓤疊癮癬"], +["c5a1","禳籠籟聾聽臟襲襯觼讀贖贗躑躓轡酈鑄鑑鑒霽霾韃韁顫饕驕驍髒鬚鱉鰱鰾鰻鷓鷗鼴齬齪龔囌巖戀攣攫攪曬欐瓚竊籤籣籥纓纖纔臢蘸蘿蠱變邐邏鑣鑠鑤靨顯饜驚驛驗髓體髑鱔鱗鱖鷥麟黴囑壩攬灞癱癲矗罐羈蠶蠹衢讓讒"], +["c640","讖艷贛釀鑪靂靈靄韆顰驟鬢魘鱟鷹鷺鹼鹽鼇齷齲廳欖灣籬籮蠻觀躡釁鑲鑰顱饞髖鬣黌灤矚讚鑷韉驢驥纜讜躪釅鑽鑾鑼鱷鱸黷豔鑿鸚爨驪鬱鸛鸞籲"], +["c940","乂乜凵匚厂万丌乇亍囗兀屮彳丏冇与丮亓仂仉仈冘勼卬厹圠夃夬尐巿旡殳毌气爿丱丼仨仜仩仡仝仚刌匜卌圢圣夗夯宁宄尒尻屴屳帄庀庂忉戉扐氕"], +["c9a1","氶汃氿氻犮犰玊禸肊阞伎优伬仵伔仱伀价伈伝伂伅伢伓伄仴伒冱刓刉刐劦匢匟卍厊吇囡囟圮圪圴夼妀奼妅奻奾奷奿孖尕尥屼屺屻屾巟幵庄异弚彴忕忔忏扜扞扤扡扦扢扙扠扚扥旯旮朾朹朸朻机朿朼朳氘汆汒汜汏汊汔汋"], +["ca40","汌灱牞犴犵玎甪癿穵网艸艼芀艽艿虍襾邙邗邘邛邔阢阤阠阣佖伻佢佉体佤伾佧佒佟佁佘伭伳伿佡冏冹刜刞刡劭劮匉卣卲厎厏吰吷吪呔呅吙吜吥吘"], +["caa1","吽呏呁吨吤呇囮囧囥坁坅坌坉坋坒夆奀妦妘妠妗妎妢妐妏妧妡宎宒尨尪岍岏岈岋岉岒岊岆岓岕巠帊帎庋庉庌庈庍弅弝彸彶忒忑忐忭忨忮忳忡忤忣忺忯忷忻怀忴戺抃抌抎抏抔抇扱扻扺扰抁抈扷扽扲扴攷旰旴旳旲旵杅杇"], +["cb40","杙杕杌杈杝杍杚杋毐氙氚汸汧汫沄沋沏汱汯汩沚汭沇沕沜汦汳汥汻沎灴灺牣犿犽狃狆狁犺狅玕玗玓玔玒町甹疔疕皁礽耴肕肙肐肒肜芐芏芅芎芑芓"], +["cba1","芊芃芄豸迉辿邟邡邥邞邧邠阰阨阯阭丳侘佼侅佽侀侇佶佴侉侄佷佌侗佪侚佹侁佸侐侜侔侞侒侂侕佫佮冞冼冾刵刲刳剆刱劼匊匋匼厒厔咇呿咁咑咂咈呫呺呾呥呬呴呦咍呯呡呠咘呣呧呤囷囹坯坲坭坫坱坰坶垀坵坻坳坴坢"], +["cc40","坨坽夌奅妵妺姏姎妲姌姁妶妼姃姖妱妽姀姈妴姇孢孥宓宕屄屇岮岤岠岵岯岨岬岟岣岭岢岪岧岝岥岶岰岦帗帔帙弨弢弣弤彔徂彾彽忞忥怭怦怙怲怋"], +["cca1","怴怊怗怳怚怞怬怢怍怐怮怓怑怌怉怜戔戽抭抴拑抾抪抶拊抮抳抯抻抩抰抸攽斨斻昉旼昄昒昈旻昃昋昍昅旽昑昐曶朊枅杬枎枒杶杻枘枆构杴枍枌杺枟枑枙枃杽极杸杹枔欥殀歾毞氝沓泬泫泮泙沶泔沭泧沷泐泂沺泃泆泭泲"], +["cd40","泒泝沴沊沝沀泞泀洰泍泇沰泹泏泩泑炔炘炅炓炆炄炑炖炂炚炃牪狖狋狘狉狜狒狔狚狌狑玤玡玭玦玢玠玬玝瓝瓨甿畀甾疌疘皯盳盱盰盵矸矼矹矻矺"], +["cda1","矷祂礿秅穸穻竻籵糽耵肏肮肣肸肵肭舠芠苀芫芚芘芛芵芧芮芼芞芺芴芨芡芩苂芤苃芶芢虰虯虭虮豖迒迋迓迍迖迕迗邲邴邯邳邰阹阽阼阺陃俍俅俓侲俉俋俁俔俜俙侻侳俛俇俖侺俀侹俬剄剉勀勂匽卼厗厖厙厘咺咡咭咥哏"], +["ce40","哃茍咷咮哖咶哅哆咠呰咼咢咾呲哞咰垵垞垟垤垌垗垝垛垔垘垏垙垥垚垕壴复奓姡姞姮娀姱姝姺姽姼姶姤姲姷姛姩姳姵姠姾姴姭宨屌峐峘峌峗峋峛"], +["cea1","峞峚峉峇峊峖峓峔峏峈峆峎峟峸巹帡帢帣帠帤庰庤庢庛庣庥弇弮彖徆怷怹恔恲恞恅恓恇恉恛恌恀恂恟怤恄恘恦恮扂扃拏挍挋拵挎挃拫拹挏挌拸拶挀挓挔拺挕拻拰敁敃斪斿昶昡昲昵昜昦昢昳昫昺昝昴昹昮朏朐柁柲柈枺"], +["cf40","柜枻柸柘柀枷柅柫柤柟枵柍枳柷柶柮柣柂枹柎柧柰枲柼柆柭柌枮柦柛柺柉柊柃柪柋欨殂殄殶毖毘毠氠氡洨洴洭洟洼洿洒洊泚洳洄洙洺洚洑洀洝浂"], +["cfa1","洁洘洷洃洏浀洇洠洬洈洢洉洐炷炟炾炱炰炡炴炵炩牁牉牊牬牰牳牮狊狤狨狫狟狪狦狣玅珌珂珈珅玹玶玵玴珫玿珇玾珃珆玸珋瓬瓮甮畇畈疧疪癹盄眈眃眄眅眊盷盻盺矧矨砆砑砒砅砐砏砎砉砃砓祊祌祋祅祄秕种秏秖秎窀"], +["d040","穾竑笀笁籺籸籹籿粀粁紃紈紁罘羑羍羾耇耎耏耔耷胘胇胠胑胈胂胐胅胣胙胜胊胕胉胏胗胦胍臿舡芔苙苾苹茇苨茀苕茺苫苖苴苬苡苲苵茌苻苶苰苪"], +["d0a1","苤苠苺苳苭虷虴虼虳衁衎衧衪衩觓訄訇赲迣迡迮迠郱邽邿郕郅邾郇郋郈釔釓陔陏陑陓陊陎倞倅倇倓倢倰倛俵俴倳倷倬俶俷倗倜倠倧倵倯倱倎党冔冓凊凄凅凈凎剡剚剒剞剟剕剢勍匎厞唦哢唗唒哧哳哤唚哿唄唈哫唑唅哱"], +["d140","唊哻哷哸哠唎唃唋圁圂埌堲埕埒垺埆垽垼垸垶垿埇埐垹埁夎奊娙娖娭娮娕娏娗娊娞娳孬宧宭宬尃屖屔峬峿峮峱峷崀峹帩帨庨庮庪庬弳弰彧恝恚恧"], +["d1a1","恁悢悈悀悒悁悝悃悕悛悗悇悜悎戙扆拲挐捖挬捄捅挶捃揤挹捋捊挼挩捁挴捘捔捙挭捇挳捚捑挸捗捀捈敊敆旆旃旄旂晊晟晇晑朒朓栟栚桉栲栳栻桋桏栖栱栜栵栫栭栯桎桄栴栝栒栔栦栨栮桍栺栥栠欬欯欭欱欴歭肂殈毦毤"], +["d240","毨毣毢毧氥浺浣浤浶洍浡涒浘浢浭浯涑涍淯浿涆浞浧浠涗浰浼浟涂涘洯浨涋浾涀涄洖涃浻浽浵涐烜烓烑烝烋缹烢烗烒烞烠烔烍烅烆烇烚烎烡牂牸"], +["d2a1","牷牶猀狺狴狾狶狳狻猁珓珙珥珖玼珧珣珩珜珒珛珔珝珚珗珘珨瓞瓟瓴瓵甡畛畟疰痁疻痄痀疿疶疺皊盉眝眛眐眓眒眣眑眕眙眚眢眧砣砬砢砵砯砨砮砫砡砩砳砪砱祔祛祏祜祓祒祑秫秬秠秮秭秪秜秞秝窆窉窅窋窌窊窇竘笐"], +["d340","笄笓笅笏笈笊笎笉笒粄粑粊粌粈粍粅紞紝紑紎紘紖紓紟紒紏紌罜罡罞罠罝罛羖羒翃翂翀耖耾耹胺胲胹胵脁胻脀舁舯舥茳茭荄茙荑茥荖茿荁茦茜茢"], +["d3a1","荂荎茛茪茈茼荍茖茤茠茷茯茩荇荅荌荓茞茬荋茧荈虓虒蚢蚨蚖蚍蚑蚞蚇蚗蚆蚋蚚蚅蚥蚙蚡蚧蚕蚘蚎蚝蚐蚔衃衄衭衵衶衲袀衱衿衯袃衾衴衼訒豇豗豻貤貣赶赸趵趷趶軑軓迾迵适迿迻逄迼迶郖郠郙郚郣郟郥郘郛郗郜郤酐"], +["d440","酎酏釕釢釚陜陟隼飣髟鬯乿偰偪偡偞偠偓偋偝偲偈偍偁偛偊偢倕偅偟偩偫偣偤偆偀偮偳偗偑凐剫剭剬剮勖勓匭厜啵啶唼啍啐唴唪啑啢唶唵唰啒啅"], +["d4a1","唌唲啥啎唹啈唭唻啀啋圊圇埻堔埢埶埜埴堀埭埽堈埸堋埳埏堇埮埣埲埥埬埡堎埼堐埧堁堌埱埩埰堍堄奜婠婘婕婧婞娸娵婭婐婟婥婬婓婤婗婃婝婒婄婛婈媎娾婍娹婌婰婩婇婑婖婂婜孲孮寁寀屙崞崋崝崚崠崌崨崍崦崥崏"], +["d540","崰崒崣崟崮帾帴庱庴庹庲庳弶弸徛徖徟悊悐悆悾悰悺惓惔惏惤惙惝惈悱惛悷惊悿惃惍惀挲捥掊掂捽掽掞掭掝掗掫掎捯掇掐据掯捵掜捭掮捼掤挻掟"], +["d5a1","捸掅掁掑掍捰敓旍晥晡晛晙晜晢朘桹梇梐梜桭桮梮梫楖桯梣梬梩桵桴梲梏桷梒桼桫桲梪梀桱桾梛梖梋梠梉梤桸桻梑梌梊桽欶欳欷欸殑殏殍殎殌氪淀涫涴涳湴涬淩淢涷淶淔渀淈淠淟淖涾淥淜淝淛淴淊涽淭淰涺淕淂淏淉"], +["d640","淐淲淓淽淗淍淣涻烺焍烷焗烴焌烰焄烳焐烼烿焆焓焀烸烶焋焂焎牾牻牼牿猝猗猇猑猘猊猈狿猏猞玈珶珸珵琄琁珽琇琀珺珼珿琌琋珴琈畤畣痎痒痏"], +["d6a1","痋痌痑痐皏皉盓眹眯眭眱眲眴眳眽眥眻眵硈硒硉硍硊硌砦硅硐祤祧祩祪祣祫祡离秺秸秶秷窏窔窐笵筇笴笥笰笢笤笳笘笪笝笱笫笭笯笲笸笚笣粔粘粖粣紵紽紸紶紺絅紬紩絁絇紾紿絊紻紨罣羕羜羝羛翊翋翍翐翑翇翏翉耟"], +["d740","耞耛聇聃聈脘脥脙脛脭脟脬脞脡脕脧脝脢舑舸舳舺舴舲艴莐莣莨莍荺荳莤荴莏莁莕莙荵莔莩荽莃莌莝莛莪莋荾莥莯莈莗莰荿莦莇莮荶莚虙虖蚿蚷"], +["d7a1","蛂蛁蛅蚺蚰蛈蚹蚳蚸蛌蚴蚻蚼蛃蚽蚾衒袉袕袨袢袪袚袑袡袟袘袧袙袛袗袤袬袌袓袎覂觖觙觕訰訧訬訞谹谻豜豝豽貥赽赻赹趼跂趹趿跁軘軞軝軜軗軠軡逤逋逑逜逌逡郯郪郰郴郲郳郔郫郬郩酖酘酚酓酕釬釴釱釳釸釤釹釪"], +["d840","釫釷釨釮镺閆閈陼陭陫陱陯隿靪頄飥馗傛傕傔傞傋傣傃傌傎傝偨傜傒傂傇兟凔匒匑厤厧喑喨喥喭啷噅喢喓喈喏喵喁喣喒喤啽喌喦啿喕喡喎圌堩堷"], +["d8a1","堙堞堧堣堨埵塈堥堜堛堳堿堶堮堹堸堭堬堻奡媯媔媟婺媢媞婸媦婼媥媬媕媮娷媄媊媗媃媋媩婻婽媌媜媏媓媝寪寍寋寔寑寊寎尌尰崷嵃嵫嵁嵋崿崵嵑嵎嵕崳崺嵒崽崱嵙嵂崹嵉崸崼崲崶嵀嵅幄幁彘徦徥徫惉悹惌惢惎惄愔"], +["d940","惲愊愖愅惵愓惸惼惾惁愃愘愝愐惿愄愋扊掔掱掰揎揥揨揯揃撝揳揊揠揶揕揲揵摡揟掾揝揜揄揘揓揂揇揌揋揈揰揗揙攲敧敪敤敜敨敥斌斝斞斮旐旒"], +["d9a1","晼晬晻暀晱晹晪晲朁椌棓椄棜椪棬棪棱椏棖棷棫棤棶椓椐棳棡椇棌椈楰梴椑棯棆椔棸棐棽棼棨椋椊椗棎棈棝棞棦棴棑椆棔棩椕椥棇欹欻欿欼殔殗殙殕殽毰毲毳氰淼湆湇渟湉溈渼渽湅湢渫渿湁湝湳渜渳湋湀湑渻渃渮湞"], +["da40","湨湜湡渱渨湠湱湫渹渢渰湓湥渧湸湤湷湕湹湒湦渵渶湚焠焞焯烻焮焱焣焥焢焲焟焨焺焛牋牚犈犉犆犅犋猒猋猰猢猱猳猧猲猭猦猣猵猌琮琬琰琫琖"], +["daa1","琚琡琭琱琤琣琝琩琠琲瓻甯畯畬痧痚痡痦痝痟痤痗皕皒盚睆睇睄睍睅睊睎睋睌矞矬硠硤硥硜硭硱硪确硰硩硨硞硢祴祳祲祰稂稊稃稌稄窙竦竤筊笻筄筈筌筎筀筘筅粢粞粨粡絘絯絣絓絖絧絪絏絭絜絫絒絔絩絑絟絎缾缿罥"], +["db40","罦羢羠羡翗聑聏聐胾胔腃腊腒腏腇脽腍脺臦臮臷臸臹舄舼舽舿艵茻菏菹萣菀菨萒菧菤菼菶萐菆菈菫菣莿萁菝菥菘菿菡菋菎菖菵菉萉萏菞萑萆菂菳"], +["dba1","菕菺菇菑菪萓菃菬菮菄菻菗菢萛菛菾蛘蛢蛦蛓蛣蛚蛪蛝蛫蛜蛬蛩蛗蛨蛑衈衖衕袺裗袹袸裀袾袶袼袷袽袲褁裉覕覘覗觝觚觛詎詍訹詙詀詗詘詄詅詒詈詑詊詌詏豟貁貀貺貾貰貹貵趄趀趉跘跓跍跇跖跜跏跕跙跈跗跅軯軷軺"], +["dc40","軹軦軮軥軵軧軨軶軫軱軬軴軩逭逴逯鄆鄬鄄郿郼鄈郹郻鄁鄀鄇鄅鄃酡酤酟酢酠鈁鈊鈥鈃鈚鈦鈏鈌鈀鈒釿釽鈆鈄鈧鈂鈜鈤鈙鈗鈅鈖镻閍閌閐隇陾隈"], +["dca1","隉隃隀雂雈雃雱雰靬靰靮頇颩飫鳦黹亃亄亶傽傿僆傮僄僊傴僈僂傰僁傺傱僋僉傶傸凗剺剸剻剼嗃嗛嗌嗐嗋嗊嗝嗀嗔嗄嗩喿嗒喍嗏嗕嗢嗖嗈嗲嗍嗙嗂圔塓塨塤塏塍塉塯塕塎塝塙塥塛堽塣塱壼嫇嫄嫋媺媸媱媵媰媿嫈媻嫆"], +["dd40","媷嫀嫊媴媶嫍媹媐寖寘寙尟尳嵱嵣嵊嵥嵲嵬嵞嵨嵧嵢巰幏幎幊幍幋廅廌廆廋廇彀徯徭惷慉慊愫慅愶愲愮慆愯慏愩慀戠酨戣戥戤揅揱揫搐搒搉搠搤"], +["dda1","搳摃搟搕搘搹搷搢搣搌搦搰搨摁搵搯搊搚摀搥搧搋揧搛搮搡搎敯斒旓暆暌暕暐暋暊暙暔晸朠楦楟椸楎楢楱椿楅楪椹楂楗楙楺楈楉椵楬椳椽楥棰楸椴楩楀楯楄楶楘楁楴楌椻楋椷楜楏楑椲楒椯楻椼歆歅歃歂歈歁殛嗀毻毼"], +["de40","毹毷毸溛滖滈溏滀溟溓溔溠溱溹滆滒溽滁溞滉溷溰滍溦滏溲溾滃滜滘溙溒溎溍溤溡溿溳滐滊溗溮溣煇煔煒煣煠煁煝煢煲煸煪煡煂煘煃煋煰煟煐煓"], +["dea1","煄煍煚牏犍犌犑犐犎猼獂猻猺獀獊獉瑄瑊瑋瑒瑑瑗瑀瑏瑐瑎瑂瑆瑍瑔瓡瓿瓾瓽甝畹畷榃痯瘏瘃痷痾痼痹痸瘐痻痶痭痵痽皙皵盝睕睟睠睒睖睚睩睧睔睙睭矠碇碚碔碏碄碕碅碆碡碃硹碙碀碖硻祼禂祽祹稑稘稙稒稗稕稢稓"], +["df40","稛稐窣窢窞竫筦筤筭筴筩筲筥筳筱筰筡筸筶筣粲粴粯綈綆綀綍絿綅絺綎絻綃絼綌綔綄絽綒罭罫罧罨罬羦羥羧翛翜耡腤腠腷腜腩腛腢腲朡腞腶腧腯"], +["dfa1","腄腡舝艉艄艀艂艅蓱萿葖葶葹蒏蒍葥葑葀蒆葧萰葍葽葚葙葴葳葝蔇葞萷萺萴葺葃葸萲葅萩菙葋萯葂萭葟葰萹葎葌葒葯蓅蒎萻葇萶萳葨葾葄萫葠葔葮葐蜋蜄蛷蜌蛺蛖蛵蝍蛸蜎蜉蜁蛶蜍蜅裖裋裍裎裞裛裚裌裐覅覛觟觥觤"], +["e040","觡觠觢觜触詶誆詿詡訿詷誂誄詵誃誁詴詺谼豋豊豥豤豦貆貄貅賌赨赩趑趌趎趏趍趓趔趐趒跰跠跬跱跮跐跩跣跢跧跲跫跴輆軿輁輀輅輇輈輂輋遒逿"], +["e0a1","遄遉逽鄐鄍鄏鄑鄖鄔鄋鄎酮酯鉈鉒鈰鈺鉦鈳鉥鉞銃鈮鉊鉆鉭鉬鉏鉠鉧鉯鈶鉡鉰鈱鉔鉣鉐鉲鉎鉓鉌鉖鈲閟閜閞閛隒隓隑隗雎雺雽雸雵靳靷靸靲頏頍頎颬飶飹馯馲馰馵骭骫魛鳪鳭鳧麀黽僦僔僗僨僳僛僪僝僤僓僬僰僯僣僠"], +["e140","凘劀劁勩勫匰厬嘧嘕嘌嘒嗼嘏嘜嘁嘓嘂嗺嘝嘄嗿嗹墉塼墐墘墆墁塿塴墋塺墇墑墎塶墂墈塻墔墏壾奫嫜嫮嫥嫕嫪嫚嫭嫫嫳嫢嫠嫛嫬嫞嫝嫙嫨嫟孷寠"], +["e1a1","寣屣嶂嶀嵽嶆嵺嶁嵷嶊嶉嶈嵾嵼嶍嵹嵿幘幙幓廘廑廗廎廜廕廙廒廔彄彃彯徶愬愨慁慞慱慳慒慓慲慬憀慴慔慺慛慥愻慪慡慖戩戧戫搫摍摛摝摴摶摲摳摽摵摦撦摎撂摞摜摋摓摠摐摿搿摬摫摙摥摷敳斠暡暠暟朅朄朢榱榶槉"], +["e240","榠槎榖榰榬榼榑榙榎榧榍榩榾榯榿槄榽榤槔榹槊榚槏榳榓榪榡榞槙榗榐槂榵榥槆歊歍歋殞殟殠毃毄毾滎滵滱漃漥滸漷滻漮漉潎漙漚漧漘漻漒滭漊"], +["e2a1","漶潳滹滮漭潀漰漼漵滫漇漎潃漅滽滶漹漜滼漺漟漍漞漈漡熇熐熉熀熅熂熏煻熆熁熗牄牓犗犕犓獃獍獑獌瑢瑳瑱瑵瑲瑧瑮甀甂甃畽疐瘖瘈瘌瘕瘑瘊瘔皸瞁睼瞅瞂睮瞀睯睾瞃碲碪碴碭碨硾碫碞碥碠碬碢碤禘禊禋禖禕禔禓"], +["e340","禗禈禒禐稫穊稰稯稨稦窨窫窬竮箈箜箊箑箐箖箍箌箛箎箅箘劄箙箤箂粻粿粼粺綧綷緂綣綪緁緀緅綝緎緄緆緋緌綯綹綖綼綟綦綮綩綡緉罳翢翣翥翞"], +["e3a1","耤聝聜膉膆膃膇膍膌膋舕蒗蒤蒡蒟蒺蓎蓂蒬蒮蒫蒹蒴蓁蓍蒪蒚蒱蓐蒝蒧蒻蒢蒔蓇蓌蒛蒩蒯蒨蓖蒘蒶蓏蒠蓗蓔蓒蓛蒰蒑虡蜳蜣蜨蝫蝀蜮蜞蜡蜙蜛蝃蜬蝁蜾蝆蜠蜲蜪蜭蜼蜒蜺蜱蜵蝂蜦蜧蜸蜤蜚蜰蜑裷裧裱裲裺裾裮裼裶裻"], +["e440","裰裬裫覝覡覟覞觩觫觨誫誙誋誒誏誖谽豨豩賕賏賗趖踉踂跿踍跽踊踃踇踆踅跾踀踄輐輑輎輍鄣鄜鄠鄢鄟鄝鄚鄤鄡鄛酺酲酹酳銥銤鉶銛鉺銠銔銪銍"], +["e4a1","銦銚銫鉹銗鉿銣鋮銎銂銕銢鉽銈銡銊銆銌銙銧鉾銇銩銝銋鈭隞隡雿靘靽靺靾鞃鞀鞂靻鞄鞁靿韎韍頖颭颮餂餀餇馝馜駃馹馻馺駂馽駇骱髣髧鬾鬿魠魡魟鳱鳲鳵麧僿儃儰僸儆儇僶僾儋儌僽儊劋劌勱勯噈噂噌嘵噁噊噉噆噘"], +["e540","噚噀嘳嘽嘬嘾嘸嘪嘺圚墫墝墱墠墣墯墬墥墡壿嫿嫴嫽嫷嫶嬃嫸嬂嫹嬁嬇嬅嬏屧嶙嶗嶟嶒嶢嶓嶕嶠嶜嶡嶚嶞幩幝幠幜緳廛廞廡彉徲憋憃慹憱憰憢憉"], +["e5a1","憛憓憯憭憟憒憪憡憍慦憳戭摮摰撖撠撅撗撜撏撋撊撌撣撟摨撱撘敶敺敹敻斲斳暵暰暩暲暷暪暯樀樆樗槥槸樕槱槤樠槿槬槢樛樝槾樧槲槮樔槷槧橀樈槦槻樍槼槫樉樄樘樥樏槶樦樇槴樖歑殥殣殢殦氁氀毿氂潁漦潾澇濆澒"], +["e640","澍澉澌潢潏澅潚澖潶潬澂潕潲潒潐潗澔澓潝漀潡潫潽潧澐潓澋潩潿澕潣潷潪潻熲熯熛熰熠熚熩熵熝熥熞熤熡熪熜熧熳犘犚獘獒獞獟獠獝獛獡獚獙"], +["e6a1","獢璇璉璊璆璁瑽璅璈瑼瑹甈甇畾瘥瘞瘙瘝瘜瘣瘚瘨瘛皜皝皞皛瞍瞏瞉瞈磍碻磏磌磑磎磔磈磃磄磉禚禡禠禜禢禛歶稹窲窴窳箷篋箾箬篎箯箹篊箵糅糈糌糋緷緛緪緧緗緡縃緺緦緶緱緰緮緟罶羬羰羭翭翫翪翬翦翨聤聧膣膟"], +["e740","膞膕膢膙膗舖艏艓艒艐艎艑蔤蔻蔏蔀蔩蔎蔉蔍蔟蔊蔧蔜蓻蔫蓺蔈蔌蓴蔪蓲蔕蓷蓫蓳蓼蔒蓪蓩蔖蓾蔨蔝蔮蔂蓽蔞蓶蔱蔦蓧蓨蓰蓯蓹蔘蔠蔰蔋蔙蔯虢"], +["e7a1","蝖蝣蝤蝷蟡蝳蝘蝔蝛蝒蝡蝚蝑蝞蝭蝪蝐蝎蝟蝝蝯蝬蝺蝮蝜蝥蝏蝻蝵蝢蝧蝩衚褅褌褔褋褗褘褙褆褖褑褎褉覢覤覣觭觰觬諏諆誸諓諑諔諕誻諗誾諀諅諘諃誺誽諙谾豍貏賥賟賙賨賚賝賧趠趜趡趛踠踣踥踤踮踕踛踖踑踙踦踧"], +["e840","踔踒踘踓踜踗踚輬輤輘輚輠輣輖輗遳遰遯遧遫鄯鄫鄩鄪鄲鄦鄮醅醆醊醁醂醄醀鋐鋃鋄鋀鋙銶鋏鋱鋟鋘鋩鋗鋝鋌鋯鋂鋨鋊鋈鋎鋦鋍鋕鋉鋠鋞鋧鋑鋓"], +["e8a1","銵鋡鋆銴镼閬閫閮閰隤隢雓霅霈霂靚鞊鞎鞈韐韏頞頝頦頩頨頠頛頧颲餈飺餑餔餖餗餕駜駍駏駓駔駎駉駖駘駋駗駌骳髬髫髳髲髱魆魃魧魴魱魦魶魵魰魨魤魬鳼鳺鳽鳿鳷鴇鴀鳹鳻鴈鴅鴄麃黓鼏鼐儜儓儗儚儑凞匴叡噰噠噮"], +["e940","噳噦噣噭噲噞噷圜圛壈墽壉墿墺壂墼壆嬗嬙嬛嬡嬔嬓嬐嬖嬨嬚嬠嬞寯嶬嶱嶩嶧嶵嶰嶮嶪嶨嶲嶭嶯嶴幧幨幦幯廩廧廦廨廥彋徼憝憨憖懅憴懆懁懌憺"], +["e9a1","憿憸憌擗擖擐擏擉撽撉擃擛擳擙攳敿敼斢曈暾曀曊曋曏暽暻暺曌朣樴橦橉橧樲橨樾橝橭橶橛橑樨橚樻樿橁橪橤橐橏橔橯橩橠樼橞橖橕橍橎橆歕歔歖殧殪殫毈毇氄氃氆澭濋澣濇澼濎濈潞濄澽澞濊澨瀄澥澮澺澬澪濏澿澸"], +["ea40","澢濉澫濍澯澲澰燅燂熿熸燖燀燁燋燔燊燇燏熽燘熼燆燚燛犝犞獩獦獧獬獥獫獪瑿璚璠璔璒璕璡甋疀瘯瘭瘱瘽瘳瘼瘵瘲瘰皻盦瞚瞝瞡瞜瞛瞢瞣瞕瞙"], +["eaa1","瞗磝磩磥磪磞磣磛磡磢磭磟磠禤穄穈穇窶窸窵窱窷篞篣篧篝篕篥篚篨篹篔篪篢篜篫篘篟糒糔糗糐糑縒縡縗縌縟縠縓縎縜縕縚縢縋縏縖縍縔縥縤罃罻罼罺羱翯耪耩聬膱膦膮膹膵膫膰膬膴膲膷膧臲艕艖艗蕖蕅蕫蕍蕓蕡蕘"], +["eb40","蕀蕆蕤蕁蕢蕄蕑蕇蕣蔾蕛蕱蕎蕮蕵蕕蕧蕠薌蕦蕝蕔蕥蕬虣虥虤螛螏螗螓螒螈螁螖螘蝹螇螣螅螐螑螝螄螔螜螚螉褞褦褰褭褮褧褱褢褩褣褯褬褟觱諠"], +["eba1","諢諲諴諵諝謔諤諟諰諈諞諡諨諿諯諻貑貒貐賵賮賱賰賳赬赮趥趧踳踾踸蹀蹅踶踼踽蹁踰踿躽輶輮輵輲輹輷輴遶遹遻邆郺鄳鄵鄶醓醐醑醍醏錧錞錈錟錆錏鍺錸錼錛錣錒錁鍆錭錎錍鋋錝鋺錥錓鋹鋷錴錂錤鋿錩錹錵錪錔錌"], +["ec40","錋鋾錉錀鋻錖閼闍閾閹閺閶閿閵閽隩雔霋霒霐鞙鞗鞔韰韸頵頯頲餤餟餧餩馞駮駬駥駤駰駣駪駩駧骹骿骴骻髶髺髹髷鬳鮀鮅鮇魼魾魻鮂鮓鮒鮐魺鮕"], +["eca1","魽鮈鴥鴗鴠鴞鴔鴩鴝鴘鴢鴐鴙鴟麈麆麇麮麭黕黖黺鼒鼽儦儥儢儤儠儩勴嚓嚌嚍嚆嚄嚃噾嚂噿嚁壖壔壏壒嬭嬥嬲嬣嬬嬧嬦嬯嬮孻寱寲嶷幬幪徾徻懃憵憼懧懠懥懤懨懞擯擩擣擫擤擨斁斀斶旚曒檍檖檁檥檉檟檛檡檞檇檓檎"], +["ed40","檕檃檨檤檑橿檦檚檅檌檒歛殭氉濌澩濴濔濣濜濭濧濦濞濲濝濢濨燡燱燨燲燤燰燢獳獮獯璗璲璫璐璪璭璱璥璯甐甑甒甏疄癃癈癉癇皤盩瞵瞫瞲瞷瞶"], +["eda1","瞴瞱瞨矰磳磽礂磻磼磲礅磹磾礄禫禨穜穛穖穘穔穚窾竀竁簅簏篲簀篿篻簎篴簋篳簂簉簃簁篸篽簆篰篱簐簊糨縭縼繂縳顈縸縪繉繀繇縩繌縰縻縶繄縺罅罿罾罽翴翲耬膻臄臌臊臅臇膼臩艛艚艜薃薀薏薧薕薠薋薣蕻薤薚薞"], +["ee40","蕷蕼薉薡蕺蕸蕗薎薖薆薍薙薝薁薢薂薈薅蕹蕶薘薐薟虨螾螪螭蟅螰螬螹螵螼螮蟉蟃蟂蟌螷螯蟄蟊螴螶螿螸螽蟞螲褵褳褼褾襁襒褷襂覭覯覮觲觳謞"], +["eea1","謘謖謑謅謋謢謏謒謕謇謍謈謆謜謓謚豏豰豲豱豯貕貔賹赯蹎蹍蹓蹐蹌蹇轃轀邅遾鄸醚醢醛醙醟醡醝醠鎡鎃鎯鍤鍖鍇鍼鍘鍜鍶鍉鍐鍑鍠鍭鎏鍌鍪鍹鍗鍕鍒鍏鍱鍷鍻鍡鍞鍣鍧鎀鍎鍙闇闀闉闃闅閷隮隰隬霠霟霘霝霙鞚鞡鞜"], +["ef40","鞞鞝韕韔韱顁顄顊顉顅顃餥餫餬餪餳餲餯餭餱餰馘馣馡騂駺駴駷駹駸駶駻駽駾駼騃骾髾髽鬁髼魈鮚鮨鮞鮛鮦鮡鮥鮤鮆鮢鮠鮯鴳鵁鵧鴶鴮鴯鴱鴸鴰"], +["efa1","鵅鵂鵃鴾鴷鵀鴽翵鴭麊麉麍麰黈黚黻黿鼤鼣鼢齔龠儱儭儮嚘嚜嚗嚚嚝嚙奰嬼屩屪巀幭幮懘懟懭懮懱懪懰懫懖懩擿攄擽擸攁攃擼斔旛曚曛曘櫅檹檽櫡櫆檺檶檷櫇檴檭歞毉氋瀇瀌瀍瀁瀅瀔瀎濿瀀濻瀦濼濷瀊爁燿燹爃燽獶"], +["f040","璸瓀璵瓁璾璶璻瓂甔甓癜癤癙癐癓癗癚皦皽盬矂瞺磿礌礓礔礉礐礒礑禭禬穟簜簩簙簠簟簭簝簦簨簢簥簰繜繐繖繣繘繢繟繑繠繗繓羵羳翷翸聵臑臒"], +["f0a1","臐艟艞薴藆藀藃藂薳薵薽藇藄薿藋藎藈藅薱薶藒蘤薸薷薾虩蟧蟦蟢蟛蟫蟪蟥蟟蟳蟤蟔蟜蟓蟭蟘蟣螤蟗蟙蠁蟴蟨蟝襓襋襏襌襆襐襑襉謪謧謣謳謰謵譇謯謼謾謱謥謷謦謶謮謤謻謽謺豂豵貙貘貗賾贄贂贀蹜蹢蹠蹗蹖蹞蹥蹧"], +["f140","蹛蹚蹡蹝蹩蹔轆轇轈轋鄨鄺鄻鄾醨醥醧醯醪鎵鎌鎒鎷鎛鎝鎉鎧鎎鎪鎞鎦鎕鎈鎙鎟鎍鎱鎑鎲鎤鎨鎴鎣鎥闒闓闑隳雗雚巂雟雘雝霣霢霥鞬鞮鞨鞫鞤鞪"], +["f1a1","鞢鞥韗韙韖韘韺顐顑顒颸饁餼餺騏騋騉騍騄騑騊騅騇騆髀髜鬈鬄鬅鬩鬵魊魌魋鯇鯆鯃鮿鯁鮵鮸鯓鮶鯄鮹鮽鵜鵓鵏鵊鵛鵋鵙鵖鵌鵗鵒鵔鵟鵘鵚麎麌黟鼁鼀鼖鼥鼫鼪鼩鼨齌齕儴儵劖勷厴嚫嚭嚦嚧嚪嚬壚壝壛夒嬽嬾嬿巃幰"], +["f240","徿懻攇攐攍攉攌攎斄旞旝曞櫧櫠櫌櫑櫙櫋櫟櫜櫐櫫櫏櫍櫞歠殰氌瀙瀧瀠瀖瀫瀡瀢瀣瀩瀗瀤瀜瀪爌爊爇爂爅犥犦犤犣犡瓋瓅璷瓃甖癠矉矊矄矱礝礛"], +["f2a1","礡礜礗礞禰穧穨簳簼簹簬簻糬糪繶繵繸繰繷繯繺繲繴繨罋罊羃羆羷翽翾聸臗臕艤艡艣藫藱藭藙藡藨藚藗藬藲藸藘藟藣藜藑藰藦藯藞藢蠀蟺蠃蟶蟷蠉蠌蠋蠆蟼蠈蟿蠊蠂襢襚襛襗襡襜襘襝襙覈覷覶觶譐譈譊譀譓譖譔譋譕"], +["f340","譑譂譒譗豃豷豶貚贆贇贉趬趪趭趫蹭蹸蹳蹪蹯蹻軂轒轑轏轐轓辴酀鄿醰醭鏞鏇鏏鏂鏚鏐鏹鏬鏌鏙鎩鏦鏊鏔鏮鏣鏕鏄鏎鏀鏒鏧镽闚闛雡霩霫霬霨霦"], +["f3a1","鞳鞷鞶韝韞韟顜顙顝顗颿颽颻颾饈饇饃馦馧騚騕騥騝騤騛騢騠騧騣騞騜騔髂鬋鬊鬎鬌鬷鯪鯫鯠鯞鯤鯦鯢鯰鯔鯗鯬鯜鯙鯥鯕鯡鯚鵷鶁鶊鶄鶈鵱鶀鵸鶆鶋鶌鵽鵫鵴鵵鵰鵩鶅鵳鵻鶂鵯鵹鵿鶇鵨麔麑黀黼鼭齀齁齍齖齗齘匷嚲"], +["f440","嚵嚳壣孅巆巇廮廯忀忁懹攗攖攕攓旟曨曣曤櫳櫰櫪櫨櫹櫱櫮櫯瀼瀵瀯瀷瀴瀱灂瀸瀿瀺瀹灀瀻瀳灁爓爔犨獽獼璺皫皪皾盭矌矎矏矍矲礥礣礧礨礤礩"], +["f4a1","禲穮穬穭竷籉籈籊籇籅糮繻繾纁纀羺翿聹臛臙舋艨艩蘢藿蘁藾蘛蘀藶蘄蘉蘅蘌藽蠙蠐蠑蠗蠓蠖襣襦覹觷譠譪譝譨譣譥譧譭趮躆躈躄轙轖轗轕轘轚邍酃酁醷醵醲醳鐋鐓鏻鐠鐏鐔鏾鐕鐐鐨鐙鐍鏵鐀鏷鐇鐎鐖鐒鏺鐉鏸鐊鏿"], +["f540","鏼鐌鏶鐑鐆闞闠闟霮霯鞹鞻韽韾顠顢顣顟飁飂饐饎饙饌饋饓騲騴騱騬騪騶騩騮騸騭髇髊髆鬐鬒鬑鰋鰈鯷鰅鰒鯸鱀鰇鰎鰆鰗鰔鰉鶟鶙鶤鶝鶒鶘鶐鶛"], +["f5a1","鶠鶔鶜鶪鶗鶡鶚鶢鶨鶞鶣鶿鶩鶖鶦鶧麙麛麚黥黤黧黦鼰鼮齛齠齞齝齙龑儺儹劘劗囃嚽嚾孈孇巋巏廱懽攛欂櫼欃櫸欀灃灄灊灈灉灅灆爝爚爙獾甗癪矐礭礱礯籔籓糲纊纇纈纋纆纍罍羻耰臝蘘蘪蘦蘟蘣蘜蘙蘧蘮蘡蘠蘩蘞蘥"], +["f640","蠩蠝蠛蠠蠤蠜蠫衊襭襩襮襫觺譹譸譅譺譻贐贔趯躎躌轞轛轝酆酄酅醹鐿鐻鐶鐩鐽鐼鐰鐹鐪鐷鐬鑀鐱闥闤闣霵霺鞿韡顤飉飆飀饘饖騹騽驆驄驂驁騺"], +["f6a1","騿髍鬕鬗鬘鬖鬺魒鰫鰝鰜鰬鰣鰨鰩鰤鰡鶷鶶鶼鷁鷇鷊鷏鶾鷅鷃鶻鶵鷎鶹鶺鶬鷈鶱鶭鷌鶳鷍鶲鹺麜黫黮黭鼛鼘鼚鼱齎齥齤龒亹囆囅囋奱孋孌巕巑廲攡攠攦攢欋欈欉氍灕灖灗灒爞爟犩獿瓘瓕瓙瓗癭皭礵禴穰穱籗籜籙籛籚"], +["f740","糴糱纑罏羇臞艫蘴蘵蘳蘬蘲蘶蠬蠨蠦蠪蠥襱覿覾觻譾讄讂讆讅譿贕躕躔躚躒躐躖躗轠轢酇鑌鑐鑊鑋鑏鑇鑅鑈鑉鑆霿韣顪顩飋饔饛驎驓驔驌驏驈驊"], +["f7a1","驉驒驐髐鬙鬫鬻魖魕鱆鱈鰿鱄鰹鰳鱁鰼鰷鰴鰲鰽鰶鷛鷒鷞鷚鷋鷐鷜鷑鷟鷩鷙鷘鷖鷵鷕鷝麶黰鼵鼳鼲齂齫龕龢儽劙壨壧奲孍巘蠯彏戁戃戄攩攥斖曫欑欒欏毊灛灚爢玂玁玃癰矔籧籦纕艬蘺虀蘹蘼蘱蘻蘾蠰蠲蠮蠳襶襴襳觾"], +["f840","讌讎讋讈豅贙躘轤轣醼鑢鑕鑝鑗鑞韄韅頀驖驙鬞鬟鬠鱒鱘鱐鱊鱍鱋鱕鱙鱌鱎鷻鷷鷯鷣鷫鷸鷤鷶鷡鷮鷦鷲鷰鷢鷬鷴鷳鷨鷭黂黐黲黳鼆鼜鼸鼷鼶齃齏"], +["f8a1","齱齰齮齯囓囍孎屭攭曭曮欓灟灡灝灠爣瓛瓥矕礸禷禶籪纗羉艭虃蠸蠷蠵衋讔讕躞躟躠躝醾醽釂鑫鑨鑩雥靆靃靇韇韥驞髕魙鱣鱧鱦鱢鱞鱠鸂鷾鸇鸃鸆鸅鸀鸁鸉鷿鷽鸄麠鼞齆齴齵齶囔攮斸欘欙欗欚灢爦犪矘矙礹籩籫糶纚"], +["f940","纘纛纙臠臡虆虇虈襹襺襼襻觿讘讙躥躤躣鑮鑭鑯鑱鑳靉顲饟鱨鱮鱭鸋鸍鸐鸏鸒鸑麡黵鼉齇齸齻齺齹圞灦籯蠼趲躦釃鑴鑸鑶鑵驠鱴鱳鱱鱵鸔鸓黶鼊"], +["f9a1","龤灨灥糷虪蠾蠽蠿讞貜躩軉靋顳顴飌饡馫驤驦驧鬤鸕鸗齈戇欞爧虌躨钂钀钁驩驨鬮鸙爩虋讟钃鱹麷癵驫鱺鸝灩灪麤齾齉龘碁銹裏墻恒粧嫺╔╦╗╠╬╣╚╩╝╒╤╕╞╪╡╘╧╛╓╥╖╟╫╢╙╨╜║═╭╮╰╯▓"] +] diff --git a/node_modules/iconv-lite/encodings/tables/eucjp.json b/node_modules/iconv-lite/encodings/tables/eucjp.json new file mode 100644 index 00000000..4fa61ca1 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/eucjp.json @@ -0,0 +1,182 @@ +[ +["0","\u0000",127], +["8ea1","。",62], +["a1a1"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇"], +["a2a1","◆□■△▲▽▼※〒→←↑↓〓"], +["a2ba","∈∋⊆⊇⊂⊃∪∩"], +["a2ca","∧∨¬⇒⇔∀∃"], +["a2dc","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["a2f2","ʼn♯♭♪†‡¶"], +["a2fe","◯"], +["a3b0","0",9], +["a3c1","A",25], +["a3e1","a",25], +["a4a1","ぁ",82], +["a5a1","ァ",85], +["a6a1","Α",16,"Σ",6], +["a6c1","α",16,"σ",6], +["a7a1","А",5,"ЁЖ",25], +["a7d1","а",5,"ёж",25], +["a8a1","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["ada1","①",19,"Ⅰ",9], +["adc0","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["addf","㍻〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["b0a1","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["b1a1","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応"], +["b2a1","押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["b3a1","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱"], +["b4a1","粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["b5a1","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京"], +["b6a1","供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["b7a1","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲"], +["b8a1","検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["b9a1","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込"], +["baa1","此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["bba1","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時"], +["bca1","次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["bda1","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償"], +["bea1","勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["bfa1","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾"], +["c0a1","澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["c1a1","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎"], +["c2a1","臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["c3a1","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵"], +["c4a1","帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["c5a1","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到"], +["c6a1","董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["c7a1","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦"], +["c8a1","函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["c9a1","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服"], +["caa1","福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["cba1","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満"], +["cca1","漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["cda1","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃"], +["cea1","痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["cfa1","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["d0a1","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["d1a1","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨"], +["d2a1","辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["d3a1","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉"], +["d4a1","圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["d5a1","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓"], +["d6a1","屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["d7a1","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚"], +["d8a1","悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["d9a1","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼"], +["daa1","據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["dba1","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍"], +["dca1","棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["dda1","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾"], +["dea1","沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["dfa1","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼"], +["e0a1","燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e1a1","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰"], +["e2a1","癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e3a1","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐"], +["e4a1","筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e5a1","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺"], +["e6a1","罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e7a1","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙"], +["e8a1","茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e9a1","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙"], +["eaa1","蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["eba1","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫"], +["eca1","譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["eda1","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸"], +["eea1","遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["efa1","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞"], +["f0a1","陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["f1a1","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷"], +["f2a1","髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["f3a1","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠"], +["f4a1","堯槇遙瑤凜熙"], +["f9a1","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德"], +["faa1","忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["fba1","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚"], +["fca1","釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["fcf1","ⅰ",9,"¬¦'""], +["8fa2af","˘ˇ¸˙˝¯˛˚~΄΅"], +["8fa2c2","¡¦¿"], +["8fa2eb","ºª©®™¤№"], +["8fa6e1","ΆΈΉΊΪ"], +["8fa6e7","Ό"], +["8fa6e9","ΎΫ"], +["8fa6ec","Ώ"], +["8fa6f1","άέήίϊΐόςύϋΰώ"], +["8fa7c2","Ђ",10,"ЎЏ"], +["8fa7f2","ђ",10,"ўџ"], +["8fa9a1","ÆĐ"], +["8fa9a4","Ħ"], +["8fa9a6","IJ"], +["8fa9a8","ŁĿ"], +["8fa9ab","ŊØŒ"], +["8fa9af","ŦÞ"], +["8fa9c1","æđðħıijĸłŀʼnŋøœßŧþ"], +["8faaa1","ÁÀÄÂĂǍĀĄÅÃĆĈČÇĊĎÉÈËÊĚĖĒĘ"], +["8faaba","ĜĞĢĠĤÍÌÏÎǏİĪĮĨĴĶĹĽĻŃŇŅÑÓÒÖÔǑŐŌÕŔŘŖŚŜŠŞŤŢÚÙÜÛŬǓŰŪŲŮŨǗǛǙǕŴÝŸŶŹŽŻ"], +["8faba1","áàäâăǎāąåãćĉčçċďéèëêěėēęǵĝğ"], +["8fabbd","ġĥíìïîǐ"], +["8fabc5","īįĩĵķĺľļńňņñóòöôǒőōõŕřŗśŝšşťţúùüûŭǔűūųůũǘǜǚǖŵýÿŷźžż"], +["8fb0a1","丂丄丅丌丒丟丣两丨丫丮丯丰丵乀乁乄乇乑乚乜乣乨乩乴乵乹乿亍亖亗亝亯亹仃仐仚仛仠仡仢仨仯仱仳仵份仾仿伀伂伃伈伋伌伒伕伖众伙伮伱你伳伵伷伹伻伾佀佂佈佉佋佌佒佔佖佘佟佣佪佬佮佱佷佸佹佺佽佾侁侂侄"], +["8fb1a1","侅侉侊侌侎侐侒侓侔侗侙侚侞侟侲侷侹侻侼侽侾俀俁俅俆俈俉俋俌俍俏俒俜俠俢俰俲俼俽俿倀倁倄倇倊倌倎倐倓倗倘倛倜倝倞倢倧倮倰倲倳倵偀偁偂偅偆偊偌偎偑偒偓偗偙偟偠偢偣偦偧偪偭偰偱倻傁傃傄傆傊傎傏傐"], +["8fb2a1","傒傓傔傖傛傜傞",4,"傪傯傰傹傺傽僀僃僄僇僌僎僐僓僔僘僜僝僟僢僤僦僨僩僯僱僶僺僾儃儆儇儈儋儌儍儎僲儐儗儙儛儜儝儞儣儧儨儬儭儯儱儳儴儵儸儹兂兊兏兓兕兗兘兟兤兦兾冃冄冋冎冘冝冡冣冭冸冺冼冾冿凂"], +["8fb3a1","凈减凑凒凓凕凘凞凢凥凮凲凳凴凷刁刂刅划刓刕刖刘刢刨刱刲刵刼剅剉剕剗剘剚剜剟剠剡剦剮剷剸剹劀劂劅劊劌劓劕劖劗劘劚劜劤劥劦劧劯劰劶劷劸劺劻劽勀勄勆勈勌勏勑勔勖勛勜勡勥勨勩勪勬勰勱勴勶勷匀匃匊匋"], +["8fb4a1","匌匑匓匘匛匜匞匟匥匧匨匩匫匬匭匰匲匵匼匽匾卂卌卋卙卛卡卣卥卬卭卲卹卾厃厇厈厎厓厔厙厝厡厤厪厫厯厲厴厵厷厸厺厽叀叅叏叒叓叕叚叝叞叠另叧叵吂吓吚吡吧吨吪启吱吴吵呃呄呇呍呏呞呢呤呦呧呩呫呭呮呴呿"], +["8fb5a1","咁咃咅咈咉咍咑咕咖咜咟咡咦咧咩咪咭咮咱咷咹咺咻咿哆哊响哎哠哪哬哯哶哼哾哿唀唁唅唈唉唌唍唎唕唪唫唲唵唶唻唼唽啁啇啉啊啍啐啑啘啚啛啞啠啡啤啦啿喁喂喆喈喎喏喑喒喓喔喗喣喤喭喲喿嗁嗃嗆嗉嗋嗌嗎嗑嗒"], +["8fb6a1","嗓嗗嗘嗛嗞嗢嗩嗶嗿嘅嘈嘊嘍",5,"嘙嘬嘰嘳嘵嘷嘹嘻嘼嘽嘿噀噁噃噄噆噉噋噍噏噔噞噠噡噢噣噦噩噭噯噱噲噵嚄嚅嚈嚋嚌嚕嚙嚚嚝嚞嚟嚦嚧嚨嚩嚫嚬嚭嚱嚳嚷嚾囅囉囊囋囏囐囌囍囙囜囝囟囡囤",4,"囱囫园"], +["8fb7a1","囶囷圁圂圇圊圌圑圕圚圛圝圠圢圣圤圥圩圪圬圮圯圳圴圽圾圿坅坆坌坍坒坢坥坧坨坫坭",4,"坳坴坵坷坹坺坻坼坾垁垃垌垔垗垙垚垜垝垞垟垡垕垧垨垩垬垸垽埇埈埌埏埕埝埞埤埦埧埩埭埰埵埶埸埽埾埿堃堄堈堉埡"], +["8fb8a1","堌堍堛堞堟堠堦堧堭堲堹堿塉塌塍塏塐塕塟塡塤塧塨塸塼塿墀墁墇墈墉墊墌墍墏墐墔墖墝墠墡墢墦墩墱墲壄墼壂壈壍壎壐壒壔壖壚壝壡壢壩壳夅夆夋夌夒夓夔虁夝夡夣夤夨夯夰夳夵夶夿奃奆奒奓奙奛奝奞奟奡奣奫奭"], +["8fb9a1","奯奲奵奶她奻奼妋妌妎妒妕妗妟妤妧妭妮妯妰妳妷妺妼姁姃姄姈姊姍姒姝姞姟姣姤姧姮姯姱姲姴姷娀娄娌娍娎娒娓娞娣娤娧娨娪娭娰婄婅婇婈婌婐婕婞婣婥婧婭婷婺婻婾媋媐媓媖媙媜媞媟媠媢媧媬媱媲媳媵媸媺媻媿"], +["8fbaa1","嫄嫆嫈嫏嫚嫜嫠嫥嫪嫮嫵嫶嫽嬀嬁嬈嬗嬴嬙嬛嬝嬡嬥嬭嬸孁孋孌孒孖孞孨孮孯孼孽孾孿宁宄宆宊宎宐宑宓宔宖宨宩宬宭宯宱宲宷宺宼寀寁寍寏寖",4,"寠寯寱寴寽尌尗尞尟尣尦尩尫尬尮尰尲尵尶屙屚屜屢屣屧屨屩"], +["8fbba1","屭屰屴屵屺屻屼屽岇岈岊岏岒岝岟岠岢岣岦岪岲岴岵岺峉峋峒峝峗峮峱峲峴崁崆崍崒崫崣崤崦崧崱崴崹崽崿嵂嵃嵆嵈嵕嵑嵙嵊嵟嵠嵡嵢嵤嵪嵭嵰嵹嵺嵾嵿嶁嶃嶈嶊嶒嶓嶔嶕嶙嶛嶟嶠嶧嶫嶰嶴嶸嶹巃巇巋巐巎巘巙巠巤"], +["8fbca1","巩巸巹帀帇帍帒帔帕帘帟帠帮帨帲帵帾幋幐幉幑幖幘幛幜幞幨幪",4,"幰庀庋庎庢庤庥庨庪庬庱庳庽庾庿廆廌廋廎廑廒廔廕廜廞廥廫异弆弇弈弎弙弜弝弡弢弣弤弨弫弬弮弰弴弶弻弽弿彀彄彅彇彍彐彔彘彛彠彣彤彧"], +["8fbda1","彯彲彴彵彸彺彽彾徉徍徏徖徜徝徢徧徫徤徬徯徰徱徸忄忇忈忉忋忐",4,"忞忡忢忨忩忪忬忭忮忯忲忳忶忺忼怇怊怍怓怔怗怘怚怟怤怭怳怵恀恇恈恉恌恑恔恖恗恝恡恧恱恾恿悂悆悈悊悎悑悓悕悘悝悞悢悤悥您悰悱悷"], +["8fbea1","悻悾惂惄惈惉惊惋惎惏惔惕惙惛惝惞惢惥惲惵惸惼惽愂愇愊愌愐",4,"愖愗愙愜愞愢愪愫愰愱愵愶愷愹慁慅慆慉慞慠慬慲慸慻慼慿憀憁憃憄憋憍憒憓憗憘憜憝憟憠憥憨憪憭憸憹憼懀懁懂懎懏懕懜懝懞懟懡懢懧懩懥"], +["8fbfa1","懬懭懯戁戃戄戇戓戕戜戠戢戣戧戩戫戹戽扂扃扄扆扌扐扑扒扔扖扚扜扤扭扯扳扺扽抍抎抏抐抦抨抳抶抷抺抾抿拄拎拕拖拚拪拲拴拼拽挃挄挊挋挍挐挓挖挘挩挪挭挵挶挹挼捁捂捃捄捆捊捋捎捒捓捔捘捛捥捦捬捭捱捴捵"], +["8fc0a1","捸捼捽捿掂掄掇掊掐掔掕掙掚掞掤掦掭掮掯掽揁揅揈揎揑揓揔揕揜揠揥揪揬揲揳揵揸揹搉搊搐搒搔搘搞搠搢搤搥搩搪搯搰搵搽搿摋摏摑摒摓摔摚摛摜摝摟摠摡摣摭摳摴摻摽撅撇撏撐撑撘撙撛撝撟撡撣撦撨撬撳撽撾撿"], +["8fc1a1","擄擉擊擋擌擎擐擑擕擗擤擥擩擪擭擰擵擷擻擿攁攄攈攉攊攏攓攔攖攙攛攞攟攢攦攩攮攱攺攼攽敃敇敉敐敒敔敟敠敧敫敺敽斁斅斊斒斕斘斝斠斣斦斮斲斳斴斿旂旈旉旎旐旔旖旘旟旰旲旴旵旹旾旿昀昄昈昉昍昑昒昕昖昝"], +["8fc2a1","昞昡昢昣昤昦昩昪昫昬昮昰昱昳昹昷晀晅晆晊晌晑晎晗晘晙晛晜晠晡曻晪晫晬晾晳晵晿晷晸晹晻暀晼暋暌暍暐暒暙暚暛暜暟暠暤暭暱暲暵暻暿曀曂曃曈曌曎曏曔曛曟曨曫曬曮曺朅朇朎朓朙朜朠朢朳朾杅杇杈杌杔杕杝"], +["8fc3a1","杦杬杮杴杶杻极构枎枏枑枓枖枘枙枛枰枱枲枵枻枼枽柹柀柂柃柅柈柉柒柗柙柜柡柦柰柲柶柷桒栔栙栝栟栨栧栬栭栯栰栱栳栻栿桄桅桊桌桕桗桘桛桫桮",4,"桵桹桺桻桼梂梄梆梈梖梘梚梜梡梣梥梩梪梮梲梻棅棈棌棏"], +["8fc4a1","棐棑棓棖棙棜棝棥棨棪棫棬棭棰棱棵棶棻棼棽椆椉椊椐椑椓椖椗椱椳椵椸椻楂楅楉楎楗楛楣楤楥楦楨楩楬楰楱楲楺楻楿榀榍榒榖榘榡榥榦榨榫榭榯榷榸榺榼槅槈槑槖槗槢槥槮槯槱槳槵槾樀樁樃樏樑樕樚樝樠樤樨樰樲"], +["8fc5a1","樴樷樻樾樿橅橆橉橊橎橐橑橒橕橖橛橤橧橪橱橳橾檁檃檆檇檉檋檑檛檝檞檟檥檫檯檰檱檴檽檾檿櫆櫉櫈櫌櫐櫔櫕櫖櫜櫝櫤櫧櫬櫰櫱櫲櫼櫽欂欃欆欇欉欏欐欑欗欛欞欤欨欫欬欯欵欶欻欿歆歊歍歒歖歘歝歠歧歫歮歰歵歽"], +["8fc6a1","歾殂殅殗殛殟殠殢殣殨殩殬殭殮殰殸殹殽殾毃毄毉毌毖毚毡毣毦毧毮毱毷毹毿氂氄氅氉氍氎氐氒氙氟氦氧氨氬氮氳氵氶氺氻氿汊汋汍汏汒汔汙汛汜汫汭汯汴汶汸汹汻沅沆沇沉沔沕沗沘沜沟沰沲沴泂泆泍泏泐泑泒泔泖"], +["8fc7a1","泚泜泠泧泩泫泬泮泲泴洄洇洊洎洏洑洓洚洦洧洨汧洮洯洱洹洼洿浗浞浟浡浥浧浯浰浼涂涇涑涒涔涖涗涘涪涬涴涷涹涽涿淄淈淊淎淏淖淛淝淟淠淢淥淩淯淰淴淶淼渀渄渞渢渧渲渶渹渻渼湄湅湈湉湋湏湑湒湓湔湗湜湝湞"], +["8fc8a1","湢湣湨湳湻湽溍溓溙溠溧溭溮溱溳溻溿滀滁滃滇滈滊滍滎滏滫滭滮滹滻滽漄漈漊漌漍漖漘漚漛漦漩漪漯漰漳漶漻漼漭潏潑潒潓潗潙潚潝潞潡潢潨潬潽潾澃澇澈澋澌澍澐澒澓澔澖澚澟澠澥澦澧澨澮澯澰澵澶澼濅濇濈濊"], +["8fc9a1","濚濞濨濩濰濵濹濼濽瀀瀅瀆瀇瀍瀗瀠瀣瀯瀴瀷瀹瀼灃灄灈灉灊灋灔灕灝灞灎灤灥灬灮灵灶灾炁炅炆炔",4,"炛炤炫炰炱炴炷烊烑烓烔烕烖烘烜烤烺焃",4,"焋焌焏焞焠焫焭焯焰焱焸煁煅煆煇煊煋煐煒煗煚煜煞煠"], +["8fcaa1","煨煹熀熅熇熌熒熚熛熠熢熯熰熲熳熺熿燀燁燄燋燌燓燖燙燚燜燸燾爀爇爈爉爓爗爚爝爟爤爫爯爴爸爹牁牂牃牅牎牏牐牓牕牖牚牜牞牠牣牨牫牮牯牱牷牸牻牼牿犄犉犍犎犓犛犨犭犮犱犴犾狁狇狉狌狕狖狘狟狥狳狴狺狻"], +["8fcba1","狾猂猄猅猇猋猍猒猓猘猙猞猢猤猧猨猬猱猲猵猺猻猽獃獍獐獒獖獘獝獞獟獠獦獧獩獫獬獮獯獱獷獹獼玀玁玃玅玆玎玐玓玕玗玘玜玞玟玠玢玥玦玪玫玭玵玷玹玼玽玿珅珆珉珋珌珏珒珓珖珙珝珡珣珦珧珩珴珵珷珹珺珻珽"], +["8fcca1","珿琀琁琄琇琊琑琚琛琤琦琨",9,"琹瑀瑃瑄瑆瑇瑋瑍瑑瑒瑗瑝瑢瑦瑧瑨瑫瑭瑮瑱瑲璀璁璅璆璇璉璏璐璑璒璘璙璚璜璟璠璡璣璦璨璩璪璫璮璯璱璲璵璹璻璿瓈瓉瓌瓐瓓瓘瓚瓛瓞瓟瓤瓨瓪瓫瓯瓴瓺瓻瓼瓿甆"], +["8fcda1","甒甖甗甠甡甤甧甩甪甯甶甹甽甾甿畀畃畇畈畎畐畒畗畞畟畡畯畱畹",5,"疁疅疐疒疓疕疙疜疢疤疴疺疿痀痁痄痆痌痎痏痗痜痟痠痡痤痧痬痮痯痱痹瘀瘂瘃瘄瘇瘈瘊瘌瘏瘒瘓瘕瘖瘙瘛瘜瘝瘞瘣瘥瘦瘩瘭瘲瘳瘵瘸瘹"], +["8fcea1","瘺瘼癊癀癁癃癄癅癉癋癕癙癟癤癥癭癮癯癱癴皁皅皌皍皕皛皜皝皟皠皢",6,"皪皭皽盁盅盉盋盌盎盔盙盠盦盨盬盰盱盶盹盼眀眆眊眎眒眔眕眗眙眚眜眢眨眭眮眯眴眵眶眹眽眾睂睅睆睊睍睎睏睒睖睗睜睞睟睠睢"], +["8fcfa1","睤睧睪睬睰睲睳睴睺睽瞀瞄瞌瞍瞔瞕瞖瞚瞟瞢瞧瞪瞮瞯瞱瞵瞾矃矉矑矒矕矙矞矟矠矤矦矪矬矰矱矴矸矻砅砆砉砍砎砑砝砡砢砣砭砮砰砵砷硃硄硇硈硌硎硒硜硞硠硡硣硤硨硪确硺硾碊碏碔碘碡碝碞碟碤碨碬碭碰碱碲碳"], +["8fd0a1","碻碽碿磇磈磉磌磎磒磓磕磖磤磛磟磠磡磦磪磲磳礀磶磷磺磻磿礆礌礐礚礜礞礟礠礥礧礩礭礱礴礵礻礽礿祄祅祆祊祋祏祑祔祘祛祜祧祩祫祲祹祻祼祾禋禌禑禓禔禕禖禘禛禜禡禨禩禫禯禱禴禸离秂秄秇秈秊秏秔秖秚秝秞"], +["8fd1a1","秠秢秥秪秫秭秱秸秼稂稃稇稉稊稌稑稕稛稞稡稧稫稭稯稰稴稵稸稹稺穄穅穇穈穌穕穖穙穜穝穟穠穥穧穪穭穵穸穾窀窂窅窆窊窋窐窑窔窞窠窣窬窳窵窹窻窼竆竉竌竎竑竛竨竩竫竬竱竴竻竽竾笇笔笟笣笧笩笪笫笭笮笯笰"], +["8fd2a1","笱笴笽笿筀筁筇筎筕筠筤筦筩筪筭筯筲筳筷箄箉箎箐箑箖箛箞箠箥箬箯箰箲箵箶箺箻箼箽篂篅篈篊篔篖篗篙篚篛篨篪篲篴篵篸篹篺篼篾簁簂簃簄簆簉簋簌簎簏簙簛簠簥簦簨簬簱簳簴簶簹簺籆籊籕籑籒籓籙",5], +["8fd3a1","籡籣籧籩籭籮籰籲籹籼籽粆粇粏粔粞粠粦粰粶粷粺粻粼粿糄糇糈糉糍糏糓糔糕糗糙糚糝糦糩糫糵紃紇紈紉紏紑紒紓紖紝紞紣紦紪紭紱紼紽紾絀絁絇絈絍絑絓絗絙絚絜絝絥絧絪絰絸絺絻絿綁綂綃綅綆綈綋綌綍綑綖綗綝"], +["8fd4a1","綞綦綧綪綳綶綷綹緂",4,"緌緍緎緗緙縀緢緥緦緪緫緭緱緵緶緹緺縈縐縑縕縗縜縝縠縧縨縬縭縯縳縶縿繄繅繇繎繐繒繘繟繡繢繥繫繮繯繳繸繾纁纆纇纊纍纑纕纘纚纝纞缼缻缽缾缿罃罄罇罏罒罓罛罜罝罡罣罤罥罦罭"], +["8fd5a1","罱罽罾罿羀羋羍羏羐羑羖羗羜羡羢羦羪羭羴羼羿翀翃翈翎翏翛翟翣翥翨翬翮翯翲翺翽翾翿耇耈耊耍耎耏耑耓耔耖耝耞耟耠耤耦耬耮耰耴耵耷耹耺耼耾聀聄聠聤聦聭聱聵肁肈肎肜肞肦肧肫肸肹胈胍胏胒胔胕胗胘胠胭胮"], +["8fd6a1","胰胲胳胶胹胺胾脃脋脖脗脘脜脞脠脤脧脬脰脵脺脼腅腇腊腌腒腗腠腡腧腨腩腭腯腷膁膐膄膅膆膋膎膖膘膛膞膢膮膲膴膻臋臃臅臊臎臏臕臗臛臝臞臡臤臫臬臰臱臲臵臶臸臹臽臿舀舃舏舓舔舙舚舝舡舢舨舲舴舺艃艄艅艆"], +["8fd7a1","艋艎艏艑艖艜艠艣艧艭艴艻艽艿芀芁芃芄芇芉芊芎芑芔芖芘芚芛芠芡芣芤芧芨芩芪芮芰芲芴芷芺芼芾芿苆苐苕苚苠苢苤苨苪苭苯苶苷苽苾茀茁茇茈茊茋荔茛茝茞茟茡茢茬茭茮茰茳茷茺茼茽荂荃荄荇荍荎荑荕荖荗荰荸"], +["8fd8a1","荽荿莀莂莄莆莍莒莔莕莘莙莛莜莝莦莧莩莬莾莿菀菇菉菏菐菑菔菝荓菨菪菶菸菹菼萁萆萊萏萑萕萙莭萯萹葅葇葈葊葍葏葑葒葖葘葙葚葜葠葤葥葧葪葰葳葴葶葸葼葽蒁蒅蒒蒓蒕蒞蒦蒨蒩蒪蒯蒱蒴蒺蒽蒾蓀蓂蓇蓈蓌蓏蓓"], +["8fd9a1","蓜蓧蓪蓯蓰蓱蓲蓷蔲蓺蓻蓽蔂蔃蔇蔌蔎蔐蔜蔞蔢蔣蔤蔥蔧蔪蔫蔯蔳蔴蔶蔿蕆蕏",4,"蕖蕙蕜",6,"蕤蕫蕯蕹蕺蕻蕽蕿薁薅薆薉薋薌薏薓薘薝薟薠薢薥薧薴薶薷薸薼薽薾薿藂藇藊藋藎薭藘藚藟藠藦藨藭藳藶藼"], +["8fdaa1","藿蘀蘄蘅蘍蘎蘐蘑蘒蘘蘙蘛蘞蘡蘧蘩蘶蘸蘺蘼蘽虀虂虆虒虓虖虗虘虙虝虠",4,"虩虬虯虵虶虷虺蚍蚑蚖蚘蚚蚜蚡蚦蚧蚨蚭蚱蚳蚴蚵蚷蚸蚹蚿蛀蛁蛃蛅蛑蛒蛕蛗蛚蛜蛠蛣蛥蛧蚈蛺蛼蛽蜄蜅蜇蜋蜎蜏蜐蜓蜔蜙蜞蜟蜡蜣"], +["8fdba1","蜨蜮蜯蜱蜲蜹蜺蜼蜽蜾蝀蝃蝅蝍蝘蝝蝡蝤蝥蝯蝱蝲蝻螃",6,"螋螌螐螓螕螗螘螙螞螠螣螧螬螭螮螱螵螾螿蟁蟈蟉蟊蟎蟕蟖蟙蟚蟜蟟蟢蟣蟤蟪蟫蟭蟱蟳蟸蟺蟿蠁蠃蠆蠉蠊蠋蠐蠙蠒蠓蠔蠘蠚蠛蠜蠞蠟蠨蠭蠮蠰蠲蠵"], +["8fdca1","蠺蠼衁衃衅衈衉衊衋衎衑衕衖衘衚衜衟衠衤衩衱衹衻袀袘袚袛袜袟袠袨袪袺袽袾裀裊",4,"裑裒裓裛裞裧裯裰裱裵裷褁褆褍褎褏褕褖褘褙褚褜褠褦褧褨褰褱褲褵褹褺褾襀襂襅襆襉襏襒襗襚襛襜襡襢襣襫襮襰襳襵襺"], +["8fdda1","襻襼襽覉覍覐覔覕覛覜覟覠覥覰覴覵覶覷覼觔",4,"觥觩觫觭觱觳觶觹觽觿訄訅訇訏訑訒訔訕訞訠訢訤訦訫訬訯訵訷訽訾詀詃詅詇詉詍詎詓詖詗詘詜詝詡詥詧詵詶詷詹詺詻詾詿誀誃誆誋誏誐誒誖誗誙誟誧誩誮誯誳"], +["8fdea1","誶誷誻誾諃諆諈諉諊諑諓諔諕諗諝諟諬諰諴諵諶諼諿謅謆謋謑謜謞謟謊謭謰謷謼譂",4,"譈譒譓譔譙譍譞譣譭譶譸譹譼譾讁讄讅讋讍讏讔讕讜讞讟谸谹谽谾豅豇豉豋豏豑豓豔豗豘豛豝豙豣豤豦豨豩豭豳豵豶豻豾貆"], +["8fdfa1","貇貋貐貒貓貙貛貜貤貹貺賅賆賉賋賏賖賕賙賝賡賨賬賯賰賲賵賷賸賾賿贁贃贉贒贗贛赥赩赬赮赿趂趄趈趍趐趑趕趞趟趠趦趫趬趯趲趵趷趹趻跀跅跆跇跈跊跎跑跔跕跗跙跤跥跧跬跰趼跱跲跴跽踁踄踅踆踋踑踔踖踠踡踢"], +["8fe0a1","踣踦踧踱踳踶踷踸踹踽蹀蹁蹋蹍蹎蹏蹔蹛蹜蹝蹞蹡蹢蹩蹬蹭蹯蹰蹱蹹蹺蹻躂躃躉躐躒躕躚躛躝躞躢躧躩躭躮躳躵躺躻軀軁軃軄軇軏軑軔軜軨軮軰軱軷軹軺軭輀輂輇輈輏輐輖輗輘輞輠輡輣輥輧輨輬輭輮輴輵輶輷輺轀轁"], +["8fe1a1","轃轇轏轑",4,"轘轝轞轥辝辠辡辤辥辦辵辶辸达迀迁迆迊迋迍运迒迓迕迠迣迤迨迮迱迵迶迻迾适逄逈逌逘逛逨逩逯逪逬逭逳逴逷逿遃遄遌遛遝遢遦遧遬遰遴遹邅邈邋邌邎邐邕邗邘邙邛邠邡邢邥邰邲邳邴邶邽郌邾郃"], +["8fe2a1","郄郅郇郈郕郗郘郙郜郝郟郥郒郶郫郯郰郴郾郿鄀鄄鄅鄆鄈鄍鄐鄔鄖鄗鄘鄚鄜鄞鄠鄥鄢鄣鄧鄩鄮鄯鄱鄴鄶鄷鄹鄺鄼鄽酃酇酈酏酓酗酙酚酛酡酤酧酭酴酹酺酻醁醃醅醆醊醎醑醓醔醕醘醞醡醦醨醬醭醮醰醱醲醳醶醻醼醽醿"], +["8fe3a1","釂釃釅釓釔釗釙釚釞釤釥釩釪釬",5,"釷釹釻釽鈀鈁鈄鈅鈆鈇鈉鈊鈌鈐鈒鈓鈖鈘鈜鈝鈣鈤鈥鈦鈨鈮鈯鈰鈳鈵鈶鈸鈹鈺鈼鈾鉀鉂鉃鉆鉇鉊鉍鉎鉏鉑鉘鉙鉜鉝鉠鉡鉥鉧鉨鉩鉮鉯鉰鉵",4,"鉻鉼鉽鉿銈銉銊銍銎銒銗"], +["8fe4a1","銙銟銠銤銥銧銨銫銯銲銶銸銺銻銼銽銿",4,"鋅鋆鋇鋈鋋鋌鋍鋎鋐鋓鋕鋗鋘鋙鋜鋝鋟鋠鋡鋣鋥鋧鋨鋬鋮鋰鋹鋻鋿錀錂錈錍錑錔錕錜錝錞錟錡錤錥錧錩錪錳錴錶錷鍇鍈鍉鍐鍑鍒鍕鍗鍘鍚鍞鍤鍥鍧鍩鍪鍭鍯鍰鍱鍳鍴鍶"], +["8fe5a1","鍺鍽鍿鎀鎁鎂鎈鎊鎋鎍鎏鎒鎕鎘鎛鎞鎡鎣鎤鎦鎨鎫鎴鎵鎶鎺鎩鏁鏄鏅鏆鏇鏉",4,"鏓鏙鏜鏞鏟鏢鏦鏧鏹鏷鏸鏺鏻鏽鐁鐂鐄鐈鐉鐍鐎鐏鐕鐖鐗鐟鐮鐯鐱鐲鐳鐴鐻鐿鐽鑃鑅鑈鑊鑌鑕鑙鑜鑟鑡鑣鑨鑫鑭鑮鑯鑱鑲钄钃镸镹"], +["8fe6a1","镾閄閈閌閍閎閝閞閟閡閦閩閫閬閴閶閺閽閿闆闈闉闋闐闑闒闓闙闚闝闞闟闠闤闦阝阞阢阤阥阦阬阱阳阷阸阹阺阼阽陁陒陔陖陗陘陡陮陴陻陼陾陿隁隂隃隄隉隑隖隚隝隟隤隥隦隩隮隯隳隺雊雒嶲雘雚雝雞雟雩雯雱雺霂"], +["8fe7a1","霃霅霉霚霛霝霡霢霣霨霱霳靁靃靊靎靏靕靗靘靚靛靣靧靪靮靳靶靷靸靻靽靿鞀鞉鞕鞖鞗鞙鞚鞞鞟鞢鞬鞮鞱鞲鞵鞶鞸鞹鞺鞼鞾鞿韁韄韅韇韉韊韌韍韎韐韑韔韗韘韙韝韞韠韛韡韤韯韱韴韷韸韺頇頊頙頍頎頔頖頜頞頠頣頦"], +["8fe8a1","頫頮頯頰頲頳頵頥頾顄顇顊顑顒顓顖顗顙顚顢顣顥顦顪顬颫颭颮颰颴颷颸颺颻颿飂飅飈飌飡飣飥飦飧飪飳飶餂餇餈餑餕餖餗餚餛餜餟餢餦餧餫餱",4,"餹餺餻餼饀饁饆饇饈饍饎饔饘饙饛饜饞饟饠馛馝馟馦馰馱馲馵"], +["8fe9a1","馹馺馽馿駃駉駓駔駙駚駜駞駧駪駫駬駰駴駵駹駽駾騂騃騄騋騌騐騑騖騞騠騢騣騤騧騭騮騳騵騶騸驇驁驄驊驋驌驎驑驔驖驝骪骬骮骯骲骴骵骶骹骻骾骿髁髃髆髈髎髐髒髕髖髗髛髜髠髤髥髧髩髬髲髳髵髹髺髽髿",4], +["8feaa1","鬄鬅鬈鬉鬋鬌鬍鬎鬐鬒鬖鬙鬛鬜鬠鬦鬫鬭鬳鬴鬵鬷鬹鬺鬽魈魋魌魕魖魗魛魞魡魣魥魦魨魪",4,"魳魵魷魸魹魿鮀鮄鮅鮆鮇鮉鮊鮋鮍鮏鮐鮔鮚鮝鮞鮦鮧鮩鮬鮰鮱鮲鮷鮸鮻鮼鮾鮿鯁鯇鯈鯎鯐鯗鯘鯝鯟鯥鯧鯪鯫鯯鯳鯷鯸"], +["8feba1","鯹鯺鯽鯿鰀鰂鰋鰏鰑鰖鰘鰙鰚鰜鰞鰢鰣鰦",4,"鰱鰵鰶鰷鰽鱁鱃鱄鱅鱉鱊鱎鱏鱐鱓鱔鱖鱘鱛鱝鱞鱟鱣鱩鱪鱜鱫鱨鱮鱰鱲鱵鱷鱻鳦鳲鳷鳹鴋鴂鴑鴗鴘鴜鴝鴞鴯鴰鴲鴳鴴鴺鴼鵅鴽鵂鵃鵇鵊鵓鵔鵟鵣鵢鵥鵩鵪鵫鵰鵶鵷鵻"], +["8feca1","鵼鵾鶃鶄鶆鶊鶍鶎鶒鶓鶕鶖鶗鶘鶡鶪鶬鶮鶱鶵鶹鶼鶿鷃鷇鷉鷊鷔鷕鷖鷗鷚鷞鷟鷠鷥鷧鷩鷫鷮鷰鷳鷴鷾鸊鸂鸇鸎鸐鸑鸒鸕鸖鸙鸜鸝鹺鹻鹼麀麂麃麄麅麇麎麏麖麘麛麞麤麨麬麮麯麰麳麴麵黆黈黋黕黟黤黧黬黭黮黰黱黲黵"], +["8feda1","黸黿鼂鼃鼉鼏鼐鼑鼒鼔鼖鼗鼙鼚鼛鼟鼢鼦鼪鼫鼯鼱鼲鼴鼷鼹鼺鼼鼽鼿齁齃",4,"齓齕齖齗齘齚齝齞齨齩齭",4,"齳齵齺齽龏龐龑龒龔龖龗龞龡龢龣龥"] +] diff --git a/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json new file mode 100644 index 00000000..85c69347 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json @@ -0,0 +1 @@ +{"uChars":[128,165,169,178,184,216,226,235,238,244,248,251,253,258,276,284,300,325,329,334,364,463,465,467,469,471,473,475,477,506,594,610,712,716,730,930,938,962,970,1026,1104,1106,8209,8215,8218,8222,8231,8241,8244,8246,8252,8365,8452,8454,8458,8471,8482,8556,8570,8596,8602,8713,8720,8722,8726,8731,8737,8740,8742,8748,8751,8760,8766,8777,8781,8787,8802,8808,8816,8854,8858,8870,8896,8979,9322,9372,9548,9588,9616,9622,9634,9652,9662,9672,9676,9680,9702,9735,9738,9793,9795,11906,11909,11913,11917,11928,11944,11947,11951,11956,11960,11964,11979,12284,12292,12312,12319,12330,12351,12436,12447,12535,12543,12586,12842,12850,12964,13200,13215,13218,13253,13263,13267,13270,13384,13428,13727,13839,13851,14617,14703,14801,14816,14964,15183,15471,15585,16471,16736,17208,17325,17330,17374,17623,17997,18018,18212,18218,18301,18318,18760,18811,18814,18820,18823,18844,18848,18872,19576,19620,19738,19887,40870,59244,59336,59367,59413,59417,59423,59431,59437,59443,59452,59460,59478,59493,63789,63866,63894,63976,63986,64016,64018,64021,64025,64034,64037,64042,65074,65093,65107,65112,65127,65132,65375,65510,65536],"gbChars":[0,36,38,45,50,81,89,95,96,100,103,104,105,109,126,133,148,172,175,179,208,306,307,308,309,310,311,312,313,341,428,443,544,545,558,741,742,749,750,805,819,820,7922,7924,7925,7927,7934,7943,7944,7945,7950,8062,8148,8149,8152,8164,8174,8236,8240,8262,8264,8374,8380,8381,8384,8388,8390,8392,8393,8394,8396,8401,8406,8416,8419,8424,8437,8439,8445,8482,8485,8496,8521,8603,8936,8946,9046,9050,9063,9066,9076,9092,9100,9108,9111,9113,9131,9162,9164,9218,9219,11329,11331,11334,11336,11346,11361,11363,11366,11370,11372,11375,11389,11682,11686,11687,11692,11694,11714,11716,11723,11725,11730,11736,11982,11989,12102,12336,12348,12350,12384,12393,12395,12397,12510,12553,12851,12962,12973,13738,13823,13919,13933,14080,14298,14585,14698,15583,15847,16318,16434,16438,16481,16729,17102,17122,17315,17320,17402,17418,17859,17909,17911,17915,17916,17936,17939,17961,18664,18703,18814,18962,19043,33469,33470,33471,33484,33485,33490,33497,33501,33505,33513,33520,33536,33550,37845,37921,37948,38029,38038,38064,38065,38066,38069,38075,38076,38078,39108,39109,39113,39114,39115,39116,39265,39394,189000]} \ No newline at end of file diff --git a/node_modules/iconv-lite/encodings/tables/gbk-added.json b/node_modules/iconv-lite/encodings/tables/gbk-added.json new file mode 100644 index 00000000..8abfa9f7 --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/gbk-added.json @@ -0,0 +1,55 @@ +[ +["a140","",62], +["a180","",32], +["a240","",62], +["a280","",32], +["a2ab","",5], +["a2e3","€"], +["a2ef",""], +["a2fd",""], +["a340","",62], +["a380","",31," "], +["a440","",62], +["a480","",32], +["a4f4","",10], +["a540","",62], +["a580","",32], +["a5f7","",7], +["a640","",62], +["a680","",32], +["a6b9","",7], +["a6d9","",6], +["a6ec",""], +["a6f3",""], +["a6f6","",8], +["a740","",62], +["a780","",32], +["a7c2","",14], +["a7f2","",12], +["a896","",10], +["a8bc",""], +["a8bf","ǹ"], +["a8c1",""], +["a8ea","",20], +["a958",""], +["a95b",""], +["a95d",""], +["a989","〾⿰",11], +["a997","",12], +["a9f0","",14], +["aaa1","",93], +["aba1","",93], +["aca1","",93], +["ada1","",93], +["aea1","",93], +["afa1","",93], +["d7fa","",4], +["f8a1","",93], +["f9a1","",93], +["faa1","",93], +["fba1","",93], +["fca1","",93], +["fda1","",93], +["fe50","⺁⺄㑳㑇⺈⺋㖞㘚㘎⺌⺗㥮㤘㧏㧟㩳㧐㭎㱮㳠⺧⺪䁖䅟⺮䌷⺳⺶⺷䎱䎬⺻䏝䓖䙡䙌"], +["fe80","䜣䜩䝼䞍⻊䥇䥺䥽䦂䦃䦅䦆䦟䦛䦷䦶䲣䲟䲠䲡䱷䲢䴓",6,"䶮",93] +] diff --git a/node_modules/iconv-lite/encodings/tables/shiftjis.json b/node_modules/iconv-lite/encodings/tables/shiftjis.json new file mode 100644 index 00000000..5a3a43cf --- /dev/null +++ b/node_modules/iconv-lite/encodings/tables/shiftjis.json @@ -0,0 +1,125 @@ +[ +["0","\u0000",128], +["a1","。",62], +["8140"," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈",9,"+-±×"], +["8180","÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓"], +["81b8","∈∋⊆⊇⊂⊃∪∩"], +["81c8","∧∨¬⇒⇔∀∃"], +["81da","∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬"], +["81f0","ʼn♯♭♪†‡¶"], +["81fc","◯"], +["824f","0",9], +["8260","A",25], +["8281","a",25], +["829f","ぁ",82], +["8340","ァ",62], +["8380","ム",22], +["839f","Α",16,"Σ",6], +["83bf","α",16,"σ",6], +["8440","А",5,"ЁЖ",25], +["8470","а",5,"ёж",7], +["8480","о",17], +["849f","─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂"], +["8740","①",19,"Ⅰ",9], +["875f","㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡"], +["877e","㍻"], +["8780","〝〟№㏍℡㊤",4,"㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪"], +["889f","亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭"], +["8940","院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"], +["8980","園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"], +["8a40","魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"], +["8a80","橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"], +["8b40","機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"], +["8b80","朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"], +["8c40","掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"], +["8c80","劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"], +["8d40","后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"], +["8d80","項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"], +["8e40","察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"], +["8e80","死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"], +["8f40","宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"], +["8f80","準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"], +["9040","拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"], +["9080","逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"], +["9140","繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"], +["9180","操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"], +["9240","叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"], +["9280","逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"], +["9340","邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"], +["9380","凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"], +["9440","如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"], +["9480","楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"], +["9540","鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"], +["9580","斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"], +["9640","法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"], +["9680","摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"], +["9740","諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"], +["9780","沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"], +["9840","蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"], +["989f","弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"], +["9940","僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"], +["9980","凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"], +["9a40","咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"], +["9a80","噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"], +["9b40","奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"], +["9b80","它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"], +["9c40","廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"], +["9c80","怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"], +["9d40","戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"], +["9d80","捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"], +["9e40","曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"], +["9e80","梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"], +["9f40","檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"], +["9f80","麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"], +["e040","漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"], +["e080","烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"], +["e140","瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"], +["e180","痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"], +["e240","磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"], +["e280","窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"], +["e340","紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"], +["e380","縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"], +["e440","隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"], +["e480","艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"], +["e540","蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"], +["e580","蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"], +["e640","襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"], +["e680","諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"], +["e740","蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"], +["e780","轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"], +["e840","錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"], +["e880","閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"], +["e940","顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"], +["e980","騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"], +["ea40","鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"], +["ea80","黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"], +["ed40","纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏"], +["ed80","塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱"], +["ee40","犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙"], +["ee80","蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"], +["eeef","ⅰ",9,"¬¦'""], +["f040","",62], +["f080","",124], +["f140","",62], +["f180","",124], +["f240","",62], +["f280","",124], +["f340","",62], +["f380","",124], +["f440","",62], +["f480","",124], +["f540","",62], +["f580","",124], +["f640","",62], +["f680","",124], +["f740","",62], +["f780","",124], +["f840","",62], +["f880","",124], +["f940",""], +["fa40","ⅰ",9,"Ⅰ",9,"¬¦'"㈱№℡∵纊褜鍈銈蓜俉炻昱棈鋹曻彅丨仡仼伀伃伹佖侒侊侚侔俍偀倢俿倞偆偰偂傔僴僘兊"], +["fa80","兤冝冾凬刕劜劦勀勛匀匇匤卲厓厲叝﨎咜咊咩哿喆坙坥垬埈埇﨏塚增墲夋奓奛奝奣妤妺孖寀甯寘寬尞岦岺峵崧嵓﨑嵂嵭嶸嶹巐弡弴彧德忞恝悅悊惞惕愠惲愑愷愰憘戓抦揵摠撝擎敎昀昕昻昉昮昞昤晥晗晙晴晳暙暠暲暿曺朎朗杦枻桒柀栁桄棏﨓楨﨔榘槢樰橫橆橳橾櫢櫤毖氿汜沆汯泚洄涇浯"], +["fb40","涖涬淏淸淲淼渹湜渧渼溿澈澵濵瀅瀇瀨炅炫焏焄煜煆煇凞燁燾犱犾猤猪獷玽珉珖珣珒琇珵琦琪琩琮瑢璉璟甁畯皂皜皞皛皦益睆劯砡硎硤硺礰礼神"], +["fb80","祥禔福禛竑竧靖竫箞精絈絜綷綠緖繒罇羡羽茁荢荿菇菶葈蒴蕓蕙蕫﨟薰蘒﨡蠇裵訒訷詹誧誾諟諸諶譓譿賰賴贒赶﨣軏﨤逸遧郞都鄕鄧釚釗釞釭釮釤釥鈆鈐鈊鈺鉀鈼鉎鉙鉑鈹鉧銧鉷鉸鋧鋗鋙鋐﨧鋕鋠鋓錥錡鋻﨨錞鋿錝錂鍰鍗鎤鏆鏞鏸鐱鑅鑈閒隆﨩隝隯霳霻靃靍靏靑靕顗顥飯飼餧館馞驎髙"], +["fc40","髜魵魲鮏鮱鮻鰀鵰鵫鶴鸙黑"] +] diff --git a/node_modules/iconv-lite/encodings/utf16.js b/node_modules/iconv-lite/encodings/utf16.js new file mode 100644 index 00000000..7e8f1591 --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf16.js @@ -0,0 +1,177 @@ +"use strict"; +var Buffer = require("buffer").Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { +} + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { +} + +Utf16BEEncoder.prototype.write = function(str) { + var buf = new Buffer(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; + } + return buf; +} + +Utf16BEEncoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf16BEDecoder() { + this.overflowByte = -1; +} + +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + + var buf2 = new Buffer(buf.length + 1), + i = 0, j = 0; + + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } + + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } + + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; + + return buf2.slice(0, j).toString('ucs2'); +} + +Utf16BEDecoder.prototype.end = function() { +} + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; +} + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); +} + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; + } + + return this.decoder.write(buf); +} + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); +} + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; + } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; + } + } + + return enc; +} + + diff --git a/node_modules/iconv-lite/encodings/utf7.js b/node_modules/iconv-lite/encodings/utf7.js new file mode 100644 index 00000000..19b7194a --- /dev/null +++ b/node_modules/iconv-lite/encodings/utf7.js @@ -0,0 +1,290 @@ +"use strict"; +var Buffer = require("buffer").Buffer; + +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return new Buffer(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; +}; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = new Buffer(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = new Buffer(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; + } + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } + } + } + } + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = new Buffer(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; + } + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } + } + } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(new Buffer(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(new Buffer(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + diff --git a/node_modules/iconv-lite/lib/bom-handling.js b/node_modules/iconv-lite/lib/bom-handling.js new file mode 100644 index 00000000..10508723 --- /dev/null +++ b/node_modules/iconv-lite/lib/bom-handling.js @@ -0,0 +1,52 @@ +"use strict"; + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; + } + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + diff --git a/node_modules/iconv-lite/lib/extend-node.js b/node_modules/iconv-lite/lib/extend-node.js new file mode 100644 index 00000000..a120400b --- /dev/null +++ b/node_modules/iconv-lite/lib/extend-node.js @@ -0,0 +1,215 @@ +"use strict"; +var Buffer = require("buffer").Buffer; + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + iconv.supportsNodeEncodingsExtension = !(new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; + } + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; + } + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = require('buffer').SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + } + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); + } + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; + } + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); + } + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; + } + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = require('buffer').SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = require('stream').Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } +} diff --git a/node_modules/iconv-lite/lib/index.d.ts b/node_modules/iconv-lite/lib/index.d.ts new file mode 100644 index 00000000..b9c83613 --- /dev/null +++ b/node_modules/iconv-lite/lib/index.d.ts @@ -0,0 +1,24 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. + * REQUIREMENT: This definition is dependent on the @types/node definition. + * Install with `npm install @types/node --save-dev` + *--------------------------------------------------------------------------------------------*/ + +declare module 'iconv-lite' { + export function decode(buffer: NodeBuffer, encoding: string, options?: Options): string; + + export function encode(content: string, encoding: string, options?: Options): NodeBuffer; + + export function encodingExists(encoding: string): boolean; + + export function decodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; + + export function encodeStream(encoding: string, options?: Options): NodeJS.ReadWriteStream; +} + +export interface Options { + stripBOM?: boolean; + addBOM?: boolean; + defaultEncoding?: string; +} diff --git a/node_modules/iconv-lite/lib/index.js b/node_modules/iconv-lite/lib/index.js new file mode 100644 index 00000000..9a524721 --- /dev/null +++ b/node_modules/iconv-lite/lib/index.js @@ -0,0 +1,148 @@ +"use strict"; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = require("buffer").Buffer; + +var bomHandling = require("./bom-handling"), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = new Buffer("" + (buf || ""), "binary"); // Ensure buffer. + } + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; + } +} + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = require("../encodings"); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = (''+encoding).toLowerCase().replace(/[^0-9a-z]|:\d{4}$/g, ""); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; +} + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + require("./streams")(iconv); + } + + // Load Node primitive extensions. + require("./extend-node")(iconv); +} + +if ("Ā" != "\u0100") { + console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); +} diff --git a/node_modules/iconv-lite/lib/streams.js b/node_modules/iconv-lite/lib/streams.js new file mode 100644 index 00000000..44095529 --- /dev/null +++ b/node_modules/iconv-lite/lib/streams.js @@ -0,0 +1,121 @@ +"use strict"; + +var Buffer = require("buffer").Buffer, + Transform = require("stream").Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); + } + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); + } + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); +} + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); + }); + return this; +} + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); +} + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); + } + catch (e) { + done(e); + } +} + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; +} + diff --git a/node_modules/iconv-lite/package.json b/node_modules/iconv-lite/package.json new file mode 100644 index 00000000..62a59b78 --- /dev/null +++ b/node_modules/iconv-lite/package.json @@ -0,0 +1,127 @@ +{ + "_args": [ + [ + "iconv-lite@0.4.19", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "iconv-lite@0.4.19", + "_id": "iconv-lite@0.4.19", + "_inBundle": false, + "_integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==", + "_location": "/iconv-lite", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "iconv-lite@0.4.19", + "name": "iconv-lite", + "escapedName": "iconv-lite", + "rawSpec": "0.4.19", + "saveSpec": null, + "fetchSpec": "0.4.19" + }, + "_requiredBy": [ + "/body-parser", + "/raw-body" + ], + "_resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", + "_spec": "0.4.19", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Alexander Shtuchkin", + "email": "ashtuchkin@gmail.com" + }, + "browser": { + "./extend-node": false, + "./streams": false + }, + "bugs": { + "url": "https://github.com/ashtuchkin/iconv-lite/issues" + }, + "contributors": [ + { + "name": "Jinwu Zhan", + "url": "https://github.com/jenkinv" + }, + { + "name": "Adamansky Anton", + "url": "https://github.com/adamansky" + }, + { + "name": "George Stagas", + "url": "https://github.com/stagas" + }, + { + "name": "Mike D Pilsbury", + "url": "https://github.com/pekim" + }, + { + "name": "Niggler", + "url": "https://github.com/Niggler" + }, + { + "name": "wychi", + "url": "https://github.com/wychi" + }, + { + "name": "David Kuo", + "url": "https://github.com/david50407" + }, + { + "name": "ChangZhuo Chen", + "url": "https://github.com/czchen" + }, + { + "name": "Lee Treveil", + "url": "https://github.com/leetreveil" + }, + { + "name": "Brian White", + "url": "https://github.com/mscdex" + }, + { + "name": "Mithgol", + "url": "https://github.com/Mithgol" + }, + { + "name": "Nazar Leush", + "url": "https://github.com/nleush" + } + ], + "description": "Convert character encodings in pure javascript.", + "devDependencies": { + "async": "*", + "errto": "*", + "iconv": "*", + "istanbul": "*", + "mocha": "*", + "request": "*", + "semver": "*", + "unorm": "*" + }, + "engines": { + "node": ">=0.10.0" + }, + "homepage": "https://github.com/ashtuchkin/iconv-lite", + "keywords": [ + "iconv", + "convert", + "charset", + "icu" + ], + "license": "MIT", + "main": "./lib/index.js", + "name": "iconv-lite", + "repository": { + "type": "git", + "url": "git://github.com/ashtuchkin/iconv-lite.git" + }, + "scripts": { + "coverage": "istanbul cover _mocha -- --grep .", + "coverage-open": "open coverage/lcov-report/index.html", + "test": "mocha --reporter spec --grep ." + }, + "typings": "./lib/index.d.ts", + "version": "0.4.19" +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 00000000..dea3013d --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +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/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 00000000..b1c56658 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 00000000..3b94763a --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,7 @@ +try { + var util = require('util'); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 00000000..c1e78a75 --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 00000000..fb0c701f --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,65 @@ +{ + "_args": [ + [ + "inherits@2.0.3", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "inherits@2.0.3", + "_id": "inherits@2.0.3", + "_inBundle": false, + "_integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "inherits@2.0.3", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "2.0.3", + "saveSpec": null, + "fetchSpec": "2.0.3" + }, + "_requiredBy": [ + "/http-errors", + "/raw-body/http-errors" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", + "_spec": "2.0.3", + "_where": "C:\\GitHub\\cis411_lab0", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^7.1.0" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "node test" + }, + "version": "2.0.3" +} diff --git a/node_modules/ipaddr.js/README.md b/node_modules/ipaddr.js/README.md new file mode 100644 index 00000000..6876a3b8 --- /dev/null +++ b/node_modules/ipaddr.js/README.md @@ -0,0 +1,233 @@ +# ipaddr.js — an IPv6 and IPv4 address manipulation library [![Build Status](https://travis-ci.org/whitequark/ipaddr.js.svg)](https://travis-ci.org/whitequark/ipaddr.js) + +ipaddr.js is a small (1.9K minified and gzipped) library for manipulating +IP addresses in JavaScript environments. It runs on both CommonJS runtimes +(e.g. [nodejs]) and in a web browser. + +ipaddr.js allows you to verify and parse string representation of an IP +address, match it against a CIDR range or range list, determine if it falls +into some reserved ranges (examples include loopback and private ranges), +and convert between IPv4 and IPv4-mapped IPv6 addresses. + +[nodejs]: http://nodejs.org + +## Installation + +`npm install ipaddr.js` + +or + +`bower install ipaddr.js` + +## API + +ipaddr.js defines one object in the global scope: `ipaddr`. In CommonJS, +it is exported from the module: + +```js +var ipaddr = require('ipaddr.js'); +``` + +The API consists of several global methods and two classes: ipaddr.IPv6 and ipaddr.IPv4. + +### Global methods + +There are three global methods defined: `ipaddr.isValid`, `ipaddr.parse` and +`ipaddr.process`. All of them receive a string as a single parameter. + +The `ipaddr.isValid` method returns `true` if the address is a valid IPv4 or +IPv6 address, and `false` otherwise. It does not throw any exceptions. + +The `ipaddr.parse` method returns an object representing the IP address, +or throws an `Error` if the passed string is not a valid representation of an +IP address. + +The `ipaddr.process` method works just like the `ipaddr.parse` one, but it +automatically converts IPv4-mapped IPv6 addresses to their IPv4 counterparts +before returning. It is useful when you have a Node.js instance listening +on an IPv6 socket, and the `net.ivp6.bindv6only` sysctl parameter (or its +equivalent on non-Linux OS) is set to 0. In this case, you can accept IPv4 +connections on your IPv6-only socket, but the remote address will be mangled. +Use `ipaddr.process` method to automatically demangle it. + +### Object representation + +Parsing methods return an object which descends from `ipaddr.IPv6` or +`ipaddr.IPv4`. These objects share some properties, but most of them differ. + +#### Shared properties + +One can determine the type of address by calling `addr.kind()`. It will return +either `"ipv6"` or `"ipv4"`. + +An address can be converted back to its string representation with `addr.toString()`. +Note that this method: + * does not return the original string used to create the object (in fact, there is + no way of getting that string) + * returns a compact representation (when it is applicable) + +A `match(range, bits)` method can be used to check if the address falls into a +certain CIDR range. +Note that an address can be (obviously) matched only against an address of the same type. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); +var range = ipaddr.parse("2001:db8::"); + +addr.match(range, 32); // => true +``` + +Alternatively, `match` can also be called as `match([range, bits])`. In this way, +it can be used together with the `parseCIDR(string)` method, which parses an IP +address together with a CIDR range. + +For example: + +```js +var addr = ipaddr.parse("2001:db8:1234::1"); + +addr.match(ipaddr.parseCIDR("2001:db8::/32")); // => true +``` + +A `range()` method returns one of predefined names for several special ranges defined +by IP protocols. The exact names (and their respective CIDR ranges) can be looked up +in the source: [IPv6 ranges] and [IPv4 ranges]. Some common ones include `"unicast"` +(the default one) and `"reserved"`. + +You can match against your own range list by using +`ipaddr.subnetMatch(address, rangeList, defaultName)` method. It can work with a mix of IPv6 or IPv4 addresses, and accepts a name-to-subnet map as the range list. For example: + +```js +var rangeList = { + documentationOnly: [ ipaddr.parse('2001:db8::'), 32 ], + tunnelProviders: [ + [ ipaddr.parse('2001:470::'), 32 ], // he.net + [ ipaddr.parse('2001:5c0::'), 32 ] // freenet6 + ] +}; +ipaddr.subnetMatch(ipaddr.parse('2001:470:8:66::1'), rangeList, 'unknown'); // => "tunnelProviders" +``` + +The addresses can be converted to their byte representation with `toByteArray()`. +(Actually, JavaScript mostly does not know about byte buffers. They are emulated with +arrays of numbers, each in range of 0..255.) + +```js +var bytes = ipaddr.parse('2a00:1450:8007::68').toByteArray(); // ipv6.google.com +bytes // => [42, 0x00, 0x14, 0x50, 0x80, 0x07, 0x00, , 0x00, 0x68 ] +``` + +The `ipaddr.IPv4` and `ipaddr.IPv6` objects have some methods defined, too. All of them +have the same interface for both protocols, and are similar to global methods. + +`ipaddr.IPvX.isValid(string)` can be used to check if the string is a valid address +for particular protocol, and `ipaddr.IPvX.parse(string)` is the error-throwing parser. + +`ipaddr.IPvX.isValid(string)` uses the same format for parsing as the POSIX `inet_ntoa` function, which accepts unusual formats like `0xc0.168.1.1` or `0x10000000`. The function `ipaddr.IPv4.isValidFourPartDecimal(string)` validates the IPv4 address and also ensures that it is written in four-part decimal format. + +[IPv6 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L186 +[IPv4 ranges]: https://github.com/whitequark/ipaddr.js/blob/master/src/ipaddr.coffee#L71 + +#### IPv6 properties + +Sometimes you will want to convert IPv6 not to a compact string representation (with +the `::` substitution); the `toNormalizedString()` method will return an address where +all zeroes are explicit. + +For example: + +```js +var addr = ipaddr.parse("2001:0db8::0001"); +addr.toString(); // => "2001:db8::1" +addr.toNormalizedString(); // => "2001:db8:0:0:0:0:0:1" +``` + +The `isIPv4MappedAddress()` method will return `true` if this address is an IPv4-mapped +one, and `toIPv4Address()` will return an IPv4 object address. + +To access the underlying binary representation of the address, use `addr.parts`. + +```js +var addr = ipaddr.parse("2001:db8:10::1234:DEAD"); +addr.parts // => [0x2001, 0xdb8, 0x10, 0, 0, 0, 0x1234, 0xdead] +``` + +A IPv6 zone index can be accessed via `addr.zoneId`: + +```js +var addr = ipaddr.parse("2001:db8::%eth0"); +addr.zoneId // => 'eth0' +``` + +#### IPv4 properties + +`toIPv4MappedAddress()` will return a corresponding IPv4-mapped IPv6 address. + +To access the underlying representation of the address, use `addr.octets`. + +```js +var addr = ipaddr.parse("192.168.1.1"); +addr.octets // => [192, 168, 1, 1] +``` + +`prefixLengthFromSubnetMask()` will return a CIDR prefix length for a valid IPv4 netmask or +false if the netmask is not valid. + +```js +ipaddr.IPv4.parse('255.255.255.240').prefixLengthFromSubnetMask() == 28 +ipaddr.IPv4.parse('255.192.164.0').prefixLengthFromSubnetMask() == null +``` + +`subnetMaskFromPrefixLength()` will return an IPv4 netmask for a valid CIDR prefix length. + +```js +ipaddr.IPv4.subnetMaskFromPrefixLength(24) == "255.255.255.0" +ipaddr.IPv4.subnetMaskFromPrefixLength(29) == "255.255.255.248" +``` + +`broadcastAddressFromCIDR()` will return the broadcast address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.broadcastAddressFromCIDR("172.0.0.1/24") == "172.0.0.255" +``` +`networkAddressFromCIDR()` will return the network address for a given IPv4 interface and netmask in CIDR notation. +```js +ipaddr.IPv4.networkAddressFromCIDR("172.0.0.1/24") == "172.0.0.0" +``` + +#### Conversion + +IPv4 and IPv6 can be converted bidirectionally to and from network byte order (MSB) byte arrays. + +The `fromByteArray()` method will take an array and create an appropriate IPv4 or IPv6 object +if the input satisfies the requirements. For IPv4 it has to be an array of four 8-bit values, +while for IPv6 it has to be an array of sixteen 8-bit values. + +For example: +```js +var addr = ipaddr.fromByteArray([0x7f, 0, 0, 1]); +addr.toString(); // => "127.0.0.1" +``` + +or + +```js +var addr = ipaddr.fromByteArray([0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]) +addr.toString(); // => "2001:db8::1" +``` + +Both objects also offer a `toByteArray()` method, which returns an array in network byte order (MSB). + +For example: +```js +var addr = ipaddr.parse("127.0.0.1"); +addr.toByteArray(); // => [0x7f, 0, 0, 1] +``` + +or + +```js +var addr = ipaddr.parse("2001:db8::1"); +addr.toByteArray(); // => [0x20, 1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] +``` diff --git a/node_modules/ipaddr.js/ipaddr.min.js b/node_modules/ipaddr.js/ipaddr.min.js new file mode 100644 index 00000000..56c227ca --- /dev/null +++ b/node_modules/ipaddr.js/ipaddr.min.js @@ -0,0 +1 @@ +(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;i>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return"ipv6"===(t=this.parse(r)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this); \ No newline at end of file diff --git a/node_modules/ipaddr.js/lib/ipaddr.js b/node_modules/ipaddr.js/lib/ipaddr.js new file mode 100644 index 00000000..ab5d74b4 --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js @@ -0,0 +1,636 @@ +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + + ipaddr = {}; + + root = this; + + if ((typeof module !== "undefined" && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; + } + + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); + } + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; + } + return true; + }; + + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; + + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } + + IPv4.prototype.kind = function() { + return 'ipv4'; + }; + + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; + + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; + + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; + + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; + + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 32 - cidr; + }; + + return IPv4; + + })(); + + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; + + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; + + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } + } + + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; + + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; + + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; + + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; + + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; + + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; + + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; + + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; + + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + + return IPv6; + + })(); + + ipv6Part = "(?:[0-9a-f]+::?)+"; + + zoneIndex = "%[0-9a-z]{1,}"; + + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; + + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; + + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; + + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; + + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; + + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; + + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; + +}).call(this); diff --git a/node_modules/ipaddr.js/lib/ipaddr.js.d.ts b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts new file mode 100644 index 00000000..882fa96d --- /dev/null +++ b/node_modules/ipaddr.js/lib/ipaddr.js.d.ts @@ -0,0 +1,71 @@ + + +declare module "ipaddr.js" { + + type IPv4Range = 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved'; + type IPv6Range = 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved'; + + interface RangeList { + [name: string]: [T, number] | [T, number][]; + } + + + // Common methods/properties for IPv4 and IPv6 classes. + class IP { + + prefixLengthFromSubnetMask(): number | false; + toByteArray(): number[]; + toNormalizedString(): string; + toString(): string; + } + + namespace Address { + + export function isValid(addr: string): boolean; + export function fromByteArray(bytes: number[]): IPv4 | IPv6; + export function parse(addr: string): IPv4 | IPv6; + export function parseCIDR(mask: string): [IPv4 | IPv6, number]; + export function process(address: string): IPv4 | IPv6; + export function subnetMatch(addr: IPv4, rangeList: RangeList, defaultName?: string): string; + export function subnetMatch(addr: IPv6, rangeList: RangeList, defaultName?: string): string; + + export class IPv4 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv4; + static isIPv4(addr: string): boolean; + static isValidFourPartDecimal(addr: string): boolean; + static isValid(addr: string): boolean; + static networkAddressFromCIDR(addr: string): IPv4; + static parse(addr: string): IPv4; + static parseCIDR(addr: string): [IPv4, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv4; + constructor(octets: number[]); + + kind(): 'ipv4'; + match(addr: IPv4, bits: number): boolean; + match(mask: [IPv4, number]): boolean; + range(): IPv4Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4MappedAddress(): IPv6; + } + + export class IPv6 extends IP { + static broadcastAddressFromCIDR(addr: string): IPv6; + static isIPv6(addr: string): boolean; + static isValid(addr: string): boolean; + static parse(addr: string): IPv6; + static parseCIDR(addr: string): [IPv6, number]; + static subnetMaskFromPrefixLength(prefix: number): IPv6; + constructor(octets: number[]); + + isIPv4MappedAddress(): boolean; + kind(): 'ipv6'; + match(addr: IPv6, bits: number): boolean; + match(mask: [IPv6, number]): boolean; + range(): IPv6Range; + subnetMatch(rangeList: RangeList, defaultName?: string): string; + toIPv4Address(): IPv4; + } + } + + export = Address; +} diff --git a/node_modules/ipaddr.js/package.json b/node_modules/ipaddr.js/package.json new file mode 100644 index 00000000..ab3a5fbe --- /dev/null +++ b/node_modules/ipaddr.js/package.json @@ -0,0 +1,72 @@ +{ + "_args": [ + [ + "ipaddr.js@1.8.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "ipaddr.js@1.8.0", + "_id": "ipaddr.js@1.8.0", + "_inBundle": false, + "_integrity": "sha1-6qM9bd16zo9/b+DJygRA5wZzix4=", + "_location": "/ipaddr.js", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ipaddr.js@1.8.0", + "name": "ipaddr.js", + "escapedName": "ipaddr.js", + "rawSpec": "1.8.0", + "saveSpec": null, + "fetchSpec": "1.8.0" + }, + "_requiredBy": [ + "/proxy-addr" + ], + "_resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.8.0.tgz", + "_spec": "1.8.0", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "whitequark", + "email": "whitequark@whitequark.org" + }, + "bugs": { + "url": "https://github.com/whitequark/ipaddr.js/issues" + }, + "dependencies": {}, + "description": "A library for manipulating IPv4 and IPv6 addresses in JavaScript.", + "devDependencies": { + "coffee-script": "~1.12.6", + "nodeunit": ">=0.8.2 <0.8.7", + "uglify-js": "~3.0.19" + }, + "directories": { + "lib": "./lib" + }, + "engines": { + "node": ">= 0.10" + }, + "files": [ + "lib/", + "ipaddr.min.js" + ], + "homepage": "https://github.com/whitequark/ipaddr.js#readme", + "keywords": [ + "ip", + "ipv4", + "ipv6" + ], + "license": "MIT", + "main": "./lib/ipaddr.js", + "name": "ipaddr.js", + "repository": { + "type": "git", + "url": "git://github.com/whitequark/ipaddr.js.git" + }, + "scripts": { + "test": "cake build test" + }, + "types": "./lib/ipaddr.js.d.ts", + "version": "1.8.0" +} diff --git a/node_modules/iterall/LICENSE b/node_modules/iterall/LICENSE new file mode 100644 index 00000000..32653d22 --- /dev/null +++ b/node_modules/iterall/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2016 Lee Byron + +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/iterall/README.md b/node_modules/iterall/README.md new file mode 100644 index 00000000..6a47da9d --- /dev/null +++ b/node_modules/iterall/README.md @@ -0,0 +1,808 @@ +# JavaScript [Iterators][] and [AsyncIterators][] for all! + +[![Build Status](https://travis-ci.org/leebyron/iterall.svg?branch=master)](https://travis-ci.org/leebyron/iterall) [![Coverage Status](https://coveralls.io/repos/github/leebyron/iterall/badge.svg?branch=master)](https://coveralls.io/github/leebyron/iterall?branch=master) ![710 bytes minified and gzipped](https://img.shields.io/badge/min%20gzip%20size-757%20B-blue.svg) + +`iterall` provides a few crucial utilities for implementing and working with +[Iterables][iterators], [Async Iterables][asynciterators] and +[Array-likes][array-like] in all JavaScript environments, even old versions of +Internet Explorer, in a tiny library weighing well under 1KB when minified +and gzipped. + +This is a library for libraries. If your library takes Arrays as input, accept +Iterables instead. If your library implements a new data-structure, make +it Iterable. + +When installed via `npm`, `iterall` comes complete with [Flow][] and +[TypeScript][] definition files. Don't want to take the dependency? Feel free to +copy code directly from this repository. + +```js +// Limited to only Arrays 😥 +if (Array.isArray(thing)) { + thing.forEach(function (item, i) { + console.log('Index: ' + i, item) + }) +} + +// Accepts all Iterables and Array-likes, in any JavaScript environment! 🎉 +var isCollection = require('iterall').isCollection +var forEach = require('iterall').forEach + +if (isCollection(thing)) { + forEach(thing, function (item, i) { + console.log('Index: ' + i, item) + }) +} + +// Accepts all AsyncIterators, in any JavaScript environment! ⏳ +var forAwaitEach = require('iterall').forAwaitEach + +forAwaitEach(thing, function (item, i) { + console.log('Index: ' + i, item) +}).then(function () { + console.log('Done') +}) +``` + +## Why use Iterators? + +For most of JavaScript's history it has provided two collection data-structures: +the `Object` and the `Array`. These collections can conceptually describe nearly +all data and so it's no suprise that libraries expecting lists of +things standardized on expecting and checking for an Array. This pattern even +resulted in the addition of a new method in ES5: [`Array.isArray()`][isarray]. + +As JavaScript applications grew in complexity, moved to the [server][nodejs] +where CPU is a constrained resource, faced new problems and implemented new +algorithms, new data-structures are often required. With options from +[linked lists][linked list] to [HAMTs][hamt] developers can use what is most +efficient and provides the right properties for their program. + +However none of these new data-structures can be used in libraries where an +`Array` is expected, which means developers are often stuck between abandoning +their favorite libraries or limiting their data-structure choices at the cost of +efficiency or usefulness. + +To enable many related data-structures to be used interchangably we need a +_[protocol][]_, and luckily for us ES2015 introduced the +[Iteration Protocols][iterators] to describe all list-like data-structures which +can be iterated. That includes not just the new-to-ES2015 [Map][] and [Set][] +collections but also existing ones like [arguments][], [NodeList][] and the +various [TypedArray][], all of which return `false` for [`Array.isArray()`][isarray] +and in ES2015 implement the [Iterator protocol][iterators]. + +While Iterators are defined in ES2015, they _do not require_ ES2015 to work +correctly. In fact, Iterators were first introduced in 2012 in [Firefox v17](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Iterator_property_and_iterator_symbol). Rather than using [`Symbol.iterator`][symbol.iterator], they used the property name `"@@iterator"` (in fact, the ECMAScript +spec still refers to well-known `Symbols` using this `@@` shorthand). By falling +back to use `"@@iterator"` when `Symbol.iterator` is not defined, Iterators can +be both safely defined and used by _any version of JavaScript_. + +Not only were Iterables defined in ES2015, they were also implemented by the +built-in data-structures including [Array][array#@@iterator]. Older JavaScript +environments do not implement `Array.prototype[@@iterator]()`, however this is +only a minor problem. JavaScript has another related and much older protocol: +[Array-like]. A value is "Array-like" if it has a numeric `length` property and +indexed access, but does not necessarily have methods like `.push()` or `.forEach()`. +Much like [`Array.from`][array.from], `iterall`'s `forEach()` and +`createIterator()` methods also accept collections which are not Iterable but +are Array-like. This means that `iterall` can be used with [Array][], +[arguments][], [NodeList][], [TypedArray][] and other Array-like collections +regardless of the JavaScript environment. + +When libraries only accept Arrays as input, they stick developers with a tough +choice: limit which data-structures can be used or limit the ability to use that +library. Accepting Iterables removes this false dichotomy, and allows libraries +to be more generally useful. There's no need to limit to ES2015 environments and +bleeding-edge browsers to accept `Iterable`. + +Only using Arrays can limit the efficiency and usefulness of your application +code, but custom data-structures can often feel like a fish out of water in +JavaScript programs, only working with code written specifically for it. +Protocols like `Iterable` helps these new data-structures work with more +libraries and built-in JavaScript behavior. There's no need to limit to ES2015 +environments and bleeding-edge browsers to implement `Iterable`. + +## Why use AsyncIterators? + +In the same way that `Iterator` provides a common interface for accessing many +different kinds of data-structures, `AsyncIterator` provides a common interface +over an asynchronous sequence of values (similar to Stream or Observable). + +Async Iterators are not yet an official part of JavaScript, however they're +a "Stage 3" proposal to be added, and browser vendors are +[working on adding support](https://bugs.chromium.org/p/v8/issues/detail?id=5855). +However, Async Iterators can be both safely defined and used today by +_any version of JavaScript_, by using the utilities in `iterall`. + +## FAQ + +> Aren't Iterables slower than Arrays? I want the highest performance possible. + +Arrays _are_ Iterables. Iterable is a protocol that Arrays adhere to in ES2015. +It's true that creating an Iterator and stepping through it can present some +overhead compared to a simple for-loop or `array.forEach`. However `iterall`'s +`forEach` will delegate directly to `array.forEach` and will use a for-loop for +Array-like objects, ensuring the best performance for Arrays while still +maintaining support for all Iterables. + +> Should my library functions also return Iterables instead of Arrays? Won't +> that be limiting? + +That could definitely be limiting if you return some generic Iterable where you +could have returned an Array, and (depending on context) I wouldn't recommend +you stop returning Arrays from functions if that's what you're doing today. +However if your functions are returning some collection data-structure that is +_not_ an Array, you should certainly consider having them implement the +Iterable protocol so they can be more widely useful. + +Here are a few examples: + +In [React][], render functions are expected to return view trees, where any +node (e.g. a `
    `) can have many children (e.g. many `
  • `). While it could +expect those children to always be represented as an Array, that would limit +React's usefulness - other data-structures couldn't be used. Instead, React +expects those children to be represented as an _Iterable_. That allows it to +continue to accept Arrays, but also accept many other data-structures. + +[Immutable.js][] implements many new kinds of data-structures (including [HAMT]) +all of which implement _Iterable_, which allows them to be used in many of +JavaScript's built-in functions, but also allows them to be used by many +libraries which accept Iterables, including React. Also, similar to +[`Array.from`][array.from], Immutable.js's constructors accept not only Arrays, +but any _Iterable_, allowing you to build any of these new data-structures from +any other data-structure. + +> Where are all the other functions like `map`, `filter`, and `reduce`? + +Those "higher order" collection functions are awesome, but they don't belong in +this library. Instead this library should be used as a basis for building such +a library (as it should be used for many other libraries). The `forEach` +function provided by `iterall` can be used as the underpinning for these. + +As an example: + +```js +function reduce (collection, reducer, initial) { + var reduced = initial + forEach(collection, function (item) { + reduced = reducer(reduced, item) + }) + return reduced +} +``` + +> How do I break out of a `forEach` or `forAwaitEach` loop early? + +While `for of` and `for await of` loops allow breaking out of a loop early with +a `break` statement, the `forEach()` and `forAwaitEach()` functions (much like +Array's `forEach`) do not support early breaking. + +Similar to the "higher order" functions described above, this library can be the +basis for this extended behavior. To support early break outs, you can use a +wrapping function supporting early breaking by throwing a `BREAK` sentinel value +from the callback and using a try/catch block to early break: + +```js +const BREAK = {} + +function forEachBreakable (collection, callback) { + try { + forEach(collection, callback) + } catch (error) { + if (error !== BREAK) { + throw error + } + } +} + +async function forAwaitEachBreakable (collection, callback) { + try { + await forAwaitEach(collection, callback) + } catch (error) { + if (error !== BREAK) { + throw error + } + } +} + +// Example usages: +forEachBreakable(obj, function (value) { + if (shouldBreakOn(value)) { + throw BREAK + } + console.log(value) +}) + +forAwaitEachBreakable(obj, async function (value) { + if (await shouldBreakOn(value)) { + throw BREAK + } + console.log(value) +}) +``` + +Note: This technique also works with the native Array `forEach` method! + + + +## API + + + +#### Table of Contents + +- [Iterable](#iterable) +- [Iterator](#iterator) +- [$$iterator](#iterator-1) +- [isIterable](#isiterable) +- [isArrayLike](#isarraylike) +- [isCollection](#iscollection) +- [getIterator](#getiterator) +- [getIteratorMethod](#getiteratormethod) +- [createIterator](#createiterator) +- [forEach](#foreach) +- [AsyncIterable](#asynciterable) +- [AsyncIterator](#asynciterator) +- [$$asyncIterator](#asynciterator-1) +- [isAsyncIterable](#isasynciterable) +- [getAsyncIterator](#getasynciterator) +- [getAsyncIteratorMethod](#getasynciteratormethod) +- [createAsyncIterator](#createasynciterator) +- [forAwaitEach](#forawaiteach) + +### Iterable + +- **See: [MDN Iteration protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable)** + +[Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) +is a _protocol_ which when implemented allows a JavaScript object to define +their iteration behavior, such as what values are looped over in a +[`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) +loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) +implement the Iterable protocol, including `Array` and `Map`. + +While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) +it can be utilized by any version of JavaScript. + +### Iterator + +- **See: [MDN Iteration protocols](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator)** + +[Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) +is a _protocol_ which describes a standard way to produce a sequence of +values, typically the values of the Iterable represented by this Iterator. + +While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) +it can be utilized by any version of JavaScript. + +### $$iterator + +A property name to be used as the name of an Iterable's method responsible +for producing an Iterator, referred to as `@@iterator`. Typically represents +the value `Symbol.iterator` but falls back to the string `"@@iterator"` when +`Symbol.iterator` is not defined. + +Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, +but do not use it for accessing existing Iterables, instead use +[getIterator](#getiterator) or [isIterable](#isiterable). + +**Examples** + +```javascript +var $$iterator = require('iterall').$$iterator + +function Counter (to) { + this.to = to +} + +Counter.prototype[$$iterator] = function () { + return { + to: this.to, + num: 0, + next () { + if (this.num >= this.to) { + return { value: undefined, done: true } + } + return { value: this.num++, done: false } + } + } +} + +var counter = new Counter(3) +for (var number of counter) { + console.log(number) // 0 ... 1 ... 2 +} +``` + +### isIterable + +Returns true if the provided object implements the Iterator protocol via +either implementing a `Symbol.iterator` or `"@@iterator"` method. + +**Parameters** + +- `obj` A value which might implement the Iterable protocol. + +**Examples** + +```javascript +var isIterable = require('iterall').isIterable +isIterable([ 1, 2, 3 ]) // true +isIterable('ABC') // true +isIterable({ length: 1, 0: 'Alpha' }) // false +isIterable({ key: 'value' }) // false +isIterable(new Map()) // true +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if Iterable. + +### isArrayLike + +Returns true if the provided object implements the Array-like protocol via +defining a positive-integer `length` property. + +**Parameters** + +- `obj` A value which might implement the Array-like protocol. + +**Examples** + +```javascript +var isArrayLike = require('iterall').isArrayLike +isArrayLike([ 1, 2, 3 ]) // true +isArrayLike('ABC') // true +isArrayLike({ length: 1, 0: 'Alpha' }) // true +isArrayLike({ key: 'value' }) // false +isArrayLike(new Map()) // false +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if Array-like. + +### isCollection + +Returns true if the provided object is an Object (i.e. not a string literal) +and is either Iterable or Array-like. + +This may be used in place of [Array.isArray()][isarray] to determine if an +object should be iterated-over. It always excludes string literals and +includes Arrays (regardless of if it is Iterable). It also includes other +Array-like objects such as NodeList, TypedArray, and Buffer. + +**Parameters** + +- `obj` An Object value which might implement the Iterable or Array-like protocols. + +**Examples** + +```javascript +var isCollection = require('iterall').isCollection +isCollection([ 1, 2, 3 ]) // true +isCollection('ABC') // false +isCollection({ length: 1, 0: 'Alpha' }) // true +isCollection({ key: 'value' }) // false +isCollection(new Map()) // true +``` + +```javascript +var forEach = require('iterall').forEach +if (isCollection(obj)) { + forEach(obj, function (value) { + console.log(value) + }) +} +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if Iterable or Array-like Object. + +### getIterator + +If the provided object implements the Iterator protocol, its Iterator object +is returned. Otherwise returns undefined. + +**Parameters** + +- `iterable` **[Iterable](#iterable)<T>** An Iterable object which is the source of an Iterator. + +**Examples** + +```javascript +var getIterator = require('iterall').getIterator +var iterator = getIterator([ 1, 2, 3 ]) +iterator.next() // { value: 1, done: false } +iterator.next() // { value: 2, done: false } +iterator.next() // { value: 3, done: false } +iterator.next() // { value: undefined, done: true } +``` + +Returns **[Iterator](#iterator)<T>** new Iterator instance. + +### getIteratorMethod + +If the provided object implements the Iterator protocol, the method +responsible for producing its Iterator object is returned. + +This is used in rare cases for performance tuning. This method must be called +with obj as the contextual this-argument. + +**Parameters** + +- `iterable` **[Iterable](#iterable)<T>** An Iterable object which defines an `@@iterator` method. + +**Examples** + +```javascript +var getIteratorMethod = require('iterall').getIteratorMethod +var myArray = [ 1, 2, 3 ] +var method = getIteratorMethod(myArray) +if (method) { + var iterator = method.call(myArray) +} +``` + +Returns **function (): [Iterator](#iterator)<T>** `@@iterator` method. + +### createIterator + +Similar to [getIterator](#getiterator), this method returns a new Iterator given an +Iterable. However it will also create an Iterator for a non-Iterable +Array-like collection, such as Array in a non-ES2015 environment. + +`createIterator` is complimentary to `forEach`, but allows a "pull"-based +iteration as opposed to `forEach`'s "push"-based iteration. + +`createIterator` produces an Iterator for Array-likes with the same behavior +as ArrayIteratorPrototype described in the ECMAScript specification, and +does _not_ skip over "holes". + +**Parameters** + +- `collection` **([Iterable](#iterable)<T> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** An Iterable or Array-like object to produce an Iterator. + +**Examples** + +```javascript +var createIterator = require('iterall').createIterator + +var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } +var iterator = createIterator(myArraylike) +iterator.next() // { value: 'Alpha', done: false } +iterator.next() // { value: 'Bravo', done: false } +iterator.next() // { value: 'Charlie', done: false } +iterator.next() // { value: undefined, done: true } +``` + +Returns **[Iterator](#iterator)<T>** new Iterator instance. + +### forEach + +Given an object which either implements the Iterable protocol or is +Array-like, iterate over it, calling the `callback` at each iteration. + +Use `forEach` where you would expect to use a `for ... of` loop in ES6. +However `forEach` adheres to the behavior of [Array#forEach][] described in +the ECMAScript specification, skipping over "holes" in Array-likes. It will +also delegate to a `forEach` method on `collection` if one is defined, +ensuring native performance for `Arrays`. + +Similar to [Array#forEach][], the `callback` function accepts three +arguments, and is provided with `thisArg` as the calling context. + +Note: providing an infinite Iterator to forEach will produce an error. + +[array#foreach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + +**Parameters** + +- `collection` **([Iterable](#iterable)<T> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** The Iterable or array to iterate over. +- `callback` **function (T, [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** Function to execute for each iteration, taking up to three arguments +- `thisArg` Optional. Value to use as `this` when executing `callback`. + +**Examples** + +```javascript +var forEach = require('iterall').forEach + +forEach(myIterable, function (value, index, iterable) { + console.log(value, index, iterable === myIterable) +}) +``` + +```javascript +// ES6: +for (let value of myIterable) { + console.log(value) +} + +// Any JavaScript environment: +forEach(myIterable, function (value) { + console.log(value) +}) +``` + +### AsyncIterable + +- **See: [Async Iteration Proposal](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface)** + +[AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface) +is a _protocol_ which when implemented allows a JavaScript object to define +an asynchronous iteration behavior, such as what values are looped over in +a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) +loop or `iterall`'s [forAwaitEach](#forawaiteach) function. + +While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) +it can be utilized by any version of JavaScript. + +### AsyncIterator + +- **See: [Async Iteration Proposal](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface)** + +[AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface) +is a _protocol_ which describes a standard way to produce and consume an +asynchronous sequence of values, typically the values of the +[AsyncIterable](#asynciterable) represented by this [AsyncIterator](#asynciterator). + +AsyncIterator is similar to Observable or Stream. Like an [Iterator](#iterator) it +also as a `next()` method, however instead of an IteratorResult, +calling this method returns a [Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise) for a IteratorResult. + +While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) +it can be utilized by any version of JavaScript. + +### $$asyncIterator + +A property name to be used as the name of an AsyncIterable's method +responsible for producing an Iterator, referred to as `@@asyncIterator`. +Typically represents the value `Symbol.asyncIterator` but falls back to the +string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + +Use `$$asyncIterator` for defining new AsyncIterables instead of +`Symbol.asyncIterator`, but do not use it for accessing existing Iterables, +instead use [getAsyncIterator](#getasynciterator) or [isAsyncIterable](#isasynciterable). + +**Examples** + +```javascript +var $$asyncIterator = require('iterall').$$asyncIterator + +function Chirper (to) { + this.to = to +} + +Chirper.prototype[$$asyncIterator] = function () { + return { + to: this.to, + num: 0, + next () { + return new Promise(resolve => { + if (this.num >= this.to) { + resolve({ value: undefined, done: true }) + } else { + setTimeout(() => { + resolve({ value: this.num++, done: false }) + }, 1000) + } + }) + } + } +} + +var chirper = new Chirper(3) +for await (var number of chirper) { + console.log(number) // 0 ...wait... 1 ...wait... 2 +} +``` + +### isAsyncIterable + +Returns true if the provided object implements the AsyncIterator protocol via +either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + +**Parameters** + +- `obj` A value which might implement the AsyncIterable protocol. + +**Examples** + +```javascript +var isAsyncIterable = require('iterall').isAsyncIterable +isAsyncIterable(myStream) // true +isAsyncIterable('ABC') // false +``` + +Returns **[boolean](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean)** true if AsyncIterable. + +### getAsyncIterator + +If the provided object implements the AsyncIterator protocol, its +AsyncIterator object is returned. Otherwise returns undefined. + +**Parameters** + +- `asyncIterable` **[AsyncIterable](#asynciterable)<T>** An AsyncIterable object which is the source of an AsyncIterator. + +**Examples** + +```javascript +var getAsyncIterator = require('iterall').getAsyncIterator +var asyncIterator = getAsyncIterator(myStream) +asyncIterator.next().then(console.log) // { value: 1, done: false } +asyncIterator.next().then(console.log) // { value: 2, done: false } +asyncIterator.next().then(console.log) // { value: 3, done: false } +asyncIterator.next().then(console.log) // { value: undefined, done: true } +``` + +Returns **[AsyncIterator](#asynciterator)<T>** new AsyncIterator instance. + +### getAsyncIteratorMethod + +If the provided object implements the AsyncIterator protocol, the method +responsible for producing its AsyncIterator object is returned. + +This is used in rare cases for performance tuning. This method must be called +with obj as the contextual this-argument. + +**Parameters** + +- `asyncIterable` **[AsyncIterable](#asynciterable)<T>** An AsyncIterable object which defines an `@@asyncIterator` method. + +**Examples** + +```javascript +var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod +var method = getAsyncIteratorMethod(myStream) +if (method) { + var asyncIterator = method.call(myStream) +} +``` + +Returns **function (): [AsyncIterator](#asynciterator)<T>** `@@asyncIterator` method. + +### createAsyncIterator + +Similar to [getAsyncIterator](#getasynciterator), this method returns a new AsyncIterator +given an AsyncIterable. However it will also create an AsyncIterator for a +non-async Iterable as well as non-Iterable Array-like collection, such as +Array in a pre-ES2015 environment. + +`createAsyncIterator` is complimentary to `forAwaitEach`, but allows a +buffering "pull"-based iteration as opposed to `forAwaitEach`'s +"push"-based iteration. + +`createAsyncIterator` produces an AsyncIterator for non-async Iterables as +described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + +> Note: Creating `AsyncIterator`s requires the existence of `Promise`. +> While `Promise` has been available in modern browsers for a number of +> years, legacy browsers (like IE 11) may require a polyfill. + +**Parameters** + +- `source` **([AsyncIterable](#asynciterable)<T> | [Iterable](#iterable)<T> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + +**Examples** + +```javascript +var createAsyncIterator = require('iterall').createAsyncIterator + +var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } +var iterator = createAsyncIterator(myArraylike) +iterator.next().then(console.log) // { value: 'Alpha', done: false } +iterator.next().then(console.log) // { value: 'Bravo', done: false } +iterator.next().then(console.log) // { value: 'Charlie', done: false } +iterator.next().then(console.log) // { value: undefined, done: true } +``` + +Returns **[AsyncIterator](#asynciterator)<T>** new AsyncIterator instance. + +### forAwaitEach + +Given an object which either implements the AsyncIterable protocol or is +Array-like, iterate over it, calling the `callback` at each iteration. + +Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop. + +Similar to [Array#forEach][], the `callback` function accepts three +arguments, and is provided with `thisArg` as the calling context. + +> Note: Using `forAwaitEach` requires the existence of `Promise`. +> While `Promise` has been available in modern browsers for a number of +> years, legacy browsers (like IE 11) may require a polyfill. + +**Parameters** + +- `source` **([AsyncIterable](#asynciterable)<T> | [Iterable](#iterable)<([Promise](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Promise)<T> | T)> | {length: [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number)})** The AsyncIterable or array to iterate over. +- `callback` **function (T, [number](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number), [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object))** Function to execute for each iteration, taking up to three arguments +- `thisArg` Optional. Value to use as `this` when executing `callback`. + +**Examples** + +```javascript +var forAwaitEach = require('iterall').forAwaitEach + +forAwaitEach(myIterable, function (value, index, iterable) { + console.log(value, index, iterable === myIterable) +}) +``` + +```javascript +// ES2017: +for await (let value of myAsyncIterable) { + console.log(await doSomethingAsync(value)) +} +console.log('done') + +// Any JavaScript environment: +forAwaitEach(myAsyncIterable, function (value) { + return doSomethingAsync(value).then(console.log) +}).then(function () { + console.log('done') +}) +``` + +## Contributing + +Contributions are welcome and encouraged! + +Remember that this library is designed to be small, straight-forward, and +well-tested. The value of new additional features will be weighed against their +size. This library also seeks to leverage and mirror the +[ECMAScript specification][] in its behavior as much as possible and reasonable. + +This repository has far more documentation and explanation than code, and it is +expected that the majority of contributions will come in the form of improving +these. + + + +[arguments]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments + +[array#@@iterator]: (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) + +[array-like]: http://www.2ality.com/2013/05/quirk-array-like-objects.html + +[array.from]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from + +[array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array + +[ecmascript specification]: http://www.ecma-international.org/ecma-262/6.0/ + +[flow]: https://flowtype.org/ + +[hamt]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie + +[isarray]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray + +[iterators]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols + +[asynciterators]: https://tc39.github.io/proposal-async-iteration/ + +[linked list]: https://en.wikipedia.org/wiki/Linked_list + +[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map + +[nodejs]: https://nodejs.org/ + +[nodelist]: https://developer.mozilla.org/en-US/docs/Web/API/NodeList + +[protocol]: https://en.wikipedia.org/wiki/Protocol_(object-oriented_programming) + +[react]: https://facebook.github.io/react/ + +[set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set + +[symbol.iterator]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator + +[typedarray]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray + +[typescript]: http://www.typescriptlang.org/ + +[immutable.js]: http://facebook.github.io/immutable-js/ diff --git a/node_modules/iterall/index.d.ts b/node_modules/iterall/index.d.ts new file mode 100644 index 00000000..e976c319 --- /dev/null +++ b/node_modules/iterall/index.d.ts @@ -0,0 +1,90 @@ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +// Note: TypeScript already has built-in definitions for +// Iterable, Iterator, AsyncIterable, and AsyncIterator so they are not +// defined here. However you may need to configure TypeScript to include them. + +export var $$iterator: symbol + +export function isIterable(obj: any): obj is Iterable + +export function isArrayLike(obj: any): obj is { length: number } + +export function isCollection(obj: any): obj is Iterable | { length: number } + +export function getIterator( + iterable: Iterable +): Iterator +export function getIterator(iterable: any): void | Iterator + +export function getIteratorMethod( + iterable: Iterable +): () => Iterator +export function getIteratorMethod(iterable: any): void | (() => Iterator) + +export function createIterator( + collection: Iterable +): Iterator +export function createIterator(collection: { length: number }): Iterator +export function createIterator(collection: any): void | Iterator + +export function forEach>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any +): void +export function forEach( + collection: TCollection, + callbackFn: (value: any, index: number, collection: TCollection) => any, + thisArg?: any +): void + +export var $$asyncIterator: symbol + +export function isAsyncIterable(obj: any): obj is AsyncIterable + +export function getAsyncIterator( + asyncIterable: AsyncIterable +): AsyncIterator +export function getAsyncIterator( + asyncIterable: any +): void | AsyncIterator + +export function getAsyncIteratorMethod( + asyncIterable: AsyncIterable +): () => AsyncIterator +export function getAsyncIteratorMethod( + asyncIterable: any +): void | (() => AsyncIterator) + +export function createAsyncIterator( + collection: AsyncIterable | Iterable | TValue> +): AsyncIterator +export function createAsyncIterator( + collection: {length: number} +): AsyncIterator +export function createAsyncIterator( + collection: any +): void | AsyncIterator + +export function forAwaitEach>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any +): Promise +export function forAwaitEach | TValue>>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any +): Promise +export function forAwaitEach( + collection: TCollection, + callbackFn: (value: any, index: number, collection: TCollection) => any, + thisArg?: any +): Promise diff --git a/node_modules/iterall/index.js b/node_modules/iterall/index.js new file mode 100644 index 00000000..c80aecb6 --- /dev/null +++ b/node_modules/iterall/index.js @@ -0,0 +1,180 @@ +'use strict'; + +exports.isIterable = isIterable; +exports.isArrayLike = isArrayLike; +exports.isCollection = isCollection; +exports.getIterator = getIterator; +exports.getIteratorMethod = getIteratorMethod; +exports.createIterator = createIterator; +exports.forEach = forEach; +exports.isAsyncIterable = isAsyncIterable; +exports.getAsyncIterator = getAsyncIterator; +exports.getAsyncIteratorMethod = getAsyncIteratorMethod; +exports.createAsyncIterator = createAsyncIterator; +exports.forAwaitEach = forAwaitEach; + +var SYMBOL = typeof Symbol === 'function' ? Symbol : void 0; + +var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator; + +var $$iterator = exports.$$iterator = SYMBOL_ITERATOR || '@@iterator'; + +function isIterable(obj) { + return !!getIteratorMethod(obj); +} + +function isArrayLike(obj) { + var length = obj != null && obj.length; + return typeof length === 'number' && length >= 0 && length % 1 === 0; +} + +function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)); +} + +function getIterator(iterable) { + var method = getIteratorMethod(iterable); + if (method) { + return method.call(iterable); + } +} + +function getIteratorMethod(iterable) { + if (iterable != null) { + var method = SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR] || iterable['@@iterator']; + if (typeof method === 'function') { + return method; + } + } +} + +function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection); + if (iterator) { + return iterator; + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection); + } + } +} + +function ArrayLikeIterator(obj) { + this._o = obj; + this._i = 0; +} + +ArrayLikeIterator.prototype[$$iterator] = function () { + return this; +}; + +ArrayLikeIterator.prototype.next = function () { + if (this._o === void 0 || this._i >= this._o.length) { + this._o = void 0; + return { value: void 0, done: true }; + } + return { value: this._o[this._i++], done: false }; +}; + +function forEach(collection, callback, thisArg) { + if (collection != null) { + if (typeof collection.forEach === 'function') { + return collection.forEach(callback, thisArg); + } + var i = 0; + var iterator = getIterator(collection); + if (iterator) { + var step; + while (!(step = iterator.next()).done) { + callback.call(thisArg, step.value, i++, collection); + + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.'); + } + } + } else if (isArrayLike(collection)) { + for (; i < collection.length; i++) { + if (collection.hasOwnProperty(i)) { + callback.call(thisArg, collection[i], i, collection); + } + } + } + } +} + +var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator; + +var $$asyncIterator = exports.$$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator'; + +function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj); +} + +function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable); + if (method) { + return method.call(asyncIterable); + } +} + +function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR] || asyncIterable['@@asyncIterator']; + if (typeof method === 'function') { + return method; + } + } +} + +function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source); + if (asyncIterator) { + return asyncIterator; + } + var iterator = createIterator(source); + if (iterator) { + return new AsyncFromSyncIterator(iterator); + } + } +} + +function AsyncFromSyncIterator(iterator) { + this._i = iterator; +} + +AsyncFromSyncIterator.prototype[$$asyncIterator] = function () { + return this; +}; + +AsyncFromSyncIterator.prototype.next = function () { + var step = this._i.next(); + return Promise.resolve(step.value).then(function (value) { + return { value: value, done: step.done }; + }); +}; + +function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source); + if (asyncIterator) { + var i = 0; + return new Promise(function (resolve, reject) { + function next() { + asyncIterator.next().then(function (step) { + if (!step.done) { + Promise.resolve(callback.call(thisArg, step.value, i++, source)).then(next).catch(reject); + } else { + resolve(); + } + + return null; + }).catch(reject); + + return null; + } + next(); + }); + } +} + diff --git a/node_modules/iterall/index.js.flow b/node_modules/iterall/index.js.flow new file mode 100644 index 00000000..fa3002a9 --- /dev/null +++ b/node_modules/iterall/index.js.flow @@ -0,0 +1,702 @@ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @ignore + */ + +/** + * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) + * is a *protocol* which describes a standard way to produce a sequence of + * values, typically the values of the Iterable represented by this Iterator. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterator + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator|MDN Iteration protocols} + */ + +/** + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) + * is a *protocol* which when implemented allows a JavaScript object to define + * their iteration behavior, such as what values are looped over in a + * [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) + * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) + * implement the Iterable protocol, including `Array` and `Map`. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterable + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|MDN Iteration protocols} + */ + +// In ES2015 environments, Symbol exists +var SYMBOL /*: any */ = typeof Symbol === 'function' ? Symbol : void 0 + +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator + +/** + * A property name to be used as the name of an Iterable's method responsible + * for producing an Iterator, referred to as `@@iterator`. Typically represents + * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when + * `Symbol.iterator` is not defined. + * + * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, + * but do not use it for accessing existing Iterables, instead use + * {@link getIterator} or {@link isIterable}. + * + * @example + * + * var $$iterator = require('iterall').$$iterator + * + * function Counter (to) { + * this.to = to + * } + * + * Counter.prototype[$$iterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * if (this.num >= this.to) { + * return { value: undefined, done: true } + * } + * return { value: this.num++, done: false } + * } + * } + * } + * + * var counter = new Counter(3) + * for (var number of counter) { + * console.log(number) // 0 ... 1 ... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$iterator: '@@iterator'; */ +export var $$iterator = SYMBOL_ITERATOR || '@@iterator' + +/** + * Returns true if the provided object implements the Iterator protocol via + * either implementing a `Symbol.iterator` or `"@@iterator"` method. + * + * @example + * + * var isIterable = require('iterall').isIterable + * isIterable([ 1, 2, 3 ]) // true + * isIterable('ABC') // true + * isIterable({ length: 1, 0: 'Alpha' }) // false + * isIterable({ key: 'value' }) // false + * isIterable(new Map()) // true + * + * @param obj + * A value which might implement the Iterable protocol. + * @return {boolean} true if Iterable. + */ +/*:: declare export function isIterable(obj: any): boolean; */ +export function isIterable(obj) { + return !!getIteratorMethod(obj) +} + +/** + * Returns true if the provided object implements the Array-like protocol via + * defining a positive-integer `length` property. + * + * @example + * + * var isArrayLike = require('iterall').isArrayLike + * isArrayLike([ 1, 2, 3 ]) // true + * isArrayLike('ABC') // true + * isArrayLike({ length: 1, 0: 'Alpha' }) // true + * isArrayLike({ key: 'value' }) // false + * isArrayLike(new Map()) // false + * + * @param obj + * A value which might implement the Array-like protocol. + * @return {boolean} true if Array-like. + */ +/*:: declare export function isArrayLike(obj: any): boolean; */ +export function isArrayLike(obj) { + var length = obj != null && obj.length + return typeof length === 'number' && length >= 0 && length % 1 === 0 +} + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and is either Iterable or Array-like. + * + * This may be used in place of [Array.isArray()][isArray] to determine if an + * object should be iterated-over. It always excludes string literals and + * includes Arrays (regardless of if it is Iterable). It also includes other + * Array-like objects such as NodeList, TypedArray, and Buffer. + * + * @example + * + * var isCollection = require('iterall').isCollection + * isCollection([ 1, 2, 3 ]) // true + * isCollection('ABC') // false + * isCollection({ length: 1, 0: 'Alpha' }) // true + * isCollection({ key: 'value' }) // false + * isCollection(new Map()) // true + * + * @example + * + * var forEach = require('iterall').forEach + * if (isCollection(obj)) { + * forEach(obj, function (value) { + * console.log(value) + * }) + * } + * + * @param obj + * An Object value which might implement the Iterable or Array-like protocols. + * @return {boolean} true if Iterable or Array-like Object. + */ +/*:: declare export function isCollection(obj: any): boolean; */ +export function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)) +} + +/** + * If the provided object implements the Iterator protocol, its Iterator object + * is returned. Otherwise returns undefined. + * + * @example + * + * var getIterator = require('iterall').getIterator + * var iterator = getIterator([ 1, 2, 3 ]) + * iterator.next() // { value: 1, done: false } + * iterator.next() // { value: 2, done: false } + * iterator.next() // { value: 3, done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which is the source of an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var getIterator: + & (<+TValue>(iterable: Iterable) => Iterator) + & ((iterable: mixed) => void | Iterator); */ +export function getIterator(iterable) { + var method = getIteratorMethod(iterable) + if (method) { + return method.call(iterable) + } +} + +/** + * If the provided object implements the Iterator protocol, the method + * responsible for producing its Iterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getIteratorMethod = require('iterall').getIteratorMethod + * var myArray = [ 1, 2, 3 ] + * var method = getIteratorMethod(myArray) + * if (method) { + * var iterator = method.call(myArray) + * } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which defines an `@@iterator` method. + * @return {function(): Iterator} `@@iterator` method. + */ +/*:: declare export var getIteratorMethod: + & (<+TValue>(iterable: Iterable) => (() => Iterator)) + & ((iterable: mixed) => (void | (() => Iterator))); */ +export function getIteratorMethod(iterable) { + if (iterable != null) { + var method = + (SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getIterator}, this method returns a new Iterator given an + * Iterable. However it will also create an Iterator for a non-Iterable + * Array-like collection, such as Array in a non-ES2015 environment. + * + * `createIterator` is complimentary to `forEach`, but allows a "pull"-based + * iteration as opposed to `forEach`'s "push"-based iteration. + * + * `createIterator` produces an Iterator for Array-likes with the same behavior + * as ArrayIteratorPrototype described in the ECMAScript specification, and + * does *not* skip over "holes". + * + * @example + * + * var createIterator = require('iterall').createIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createIterator(myArraylike) + * iterator.next() // { value: 'Alpha', done: false } + * iterator.next() // { value: 'Bravo', done: false } + * iterator.next() // { value: 'Charlie', done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * An Iterable or Array-like object to produce an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var createIterator: + & (<+TValue>(collection: Iterable) => Iterator) + & ((collection: {length: number}) => Iterator) + & ((collection: mixed) => (void | Iterator)); */ +export function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection) + if (iterator) { + return iterator + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection) + } + } +} + +// When the object provided to `createIterator` is not Iterable but is +// Array-like, this simple Iterator is created. +function ArrayLikeIterator(obj) { + this._o = obj + this._i = 0 +} + +// Note: all Iterators are themselves Iterable. +ArrayLikeIterator.prototype[$$iterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +ArrayLikeIterator.prototype.next = function() { + if (this._o === void 0 || this._i >= this._o.length) { + this._o = void 0 + return { value: void 0, done: true } + } + return { value: this._o[this._i++], done: false } +} + +/** + * Given an object which either implements the Iterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forEach` where you would expect to use a `for ... of` loop in ES6. + * However `forEach` adheres to the behavior of [Array#forEach][] described in + * the ECMAScript specification, skipping over "holes" in Array-likes. It will + * also delegate to a `forEach` method on `collection` if one is defined, + * ensuring native performance for `Arrays`. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * Note: providing an infinite Iterator to forEach will produce an error. + * + * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + * + * @example + * + * var forEach = require('iterall').forEach + * + * forEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES6: + * for (let value of myIterable) { + * console.log(value) + * } + * + * // Any JavaScript environment: + * forEach(myIterable, function (value) { + * console.log(value) + * }) + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * The Iterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forEach: + & (<+TValue, TCollection: Iterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => void) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => void); */ +export function forEach(collection, callback, thisArg) { + if (collection != null) { + if (typeof collection.forEach === 'function') { + return collection.forEach(callback, thisArg) + } + var i = 0 + var iterator = getIterator(collection) + if (iterator) { + var step + while (!(step = iterator.next()).done) { + callback.call(thisArg, step.value, i++, collection) + // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + /* istanbul ignore if */ + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.') + } + } + } else if (isArrayLike(collection)) { + for (; i < collection.length; i++) { + if (collection.hasOwnProperty(i)) { + callback.call(thisArg, collection[i], i, collection) + } + } + } + } +} + +///////////////////////////////////////////////////// +// // +// ASYNC ITERATORS // +// // +///////////////////////////////////////////////////// + +/** + * [AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface) + * is a *protocol* which when implemented allows a JavaScript object to define + * an asynchronous iteration behavior, such as what values are looped over in + * a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) + * loop or `iterall`'s {@link forAwaitEach} function. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterable + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface|Async Iteration Proposal} + * @template T The type of each iterated value + * @property {function (): AsyncIterator} Symbol.asyncIterator + * A method which produces an AsyncIterator for this AsyncIterable. + */ + +/** + * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface) + * is a *protocol* which describes a standard way to produce and consume an + * asynchronous sequence of values, typically the values of the + * {@link AsyncIterable} represented by this {@link AsyncIterator}. + * + * AsyncIterator is similar to Observable or Stream. Like an {@link Iterator} it + * also as a `next()` method, however instead of an IteratorResult, + * calling this method returns a {@link Promise} for a IteratorResult. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterator + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface|Async Iteration Proposal} + */ + +// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator + +/** + * A property name to be used as the name of an AsyncIterable's method + * responsible for producing an Iterator, referred to as `@@asyncIterator`. + * Typically represents the value `Symbol.asyncIterator` but falls back to the + * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + * + * Use `$$asyncIterator` for defining new AsyncIterables instead of + * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables, + * instead use {@link getAsyncIterator} or {@link isAsyncIterable}. + * + * @example + * + * var $$asyncIterator = require('iterall').$$asyncIterator + * + * function Chirper (to) { + * this.to = to + * } + * + * Chirper.prototype[$$asyncIterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * return new Promise(resolve => { + * if (this.num >= this.to) { + * resolve({ value: undefined, done: true }) + * } else { + * setTimeout(() => { + * resolve({ value: this.num++, done: false }) + * }, 1000) + * } + * }) + * } + * } + * } + * + * var chirper = new Chirper(3) + * for await (var number of chirper) { + * console.log(number) // 0 ...wait... 1 ...wait... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$asyncIterator: '@@asyncIterator'; */ +export var $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator' + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + * + * @example + * + * var isAsyncIterable = require('iterall').isAsyncIterable + * isAsyncIterable(myStream) // true + * isAsyncIterable('ABC') // false + * + * @param obj + * A value which might implement the AsyncIterable protocol. + * @return {boolean} true if AsyncIterable. + */ +/*:: declare export function isAsyncIterable(obj: any): boolean; */ +export function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj) +} + +/** + * If the provided object implements the AsyncIterator protocol, its + * AsyncIterator object is returned. Otherwise returns undefined. + * + * @example + * + * var getAsyncIterator = require('iterall').getAsyncIterator + * var asyncIterator = getAsyncIterator(myStream) + * asyncIterator.next().then(console.log) // { value: 1, done: false } + * asyncIterator.next().then(console.log) // { value: 2, done: false } + * asyncIterator.next().then(console.log) // { value: 3, done: false } + * asyncIterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which is the source of an AsyncIterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var getAsyncIterator: + & (<+TValue>(asyncIterable: AsyncIterable) => AsyncIterator) + & ((asyncIterable: mixed) => (void | AsyncIterator)); */ +export function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable) + if (method) { + return method.call(asyncIterable) + } +} + +/** + * If the provided object implements the AsyncIterator protocol, the method + * responsible for producing its AsyncIterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod + * var method = getAsyncIteratorMethod(myStream) + * if (method) { + * var asyncIterator = method.call(myStream) + * } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which defines an `@@asyncIterator` method. + * @return {function(): AsyncIterator} `@@asyncIterator` method. + */ +/*:: declare export var getAsyncIteratorMethod: + & (<+TValue>(asyncIterable: AsyncIterable) => (() => AsyncIterator)) + & ((asyncIterable: mixed) => (void | (() => AsyncIterator))); */ +export function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = + (SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) || + asyncIterable['@@asyncIterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getAsyncIterator}, this method returns a new AsyncIterator + * given an AsyncIterable. However it will also create an AsyncIterator for a + * non-async Iterable as well as non-Iterable Array-like collection, such as + * Array in a pre-ES2015 environment. + * + * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a + * buffering "pull"-based iteration as opposed to `forAwaitEach`'s + * "push"-based iteration. + * + * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as + * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + * + * > Note: Creating `AsyncIterator`s requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var createAsyncIterator = require('iterall').createAsyncIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createAsyncIterator(myArraylike) + * iterator.next().then(console.log) // { value: 'Alpha', done: false } + * iterator.next().then(console.log) // { value: 'Bravo', done: false } + * iterator.next().then(console.log) // { value: 'Charlie', done: false } + * iterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable|{ length: number }} source + * An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var createAsyncIterator: + & (<+TValue>( + collection: Iterable | TValue> | AsyncIterable + ) => AsyncIterator) + & ((collection: {length: number}) => AsyncIterator) + & ((collection: mixed) => (void | AsyncIterator)); */ +export function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source) + if (asyncIterator) { + return asyncIterator + } + var iterator = createIterator(source) + if (iterator) { + return new AsyncFromSyncIterator(iterator) + } + } +} + +// When the object provided to `createAsyncIterator` is not AsyncIterable but is +// sync Iterable, this simple wrapper is created. +function AsyncFromSyncIterator(iterator) { + this._i = iterator +} + +// Note: all AsyncIterators are themselves AsyncIterable. +AsyncFromSyncIterator.prototype[$$asyncIterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +AsyncFromSyncIterator.prototype.next = function() { + var step = this._i.next() + return Promise.resolve(step.value).then(function(value) { + return { value: value, done: step.done } + }) +} + +/** + * Given an object which either implements the AsyncIterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * > Note: Using `forAwaitEach` requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var forAwaitEach = require('iterall').forAwaitEach + * + * forAwaitEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES2017: + * for await (let value of myAsyncIterable) { + * console.log(await doSomethingAsync(value)) + * } + * console.log('done') + * + * // Any JavaScript environment: + * forAwaitEach(myAsyncIterable, function (value) { + * return doSomethingAsync(value).then(console.log) + * }).then(function () { + * console.log('done') + * }) + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable | T>|{ length: number }} source + * The AsyncIterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forAwaitEach: + & (<+TValue, TCollection: Iterable | TValue> | AsyncIterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise); */ +export function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source) + if (asyncIterator) { + var i = 0 + return new Promise(function(resolve, reject) { + function next() { + asyncIterator + .next() + .then(function(step) { + if (!step.done) { + Promise.resolve(callback.call(thisArg, step.value, i++, source)) + .then(next) + .catch(reject) + } else { + resolve() + } + // Explicitly return null, silencing bluebird-style warnings. + return null + }) + .catch(reject) + // Explicitly return null, silencing bluebird-style warnings. + return null + } + next() + }) + } +} diff --git a/node_modules/iterall/index.mjs b/node_modules/iterall/index.mjs new file mode 100644 index 00000000..fa3002a9 --- /dev/null +++ b/node_modules/iterall/index.mjs @@ -0,0 +1,702 @@ +/** + * Copyright (c) 2016, Lee Byron + * All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow + * @ignore + */ + +/** + * [Iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator) + * is a *protocol* which describes a standard way to produce a sequence of + * values, typically the values of the Iterable represented by this Iterator. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterator-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterator + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator|MDN Iteration protocols} + */ + +/** + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable) + * is a *protocol* which when implemented allows a JavaScript object to define + * their iteration behavior, such as what values are looped over in a + * [`for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) + * loop or `iterall`'s `forEach` function. Many [built-in types](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#Builtin_iterables) + * implement the Iterable protocol, including `Array` and `Map`. + * + * While described by the [ES2015 version of JavaScript](http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface) + * it can be utilized by any version of JavaScript. + * + * @external Iterable + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|MDN Iteration protocols} + */ + +// In ES2015 environments, Symbol exists +var SYMBOL /*: any */ = typeof Symbol === 'function' ? Symbol : void 0 + +// In ES2015 (or a polyfilled) environment, this will be Symbol.iterator +var SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator + +/** + * A property name to be used as the name of an Iterable's method responsible + * for producing an Iterator, referred to as `@@iterator`. Typically represents + * the value `Symbol.iterator` but falls back to the string `"@@iterator"` when + * `Symbol.iterator` is not defined. + * + * Use `$$iterator` for defining new Iterables instead of `Symbol.iterator`, + * but do not use it for accessing existing Iterables, instead use + * {@link getIterator} or {@link isIterable}. + * + * @example + * + * var $$iterator = require('iterall').$$iterator + * + * function Counter (to) { + * this.to = to + * } + * + * Counter.prototype[$$iterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * if (this.num >= this.to) { + * return { value: undefined, done: true } + * } + * return { value: this.num++, done: false } + * } + * } + * } + * + * var counter = new Counter(3) + * for (var number of counter) { + * console.log(number) // 0 ... 1 ... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$iterator: '@@iterator'; */ +export var $$iterator = SYMBOL_ITERATOR || '@@iterator' + +/** + * Returns true if the provided object implements the Iterator protocol via + * either implementing a `Symbol.iterator` or `"@@iterator"` method. + * + * @example + * + * var isIterable = require('iterall').isIterable + * isIterable([ 1, 2, 3 ]) // true + * isIterable('ABC') // true + * isIterable({ length: 1, 0: 'Alpha' }) // false + * isIterable({ key: 'value' }) // false + * isIterable(new Map()) // true + * + * @param obj + * A value which might implement the Iterable protocol. + * @return {boolean} true if Iterable. + */ +/*:: declare export function isIterable(obj: any): boolean; */ +export function isIterable(obj) { + return !!getIteratorMethod(obj) +} + +/** + * Returns true if the provided object implements the Array-like protocol via + * defining a positive-integer `length` property. + * + * @example + * + * var isArrayLike = require('iterall').isArrayLike + * isArrayLike([ 1, 2, 3 ]) // true + * isArrayLike('ABC') // true + * isArrayLike({ length: 1, 0: 'Alpha' }) // true + * isArrayLike({ key: 'value' }) // false + * isArrayLike(new Map()) // false + * + * @param obj + * A value which might implement the Array-like protocol. + * @return {boolean} true if Array-like. + */ +/*:: declare export function isArrayLike(obj: any): boolean; */ +export function isArrayLike(obj) { + var length = obj != null && obj.length + return typeof length === 'number' && length >= 0 && length % 1 === 0 +} + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and is either Iterable or Array-like. + * + * This may be used in place of [Array.isArray()][isArray] to determine if an + * object should be iterated-over. It always excludes string literals and + * includes Arrays (regardless of if it is Iterable). It also includes other + * Array-like objects such as NodeList, TypedArray, and Buffer. + * + * @example + * + * var isCollection = require('iterall').isCollection + * isCollection([ 1, 2, 3 ]) // true + * isCollection('ABC') // false + * isCollection({ length: 1, 0: 'Alpha' }) // true + * isCollection({ key: 'value' }) // false + * isCollection(new Map()) // true + * + * @example + * + * var forEach = require('iterall').forEach + * if (isCollection(obj)) { + * forEach(obj, function (value) { + * console.log(value) + * }) + * } + * + * @param obj + * An Object value which might implement the Iterable or Array-like protocols. + * @return {boolean} true if Iterable or Array-like Object. + */ +/*:: declare export function isCollection(obj: any): boolean; */ +export function isCollection(obj) { + return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj)) +} + +/** + * If the provided object implements the Iterator protocol, its Iterator object + * is returned. Otherwise returns undefined. + * + * @example + * + * var getIterator = require('iterall').getIterator + * var iterator = getIterator([ 1, 2, 3 ]) + * iterator.next() // { value: 1, done: false } + * iterator.next() // { value: 2, done: false } + * iterator.next() // { value: 3, done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which is the source of an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var getIterator: + & (<+TValue>(iterable: Iterable) => Iterator) + & ((iterable: mixed) => void | Iterator); */ +export function getIterator(iterable) { + var method = getIteratorMethod(iterable) + if (method) { + return method.call(iterable) + } +} + +/** + * If the provided object implements the Iterator protocol, the method + * responsible for producing its Iterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getIteratorMethod = require('iterall').getIteratorMethod + * var myArray = [ 1, 2, 3 ] + * var method = getIteratorMethod(myArray) + * if (method) { + * var iterator = method.call(myArray) + * } + * + * @template T the type of each iterated value + * @param {Iterable} iterable + * An Iterable object which defines an `@@iterator` method. + * @return {function(): Iterator} `@@iterator` method. + */ +/*:: declare export var getIteratorMethod: + & (<+TValue>(iterable: Iterable) => (() => Iterator)) + & ((iterable: mixed) => (void | (() => Iterator))); */ +export function getIteratorMethod(iterable) { + if (iterable != null) { + var method = + (SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getIterator}, this method returns a new Iterator given an + * Iterable. However it will also create an Iterator for a non-Iterable + * Array-like collection, such as Array in a non-ES2015 environment. + * + * `createIterator` is complimentary to `forEach`, but allows a "pull"-based + * iteration as opposed to `forEach`'s "push"-based iteration. + * + * `createIterator` produces an Iterator for Array-likes with the same behavior + * as ArrayIteratorPrototype described in the ECMAScript specification, and + * does *not* skip over "holes". + * + * @example + * + * var createIterator = require('iterall').createIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createIterator(myArraylike) + * iterator.next() // { value: 'Alpha', done: false } + * iterator.next() // { value: 'Bravo', done: false } + * iterator.next() // { value: 'Charlie', done: false } + * iterator.next() // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * An Iterable or Array-like object to produce an Iterator. + * @return {Iterator} new Iterator instance. + */ +/*:: declare export var createIterator: + & (<+TValue>(collection: Iterable) => Iterator) + & ((collection: {length: number}) => Iterator) + & ((collection: mixed) => (void | Iterator)); */ +export function createIterator(collection) { + if (collection != null) { + var iterator = getIterator(collection) + if (iterator) { + return iterator + } + if (isArrayLike(collection)) { + return new ArrayLikeIterator(collection) + } + } +} + +// When the object provided to `createIterator` is not Iterable but is +// Array-like, this simple Iterator is created. +function ArrayLikeIterator(obj) { + this._o = obj + this._i = 0 +} + +// Note: all Iterators are themselves Iterable. +ArrayLikeIterator.prototype[$$iterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +ArrayLikeIterator.prototype.next = function() { + if (this._o === void 0 || this._i >= this._o.length) { + this._o = void 0 + return { value: void 0, done: true } + } + return { value: this._o[this._i++], done: false } +} + +/** + * Given an object which either implements the Iterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forEach` where you would expect to use a `for ... of` loop in ES6. + * However `forEach` adheres to the behavior of [Array#forEach][] described in + * the ECMAScript specification, skipping over "holes" in Array-likes. It will + * also delegate to a `forEach` method on `collection` if one is defined, + * ensuring native performance for `Arrays`. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * Note: providing an infinite Iterator to forEach will produce an error. + * + * [Array#forEach]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach + * + * @example + * + * var forEach = require('iterall').forEach + * + * forEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES6: + * for (let value of myIterable) { + * console.log(value) + * } + * + * // Any JavaScript environment: + * forEach(myIterable, function (value) { + * console.log(value) + * }) + * + * @template T the type of each iterated value + * @param {Iterable|{ length: number }} collection + * The Iterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forEach: + & (<+TValue, TCollection: Iterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => void) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => void); */ +export function forEach(collection, callback, thisArg) { + if (collection != null) { + if (typeof collection.forEach === 'function') { + return collection.forEach(callback, thisArg) + } + var i = 0 + var iterator = getIterator(collection) + if (iterator) { + var step + while (!(step = iterator.next()).done) { + callback.call(thisArg, step.value, i++, collection) + // Infinite Iterators could cause forEach to run forever. + // After a very large number of iterations, produce an error. + /* istanbul ignore if */ + if (i > 9999999) { + throw new TypeError('Near-infinite iteration.') + } + } + } else if (isArrayLike(collection)) { + for (; i < collection.length; i++) { + if (collection.hasOwnProperty(i)) { + callback.call(thisArg, collection[i], i, collection) + } + } + } + } +} + +///////////////////////////////////////////////////// +// // +// ASYNC ITERATORS // +// // +///////////////////////////////////////////////////// + +/** + * [AsyncIterable](https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface) + * is a *protocol* which when implemented allows a JavaScript object to define + * an asynchronous iteration behavior, such as what values are looped over in + * a [`for-await-of`](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) + * loop or `iterall`'s {@link forAwaitEach} function. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterable + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterable-interface|Async Iteration Proposal} + * @template T The type of each iterated value + * @property {function (): AsyncIterator} Symbol.asyncIterator + * A method which produces an AsyncIterator for this AsyncIterable. + */ + +/** + * [AsyncIterator](https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface) + * is a *protocol* which describes a standard way to produce and consume an + * asynchronous sequence of values, typically the values of the + * {@link AsyncIterable} represented by this {@link AsyncIterator}. + * + * AsyncIterator is similar to Observable or Stream. Like an {@link Iterator} it + * also as a `next()` method, however instead of an IteratorResult, + * calling this method returns a {@link Promise} for a IteratorResult. + * + * While described as a proposed addition to the [ES2017 version of JavaScript](https://tc39.github.io/proposal-async-iteration/) + * it can be utilized by any version of JavaScript. + * + * @external AsyncIterator + * @see {@link https://tc39.github.io/proposal-async-iteration/#sec-asynciterator-interface|Async Iteration Proposal} + */ + +// In ES2017 (or a polyfilled) environment, this will be Symbol.asyncIterator +var SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator + +/** + * A property name to be used as the name of an AsyncIterable's method + * responsible for producing an Iterator, referred to as `@@asyncIterator`. + * Typically represents the value `Symbol.asyncIterator` but falls back to the + * string `"@@asyncIterator"` when `Symbol.asyncIterator` is not defined. + * + * Use `$$asyncIterator` for defining new AsyncIterables instead of + * `Symbol.asyncIterator`, but do not use it for accessing existing Iterables, + * instead use {@link getAsyncIterator} or {@link isAsyncIterable}. + * + * @example + * + * var $$asyncIterator = require('iterall').$$asyncIterator + * + * function Chirper (to) { + * this.to = to + * } + * + * Chirper.prototype[$$asyncIterator] = function () { + * return { + * to: this.to, + * num: 0, + * next () { + * return new Promise(resolve => { + * if (this.num >= this.to) { + * resolve({ value: undefined, done: true }) + * } else { + * setTimeout(() => { + * resolve({ value: this.num++, done: false }) + * }, 1000) + * } + * }) + * } + * } + * } + * + * var chirper = new Chirper(3) + * for await (var number of chirper) { + * console.log(number) // 0 ...wait... 1 ...wait... 2 + * } + * + * @type {Symbol|string} + */ +/*:: declare export var $$asyncIterator: '@@asyncIterator'; */ +export var $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator' + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * either implementing a `Symbol.asyncIterator` or `"@@asyncIterator"` method. + * + * @example + * + * var isAsyncIterable = require('iterall').isAsyncIterable + * isAsyncIterable(myStream) // true + * isAsyncIterable('ABC') // false + * + * @param obj + * A value which might implement the AsyncIterable protocol. + * @return {boolean} true if AsyncIterable. + */ +/*:: declare export function isAsyncIterable(obj: any): boolean; */ +export function isAsyncIterable(obj) { + return !!getAsyncIteratorMethod(obj) +} + +/** + * If the provided object implements the AsyncIterator protocol, its + * AsyncIterator object is returned. Otherwise returns undefined. + * + * @example + * + * var getAsyncIterator = require('iterall').getAsyncIterator + * var asyncIterator = getAsyncIterator(myStream) + * asyncIterator.next().then(console.log) // { value: 1, done: false } + * asyncIterator.next().then(console.log) // { value: 2, done: false } + * asyncIterator.next().then(console.log) // { value: 3, done: false } + * asyncIterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which is the source of an AsyncIterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var getAsyncIterator: + & (<+TValue>(asyncIterable: AsyncIterable) => AsyncIterator) + & ((asyncIterable: mixed) => (void | AsyncIterator)); */ +export function getAsyncIterator(asyncIterable) { + var method = getAsyncIteratorMethod(asyncIterable) + if (method) { + return method.call(asyncIterable) + } +} + +/** + * If the provided object implements the AsyncIterator protocol, the method + * responsible for producing its AsyncIterator object is returned. + * + * This is used in rare cases for performance tuning. This method must be called + * with obj as the contextual this-argument. + * + * @example + * + * var getAsyncIteratorMethod = require('iterall').getAsyncIteratorMethod + * var method = getAsyncIteratorMethod(myStream) + * if (method) { + * var asyncIterator = method.call(myStream) + * } + * + * @template T the type of each iterated value + * @param {AsyncIterable} asyncIterable + * An AsyncIterable object which defines an `@@asyncIterator` method. + * @return {function(): AsyncIterator} `@@asyncIterator` method. + */ +/*:: declare export var getAsyncIteratorMethod: + & (<+TValue>(asyncIterable: AsyncIterable) => (() => AsyncIterator)) + & ((asyncIterable: mixed) => (void | (() => AsyncIterator))); */ +export function getAsyncIteratorMethod(asyncIterable) { + if (asyncIterable != null) { + var method = + (SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) || + asyncIterable['@@asyncIterator'] + if (typeof method === 'function') { + return method + } + } +} + +/** + * Similar to {@link getAsyncIterator}, this method returns a new AsyncIterator + * given an AsyncIterable. However it will also create an AsyncIterator for a + * non-async Iterable as well as non-Iterable Array-like collection, such as + * Array in a pre-ES2015 environment. + * + * `createAsyncIterator` is complimentary to `forAwaitEach`, but allows a + * buffering "pull"-based iteration as opposed to `forAwaitEach`'s + * "push"-based iteration. + * + * `createAsyncIterator` produces an AsyncIterator for non-async Iterables as + * described in the ECMAScript proposal [Async-from-Sync Iterator Objects](https://tc39.github.io/proposal-async-iteration/#sec-async-from-sync-iterator-objects). + * + * > Note: Creating `AsyncIterator`s requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var createAsyncIterator = require('iterall').createAsyncIterator + * + * var myArraylike = { length: 3, 0: 'Alpha', 1: 'Bravo', 2: 'Charlie' } + * var iterator = createAsyncIterator(myArraylike) + * iterator.next().then(console.log) // { value: 'Alpha', done: false } + * iterator.next().then(console.log) // { value: 'Bravo', done: false } + * iterator.next().then(console.log) // { value: 'Charlie', done: false } + * iterator.next().then(console.log) // { value: undefined, done: true } + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable|{ length: number }} source + * An AsyncIterable, Iterable, or Array-like object to produce an Iterator. + * @return {AsyncIterator} new AsyncIterator instance. + */ +/*:: declare export var createAsyncIterator: + & (<+TValue>( + collection: Iterable | TValue> | AsyncIterable + ) => AsyncIterator) + & ((collection: {length: number}) => AsyncIterator) + & ((collection: mixed) => (void | AsyncIterator)); */ +export function createAsyncIterator(source) { + if (source != null) { + var asyncIterator = getAsyncIterator(source) + if (asyncIterator) { + return asyncIterator + } + var iterator = createIterator(source) + if (iterator) { + return new AsyncFromSyncIterator(iterator) + } + } +} + +// When the object provided to `createAsyncIterator` is not AsyncIterable but is +// sync Iterable, this simple wrapper is created. +function AsyncFromSyncIterator(iterator) { + this._i = iterator +} + +// Note: all AsyncIterators are themselves AsyncIterable. +AsyncFromSyncIterator.prototype[$$asyncIterator] = function() { + return this +} + +// A simple state-machine determines the IteratorResult returned, yielding +// each value in the Array-like object in order of their indicies. +AsyncFromSyncIterator.prototype.next = function() { + var step = this._i.next() + return Promise.resolve(step.value).then(function(value) { + return { value: value, done: step.done } + }) +} + +/** + * Given an object which either implements the AsyncIterable protocol or is + * Array-like, iterate over it, calling the `callback` at each iteration. + * + * Use `forAwaitEach` where you would expect to use a [for-await-of](https://tc39.github.io/proposal-async-iteration/#sec-for-in-and-for-of-statements) loop. + * + * Similar to [Array#forEach][], the `callback` function accepts three + * arguments, and is provided with `thisArg` as the calling context. + * + * > Note: Using `forAwaitEach` requires the existence of `Promise`. + * > While `Promise` has been available in modern browsers for a number of + * > years, legacy browsers (like IE 11) may require a polyfill. + * + * @example + * + * var forAwaitEach = require('iterall').forAwaitEach + * + * forAwaitEach(myIterable, function (value, index, iterable) { + * console.log(value, index, iterable === myIterable) + * }) + * + * @example + * + * // ES2017: + * for await (let value of myAsyncIterable) { + * console.log(await doSomethingAsync(value)) + * } + * console.log('done') + * + * // Any JavaScript environment: + * forAwaitEach(myAsyncIterable, function (value) { + * return doSomethingAsync(value).then(console.log) + * }).then(function () { + * console.log('done') + * }) + * + * @template T the type of each iterated value + * @param {AsyncIterable|Iterable | T>|{ length: number }} source + * The AsyncIterable or array to iterate over. + * @param {function(T, number, object)} callback + * Function to execute for each iteration, taking up to three arguments + * @param [thisArg] + * Optional. Value to use as `this` when executing `callback`. + */ +/*:: declare export var forAwaitEach: + & (<+TValue, TCollection: Iterable | TValue> | AsyncIterable>( + collection: TCollection, + callbackFn: (value: TValue, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise) + & (( + collection: TCollection, + callbackFn: (value: mixed, index: number, collection: TCollection) => any, + thisArg?: any + ) => Promise); */ +export function forAwaitEach(source, callback, thisArg) { + var asyncIterator = createAsyncIterator(source) + if (asyncIterator) { + var i = 0 + return new Promise(function(resolve, reject) { + function next() { + asyncIterator + .next() + .then(function(step) { + if (!step.done) { + Promise.resolve(callback.call(thisArg, step.value, i++, source)) + .then(next) + .catch(reject) + } else { + resolve() + } + // Explicitly return null, silencing bluebird-style warnings. + return null + }) + .catch(reject) + // Explicitly return null, silencing bluebird-style warnings. + return null + } + next() + }) + } +} diff --git a/node_modules/iterall/package.json b/node_modules/iterall/package.json new file mode 100644 index 00000000..2793bd01 --- /dev/null +++ b/node_modules/iterall/package.json @@ -0,0 +1,57 @@ +{ + "_args": [ + [ + "iterall@1.2.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "iterall@1.2.2", + "_id": "iterall@1.2.2", + "_inBundle": false, + "_integrity": "sha512-yynBb1g+RFUPY64fTrFv7nsjRrENBQJaX2UL+2Szc9REFrSNm1rpSXHGzhmAy7a9uv3vlvgBlXnf9RqmPH1/DA==", + "_location": "/iterall", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "iterall@1.2.2", + "name": "iterall", + "escapedName": "iterall", + "rawSpec": "1.2.2", + "saveSpec": null, + "fetchSpec": "1.2.2" + }, + "_requiredBy": [ + "/graphql" + ], + "_resolved": "https://registry.npmjs.org/iterall/-/iterall-1.2.2.tgz", + "_spec": "1.2.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Lee Byron", + "email": "lee@leebyron.com", + "url": "http://leebyron.com/" + }, + "bugs": { + "url": "https://github.com/leebyron/iterall/issues" + }, + "description": "Minimal zero-dependency utilities for using JavaScript Iterables in all environments.", + "homepage": "https://github.com/leebyron/iterall", + "keywords": [ + "es6", + "iterator", + "iterable", + "polyfill", + "for-of" + ], + "license": "MIT", + "main": "index", + "module": "index.mjs", + "name": "iterall", + "repository": { + "type": "git", + "url": "git+https://github.com/leebyron/iterall.git" + }, + "typings": "index.d.ts", + "version": "1.2.2" +} diff --git a/node_modules/lokijs/.editorconfig b/node_modules/lokijs/.editorconfig new file mode 100644 index 00000000..4960585e --- /dev/null +++ b/node_modules/lokijs/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 +indent_style = space +indent_size = 2 diff --git a/node_modules/lokijs/.gitattributes b/node_modules/lokijs/.gitattributes new file mode 100644 index 00000000..6325a07a --- /dev/null +++ b/node_modules/lokijs/.gitattributes @@ -0,0 +1,2 @@ +docs/* linguist-documentation +jsdoc/* linguist-documentation diff --git a/node_modules/lokijs/.jshintrc b/node_modules/lokijs/.jshintrc new file mode 100644 index 00000000..a5aaaedb --- /dev/null +++ b/node_modules/lokijs/.jshintrc @@ -0,0 +1,3 @@ +{ + "esnext": true +} diff --git a/node_modules/lokijs/.npmignore b/node_modules/lokijs/.npmignore new file mode 100644 index 00000000..8849bcf8 --- /dev/null +++ b/node_modules/lokijs/.npmignore @@ -0,0 +1,8 @@ +docs/ +benchmark/ +demos/ +examples/ +jsdoc/ +tutorials/ +spec/ +coverage/ diff --git a/node_modules/lokijs/.travis.yml b/node_modules/lokijs/.travis.yml new file mode 100644 index 00000000..ff2e32f8 --- /dev/null +++ b/node_modules/lokijs/.travis.yml @@ -0,0 +1,5 @@ + language: node_js + node_js: + - "4.0" + - "6" + - "8" diff --git a/node_modules/lokijs/CHANGELOG.md b/node_modules/lokijs/CHANGELOG.md new file mode 100644 index 00000000..6f88ce33 --- /dev/null +++ b/node_modules/lokijs/CHANGELOG.md @@ -0,0 +1,93 @@ +# Changelog + +## 1.5.5 +* fixed issue where batch removes did not update unique index (#677) + +## 1.5.4 +* fixes to checkIndex maintenance fn (#654, #661) +* bulk remove optimizations (#663) +* fix to meta when cloning (#666) +* AWS S3 sync adapter added (#670) +* fix for browser project: fs not found (#674) +* added comparators to default export (#672) + +## 1.5.3 +* simplesort can leverage binary index (via index intersect) when weakly filtered (#645) +* the simplesort 'descending' param is now multipurposed (with bw-compat) see jsdocs +* added new simplified js comparison ops for unindexed optimizations (commit bb011d) +* added collection.checkIndex() and collection.checkIndexes() for diagnostics (#654,#47) + +## 1.5.2 +* fixed error when transform steps have non-serializable parameters (#624) +* addCollection will return existing collection when collection named already exists (#635) +* batch updates when not cloning no longer risk invalidating adaptive binary indices (#639) +* fixed autosave race condition when using async adapter (#643) +* collection option added to disableMeta if not using changes api or ttl (#644) + +## 1.5.1 +* added disableDeltaChangesApi (default:true) collection option to store only differences. (#582) +* loki indexed adapter deleteDatabase method will now wait until complete before callback (#584) +* fixed clone methods correctly assigning object prototypes (#586) +* partitioning adapter and memory adapter no longer throw error when database doesn't exist (yet) +* simplesort and compoundsort now support sorting on nested properties via dot-notation (#574) +* added support for binary indices on nested properties (#574) +* fixed jsdoc syntax error causing vscode to crash (#614) +* fixed error when using partitioning adapter with nativescript adapter (#615) +* added optional 'dataOptions' to eqJoin and map (chain/transform) (see #618) + +## 1.5.0 +* refactored binary indices sorting order +* date values in properties with binary index will be converted to epoch time +* fix to LokiFsStructuredAdapter first time autoload error where file doesn't exist yet +* fixed simplesort descending with binary indices and no filters +* with 'clone' option collection 'insert' events no longer emit internal obj reference +* fix to clone method 'shallow' +* added 'removeMeta' option to chained data calls to shallow clone and remove $loki and meta +* added quickstart examples for node and updated loki sandbox with online web quickstarts +* fixes to async unit tests +* npm release trimmed from 5 megs to 500k (no examples, jsdocs, tests) + +## 1.4.3 +* added throttled saves and loads (enabled by default) to ensure no overlapping calls +* unfiltered simplesorts can leverage binary index +* collection.clear now clears indices correctly +* fix to LokiPartitioning adapter resetting maxId across saves +* meta set correctly on batch inserts +* LokiMemoryAdapter now configurable to simulate async +* fix changesApi not enabled after loading database + +## 1.4.2 +* added 'adaptiveBinaryIndices' option to collections (default true) to avoid rebuilds on inserts/updates/removes +* added higher performance LokiFsStructuredAdapter for node +* added destructured serialization methods for partitioning and exporting +* added 'addListener' method alias of 'on' method +* LokiFsAdapter doesn't throw exception when file doesn't exist (yet) +* fix for circular structure error when setting ttl +* fix unit testing on windows +* experimental implementation of an incremental adapter + +## 1.4.1 +* minor fixes +* updated jsdoc coverage + +## 1.4.0 +* fixes to loki indexed adapter +* added nativescript adapter +* added $aeq, $contains, $containsAny, $ne +* fix unique index update with new object +* expose persistence adapters to module export +* fix to loki-crypted-file-adapter + +## 1.3.0 + +* UniqueIndex and `by()` method +* staging API +* count() utility method +* RethinkDB-style joins (eqJoin) +* moved testing to Karma +* moved builds and run to npm instead of gulp +* added $containsAny operator +* statistical functions: average, max, maxRecord, min, minRecord, median, mode +* extract() to extract a flat array of values for one field in each record +* extractNumerical() - same as extract() for numerical values +* pre-insert and pre-update events diff --git a/node_modules/lokijs/CONTRIBUTING.md b/node_modules/lokijs/CONTRIBUTING.md new file mode 100644 index 00000000..29ca84b8 --- /dev/null +++ b/node_modules/lokijs/CONTRIBUTING.md @@ -0,0 +1,39 @@ +First of all thank you for contributing. + +## Overview +We try our best to adhere to the [airbnb](https://github.com/airbnb/javascript/blob/master/README.md) javascript style guidelines. + +If you spot non compliant code in our codebase do not hesitate to flag it or even submit a pull request. +Running `npm run lint` can help. + +We do not ask that you agree with our guidelines but if you want to contribute you will have to respect them. + +## Pull-requests + +LokiJS puts a strong emphasis on performance. Make sure to benchmark performance on your machine before and after you apply a change and ensure performance is unchanged (or unnoticeable), even better if it is improved. +Verify your changes are non-breaking by running `npm test`, and if you're adding a feature make sure to add a test somewhere in the relevant file in `spec/` (or a brand new file if the test cannot be included in existing files). + +## A few things we recommend + +Most of these are included in the airbnb style guide but we feel like highlighting them: + +* use shortcuts in if conditions, and always follow with a statements in curly brackets. Do not do: +`if (something) return;` instead do `if (something) { return; }` +* Name callbacks, when possible try to declare them as functions that can be cached to save memory as well making your code more readable. i.e. instead of +```javascript +result.filter(function () { /* ... */ }); +``` +try to do: +```javascript +function doFilter(obj) { + // ... +} +result.filter(doFilter); +``` + +## A few things we will not accept + +* comma first +* avoid-semicolon-at-all-cost stupidity +* general hipster code +* coffeescript/TypeScript diff --git a/node_modules/lokijs/LICENSE.txt b/node_modules/lokijs/LICENSE.txt new file mode 100644 index 00000000..0ec11abc --- /dev/null +++ b/node_modules/lokijs/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright (c) 2015 TechFort + +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/lokijs/OVERVIEW.md b/node_modules/lokijs/OVERVIEW.md new file mode 100644 index 00000000..e37076f2 --- /dev/null +++ b/node_modules/lokijs/OVERVIEW.md @@ -0,0 +1,88 @@ +# LokiJS + +[LokiJS.org web site](http://lokijs.org) | +[LokiJS GitHub page](https://github.com/techfort/LokiJS) | +[Sandbox / Playground](https://rawgit.com/techfort/LokiJS/master/examples/sandbox/LokiSandbox.htm) + +## Documentation Overview + +This is an early effort to provide a more accurate and up-to-date version of LokiJS documentation by using jsdoc. Since modifications arise from various contributors, this should allow distributed effort toward +maintaining this documentation. + +## Getting Started + +Creating a database : + +```javascript +var db = new loki('example.db'); +``` + +Add a collection : + +```javascript +var users = db.addCollection('users'); +``` + +Insert documents : + +```javascript +users.insert({ + name: 'Odin', + age: 50, + address: 'Asgard' +}); + +// alternatively, insert array of documents +users.insert([{ name: 'Thor', age: 35}, { name: 'Loki', age: 30}]); +``` + +Simple find query : + +```javascript +var results = users.find({ age: {'$gte': 35} }); + +var odin = users.findOne({ name:'Odin' }); +``` + +Simple where query : + +```javascript +var results = users.where(function(obj) { + return (obj.age >= 35); +}); +``` + +Simple Chaining : + +```javascript +var results = users.chain().find({ age: {'$gte': 35} }).simplesort('name').data(); +``` + +Simple named transform : + +```javascript +users.addTransform('progeny', [ + { + type: 'find', + value: { + 'age': {'$lte': 40} + } + } +]); + +var results = users.chain('progeny').data(); +``` + +Simple Dynamic View : + +```javascript +var pview = users.addDynamicView('progeny'); + +pview.applyFind({ + 'age': {'$lte': 40} +}); + +pview.applySimpleSort('name'); + +var results = pview.data(); +``` \ No newline at end of file diff --git a/node_modules/lokijs/README.md b/node_modules/lokijs/README.md new file mode 100644 index 00000000..d6c75704 --- /dev/null +++ b/node_modules/lokijs/README.md @@ -0,0 +1,87 @@ +# LokiJS + +[![Join the chat at https://gitter.im/techfort/LokiJS](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/techfort/LokiJS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +![alt CI-badge](https://travis-ci.org/techfort/LokiJS.svg?branch=master) +[![npm version](https://badge.fury.io/js/lokijs.svg)](http://badge.fury.io/js/lokijs) +[![alt packagequality](http://npm.packagequality.com/shield/lokijs.svg)](http://packagequality.com/#?package=lokijs) + +## Overview + +LokiJS is a document oriented database written in javascript, published under MIT License. +Its purpose is to store javascript objects as documents in a nosql fashion and retrieve them with a similar mechanism. +Runs in node (including cordova/phonegap and node-webkit), [nativescript](http://www.nativescript.org) and the browser. +LokiJS is ideal for the following scenarios: + +1. client-side in-memory db is ideal (e.g., a session store) +2. performance critical applications +3. cordova/phonegap mobile apps where you can leverage the power of javascript and avoid interacting with native databases +4. data sets loaded into a browser page and synchronised at the end of the work session +5. node-webkit desktop apps +6. nativescript mobile apps that mix the power and ubiquity of javascript with native performance and ui + +LokiJS supports indexing and views and achieves high-performance through maintaining unique and binary indexes (indices) for data. + +## Demo + +The following demos are available: +- [Sandbox / Playground](https://rawgit.com/techfort/LokiJS/master/examples/sandbox/LokiSandbox.htm) +- a node-webkit small demo in the folder demos/desktop_app. You can launch it by running `/path/to/nw demos/desktop_app/` + +## Wiki + +Example usage can be found on the [wiki](https://github.com/techfort/LokiJS/wiki) + +## Main Features + +1. Fast performance NoSQL in-memory database, collections with unique index (1.1M ops/s) and binary-index (500k ops/s) +2. Runs in multiple environments (browser, node, nativescript) +3. Dynamic Views for fast access of data subsets +4. Built-in persistence adapters, and the ability to support user-defined ones +5. Changes API +6. Joins + +## Current state + +LokiJS is at version 1.3 [Eostre]. + +As LokiJS is written in JavaScript it can be run on any environment supporting JavaScript such as browsers, node.js/node-webkit, nativescript mobile framework and hybrid mobile apps (such as phonegap/cordova). + +Made by [@techfort](http://twitter.com/tech_fort), with the precious help of Dave Easterday. + +_[Leave a tip](https://gratipay.com/techfort/) or give us a star if you find LokiJS useful!_ + +## Installation + +For browser environments you simply need the lokijs.js file contained in src/ + +You can use bower to install lokijs with `bower install lokijs` + +For node and nativescript environments you can install through `npm install lokijs`. + +## Roadmap + +* exactIndex +* key-value datastore +* MRU cache +* MongoDB API compatibility +* server standalone (tcp and http servers and clients) +* replication and horizontal scaling + +## Contact + +For help / enquiries contact joe.minichino@gmail.com + +## Commercial Support + +For commercial support contact info.techfort@gmail.com + +## License + +Copyright (c) 2015 TechFort + +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/lokijs/benchmark.html b/node_modules/lokijs/benchmark.html new file mode 100644 index 00000000..29e84dc9 --- /dev/null +++ b/node_modules/lokijs/benchmark.html @@ -0,0 +1,2 @@ + + diff --git a/node_modules/lokijs/bower.json b/node_modules/lokijs/bower.json new file mode 100644 index 00000000..46f1da11 --- /dev/null +++ b/node_modules/lokijs/bower.json @@ -0,0 +1,12 @@ +{ + "name": "lokijs", + "main": ["src/lokijs.js"], + "ignore": [ + "**/.*", + "node_modules", + "components", + "bower_components", + "test", + "tests" + ] +} diff --git a/node_modules/lokijs/build/loki-indexed-adapter.min.js b/node_modules/lokijs/build/loki-indexed-adapter.min.js new file mode 100644 index 00000000..eea9e62d --- /dev/null +++ b/node_modules/lokijs/build/loki-indexed-adapter.min.js @@ -0,0 +1 @@ +(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof exports==="object"){module.exports=factory()}else{root.LokiIndexedAdapter=factory()}})(this,function(){return function(){function LokiIndexedAdapter(appname){this.app="loki";if(typeof appname!=="undefined"){this.app=appname}this.catalog=null;if(!this.checkAvailability()){throw new Error("indexedDB does not seem to be supported for your environment")}}LokiIndexedAdapter.prototype.checkAvailability=function(){if(typeof indexedDB!=="undefined"&&indexedDB)return true;return false};LokiIndexedAdapter.prototype.loadDatabase=function(dbname,callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.loadDatabase(dbname,callback)});return}this.catalog.getAppKey(appName,dbname,function(result){if(typeof callback==="function"){if(result.id===0){callback(null);return}callback(result.val)}else{console.log(result.val)}})};LokiIndexedAdapter.prototype.loadKey=LokiIndexedAdapter.prototype.loadDatabase;LokiIndexedAdapter.prototype.saveDatabase=function(dbname,dbstring,callback){var appName=this.app;var adapter=this;function saveCallback(result){if(result&&result.success===true){callback(null)}else{callback(new Error("Error saving database"))}}if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;cat.setAppKey(appName,dbname,dbstring,saveCallback)});return}this.catalog.setAppKey(appName,dbname,dbstring,saveCallback)};LokiIndexedAdapter.prototype.saveKey=LokiIndexedAdapter.prototype.saveDatabase;LokiIndexedAdapter.prototype.deleteDatabase=function(dbname,callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.deleteDatabase(dbname,callback)});return}this.catalog.getAppKey(appName,dbname,function(result){var id=result.id;if(id!==0){adapter.catalog.deleteAppKey(id,callback)}else if(typeof callback==="function"){callback({success:true})}})};LokiIndexedAdapter.prototype.deleteKey=LokiIndexedAdapter.prototype.deleteDatabase;LokiIndexedAdapter.prototype.deleteDatabasePartitions=function(dbname){var self=this;this.getDatabaseList(function(result){result.forEach(function(str){if(str.startsWith(dbname)){self.deleteDatabase(str)}})})};LokiIndexedAdapter.prototype.getDatabaseList=function(callback){var appName=this.app;var adapter=this;if(this.catalog===null||this.catalog.db===null){this.catalog=new LokiCatalog(function(cat){adapter.catalog=cat;adapter.getDatabaseList(callback)});return}this.catalog.getAppKeys(appName,function(results){var names=[];for(var idx=0;idx=10)return subObj;for(prop in subObj){if(typeof subObj[prop]==="string"&&subObj[prop].indexOf("[%lktxp]")===0){pname=subObj[prop].substring(8);if(params.hasOwnProperty(pname)){subObj[prop]=params[pname]}}else if(typeof subObj[prop]==="object"){subObj[prop]=Utils.resolveTransformObject(subObj[prop],params,depth)}}return subObj},resolveTransformParams:function(transform,params){var idx,clonedStep,resolvedTransform=[];if(typeof params==="undefined")return transform;for(idx=0;idxcv2)return false;return equal}if(cv1===cv1&&cv2!==cv2){return true}if(cv2===cv2&&cv1!==cv1){return false}if(prop1prop2)return false;if(prop1==prop2)return equal;cv1=prop1.toString();cv2=prop2.toString();if(cv1t2}}cv1=Number(prop1);cv2=Number(prop2);if(cv1===cv1&&cv2===cv2){if(cv1>cv2)return true;if(cv1prop2)return true;if(prop1cv2){return true}if(cv1==cv2){return equal}return false}function sortHelper(prop1,prop2,desc){if(Comparators.aeq(prop1,prop2))return 0;if(Comparators.lt(prop1,prop2,false)){return desc?1:-1}if(Comparators.gt(prop1,prop2,false)){return desc?-1:1}return 0}function compoundeval(properties,obj1,obj2){var res=0;var prop,field,val1,val2,arr;for(var i=0,len=properties.length;i=paths.length){valueFound=fun(element,value)}else if(Array.isArray(element)){for(var index=0,len=element.length;indexb},$jgte:function(a,b){return a>=b},$jlt:function(a,b){return a=vals[0]&&a<=vals[1]},$in:function(a,b){return b.indexOf(a)!==-1},$nin:function(a,b){return b.indexOf(a)===-1},$keyin:function(a,b){return a in b},$nkeyin:function(a,b){return!(a in b)},$definedin:function(a,b){return b[a]!==undefined},$undefinedin:function(a,b){return b[a]===undefined},$regex:function(a,b){return b.test(a)},$containsString:function(a,b){return typeof a==="string"&&a.indexOf(b)!==-1},$containsNone:function(a,b){return!LokiOps.$containsAny(a,b)},$containsAny:function(a,b){var checkFn=containsCheckFn(a);if(checkFn!==null){return Array.isArray(b)?b.some(checkFn):checkFn(b)}return false},$contains:function(a,b){var checkFn=containsCheckFn(a);if(checkFn!==null){return Array.isArray(b)?b.every(checkFn):checkFn(b)}return false},$type:function(a,b){var type=typeof a;if(type==="object"){if(Array.isArray(a)){type="array"}else if(a instanceof Date){type="date"}}return typeof b!=="object"?type===b:doQueryOp(type,b)},$finite:function(a,b){return b===isFinite(a)},$size:function(a,b){if(Array.isArray(a)){return typeof b!=="object"?a.length===b:doQueryOp(a.length,b)}return false},$len:function(a,b){if(typeof a==="string"){return typeof b!=="object"?a.length===b:doQueryOp(a.length,b)}return false},$where:function(a,b){return b(a)===true},$not:function(a,b){return!doQueryOp(a,b)},$and:function(a,b){for(var idx=0,len=b.length;idx0){throw new Error("disableMeta option cannot be passed as true when ttl is enabled")}}for(i=0;i=0){return this.serializeCollection({delimited:options.delimited,delimiter:options.delimiter,collectionIndex:options.partition})}dbcopy=new Loki(this.filename);dbcopy.loadJSONObject(this);for(idx=0;idxcollCount){done=true}}else{currObject=JSON.parse(workarray[lineIndex]);cdb.collections[collIndex].data.push(currObject)}workarray[lineIndex++]=null}return cdb};Loki.prototype.deserializeCollection=function(destructuredSource,options){var workarray=[];var idx,len;options=options||{};if(!options.hasOwnProperty("partitioned")){options.partitioned=false}if(!options.hasOwnProperty("delimited")){options.delimited=true}if(!options.hasOwnProperty("delimiter")){options.delimiter=this.options.destructureDelimiter}if(options.delimited){workarray=destructuredSource.split(options.delimiter);workarray.pop()}else{workarray=destructuredSource}len=workarray.length;for(idx=0;idx=cdlen)doneWithPartition=true}if(pageLen>=this.options.pageSize)doneWithPage=true;if(!doneWithPage||doneWithPartition){pageBuilder+=this.options.delimiter;pageLen+=delimlen}if(doneWithPartition||doneWithPage){this.adapter.saveDatabase(keyname,pageBuilder,pageSaveCallback);return}}};function LokiFsAdapter(){try{this.fs=require("fs")}catch(e){this.fs=null}}LokiFsAdapter.prototype.loadDatabase=function loadDatabase(dbname,callback){var self=this;this.fs.stat(dbname,function(err,stats){if(!err&&stats.isFile()){self.fs.readFile(dbname,{encoding:"utf8"},function readFileCallback(err,data){if(err){callback(new Error(err))}else{callback(data)}})}else{callback(null)}})};LokiFsAdapter.prototype.saveDatabase=function saveDatabase(dbname,dbstring,callback){var self=this;var tmpdbname=dbname+"~";this.fs.writeFile(tmpdbname,dbstring,function writeFileCallback(err){if(err){callback(new Error(err))}else{self.fs.rename(tmpdbname,dbname,callback)}})};LokiFsAdapter.prototype.deleteDatabase=function deleteDatabase(dbname,callback){this.fs.unlink(dbname,function deleteDatabaseCallback(err){if(err){callback(new Error(err))}else{callback()}})};function LokiLocalStorageAdapter(){}LokiLocalStorageAdapter.prototype.loadDatabase=function loadDatabase(dbname,callback){if(localStorageAvailable()){callback(localStorage.getItem(dbname))}else{callback(new Error("localStorage is not available"))}};LokiLocalStorageAdapter.prototype.saveDatabase=function saveDatabase(dbname,dbstring,callback){if(localStorageAvailable()){localStorage.setItem(dbname,dbstring);callback(null)}else{callback(new Error("localStorage is not available"))}};LokiLocalStorageAdapter.prototype.deleteDatabase=function deleteDatabase(dbname,callback){if(localStorageAvailable()){ +localStorage.removeItem(dbname);callback(null)}else{callback(new Error("localStorage is not available"))}};Loki.prototype.throttledSaveDrain=function(callback,options){var self=this;var now=(new Date).getTime();if(!this.throttledSaves){callback(true)}options=options||{};if(!options.hasOwnProperty("recursiveWait")){options.recursiveWait=true}if(!options.hasOwnProperty("recursiveWaitLimit")){options.recursiveWaitLimit=false}if(!options.hasOwnProperty("recursiveWaitLimitDuration")){options.recursiveWaitLimitDuration=2e3}if(!options.hasOwnProperty("started")){options.started=(new Date).getTime()}if(this.throttledSaves&&this.throttledSavePending){if(options.recursiveWait){this.throttledCallbacks.push(function(){if(self.throttledSavePending){if(options.recursiveWaitLimit&&now-options.started>options.recursiveWaitLimitDuration){callback(false);return}self.throttledSaveDrain(callback,options);return}else{callback(true);return}})}else{this.throttledCallbacks.push(callback);return}}else{callback(true)}};Loki.prototype.loadDatabaseInternal=function(options,callback){var cFun=callback||function(err,data){if(err){throw err}},self=this;if(this.persistenceAdapter!==null){this.persistenceAdapter.loadDatabase(this.filename,function loadDatabaseCallback(dbString){if(typeof dbString==="string"){var parseSuccess=false;try{self.loadJSON(dbString,options||{});parseSuccess=true}catch(err){cFun(err)}if(parseSuccess){cFun(null);self.emit("loaded","database "+self.filename+" loaded")}}else{if(!dbString){cFun(null);self.emit("loaded","empty database "+self.filename+" loaded");return}if(dbString instanceof Error){cFun(dbString);return}if(typeof dbString==="object"){self.loadJSONObject(dbString,options||{});cFun(null);self.emit("loaded","database "+self.filename+" loaded");return}cFun("unexpected adapter response : "+dbString)}})}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.loadDatabase=function(options,callback){var self=this;if(!this.throttledSaves){this.loadDatabaseInternal(options,callback);return}this.throttledSaveDrain(function(success){if(success){self.throttledSavePending=true;self.loadDatabaseInternal(options,function(err){if(self.throttledCallbacks.length===0){self.throttledSavePending=false}else{self.saveDatabase()}if(typeof callback==="function"){callback(err)}});return}else{if(typeof callback==="function"){callback(new Error("Unable to pause save throttling long enough to read database"))}}},options)};Loki.prototype.saveDatabaseInternal=function(callback){var cFun=callback||function(err){if(err){throw err}return},self=this;if(this.persistenceAdapter!==null){if(this.persistenceAdapter.mode==="reference"&&typeof this.persistenceAdapter.exportDatabase==="function"){this.persistenceAdapter.exportDatabase(this.filename,this.copy({removeNonSerializable:true}),function exportDatabaseCallback(err){self.autosaveClearFlags();cFun(err)})}else{self.autosaveClearFlags();this.persistenceAdapter.saveDatabase(this.filename,self.serialize(),function saveDatabasecallback(err){cFun(err)})}}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.saveDatabase=function(callback){if(!this.throttledSaves){this.saveDatabaseInternal(callback);return}if(this.throttledSavePending){this.throttledCallbacks.push(callback);return}var localCallbacks=this.throttledCallbacks;this.throttledCallbacks=[];localCallbacks.unshift(callback);this.throttledSavePending=true;var self=this;this.saveDatabaseInternal(function(err){self.throttledSavePending=false;localCallbacks.forEach(function(pcb){if(typeof pcb==="function"){setTimeout(function(){pcb(err)},1)}});if(self.throttledCallbacks.length>0){self.saveDatabase()}})};Loki.prototype.save=Loki.prototype.saveDatabase;Loki.prototype.deleteDatabase=function(options,callback){var cFun=callback||function(err,data){if(err){throw err}};if(typeof options==="function"&&!callback){cFun=options}if(this.persistenceAdapter!==null){this.persistenceAdapter.deleteDatabase(this.filename,function deleteDatabaseCallback(err){cFun(err)})}else{cFun(new Error("persistenceAdapter not configured"))}};Loki.prototype.autosaveDirty=function(){for(var idx=0;idx0){this.filteredrows=[]}this.filterInitialized=false;return this};Resultset.prototype.toJSON=function(){var copy=this.copy();copy.collection=null;return copy};Resultset.prototype.limit=function(qty){if(!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=this.collection.prepareFullDocIndex()}var rscopy=new Resultset(this.collection);rscopy.filteredrows=this.filteredrows.slice(0,qty);rscopy.filterInitialized=true;return rscopy};Resultset.prototype.offset=function(pos){if(!this.filterInitialized&&this.filteredrows.length===0){this.filteredrows=this.collection.prepareFullDocIndex()}var rscopy=new Resultset(this.collection);rscopy.filteredrows=this.filteredrows.slice(pos);rscopy.filterInitialized=true;return rscopy};Resultset.prototype.copy=function(){var result=new Resultset(this.collection);if(this.filteredrows.length>0){result.filteredrows=this.filteredrows.slice()}result.filterInitialized=this.filterInitialized;return result};Resultset.prototype.branch=Resultset.prototype.copy;Resultset.prototype.transform=function(transform,parameters){var idx,step,rs=this;if(typeof transform==="string"){if(this.collection.transforms.hasOwnProperty(transform)){transform=this.collection.transforms[transform]}}if(typeof transform!=="object"||!Array.isArray(transform)){throw new Error("Invalid transform")}if(typeof parameters!=="undefined"){transform=Utils.resolveTransformParams(transform,parameters)}for(idx=0;idxobj2[propname])return 1;if(obj1[propname]1){return this.find({$and:filters},firstOnly)}}if(!property||queryObject==="getAll"){if(firstOnly){this.filteredrows=this.collection.data.length>0?[0]:[];this.filterInitialized=true}return this}if(property==="$and"||property==="$or"){this[property](queryObjectOp);if(firstOnly&&this.filteredrows.length>1){this.filteredrows=this.filteredrows.slice(0,1)}return this}if(queryObjectOp===null||(typeof queryObjectOp!=="object"||queryObjectOp instanceof Date)){operator="$eq";value=queryObjectOp}else if(typeof queryObjectOp==="object"){for(key in queryObjectOp){if(hasOwnProperty.call(queryObjectOp,key)){operator=key;value=queryObjectOp[key];break}}}else{throw new Error("Do not know what you want to do.")}if(operator==="$regex"){if(Array.isArray(value)){value=new RegExp(value[0],value[1])}else if(!(value instanceof RegExp)){value=new RegExp(value)}}var usingDotNotation=property.indexOf(".")!==-1;var doIndexCheck=!usingDotNotation&&!this.filterInitialized;if(doIndexCheck&&this.collection.binaryIndices[property]&&indexedOps[operator]){if(this.collection.adaptiveBinaryIndices!==true){this.collection.ensureIndex(property)}searchByIndex=true;index=this.collection.binaryIndices[property]}var fun=LokiOps[operator];var t=this.collection.data;var i=0,len=0;var filter,rowIdx=0;if(this.filterInitialized){filter=this.filteredrows;len=filter.length;if(usingDotNotation){property=property.split(".");for(i=0;i=0){this.filterPipeline[idx]=filter;return this.reapplyFilters()}this.cachedresultset=null;if(this.options.persistent){this.resultdata=[];this.resultsdirty=true}this._addFilter(filter);if(this.sortFunction||this.sortCriteria||this.sortCriteriaSimple){this.queueSortPhase()}else{this.queueRebuildEvent()}return this};DynamicView.prototype.applyFind=function(query,uid){this.applyFilter({type:"find",val:query,uid:uid});return this};DynamicView.prototype.applyWhere=function(fun,uid){this.applyFilter({type:"where",val:fun,uid:uid});return this};DynamicView.prototype.removeFilter=function(uid){var idx=this._indexOfFilterWithId(uid);if(idx<0){throw new Error("Dynamic view does not contain a filter with ID: "+uid)}this.filterPipeline.splice(idx,1);this.reapplyFilters();return this};DynamicView.prototype.count=function(){if(this.resultsdirty){this.resultdata=this.resultset.data()}return this.resultset.count()};DynamicView.prototype.data=function(options){if(this.sortDirty||this.resultsdirty){this.performSortPhase({suppressRebuildEvent:true})}return this.options.persistent?this.resultdata:this.resultset.data(options)};DynamicView.prototype.queueRebuildEvent=function(){if(this.rebuildPending){return}this.rebuildPending=true;var self=this;setTimeout(function(){if(self.rebuildPending){self.rebuildPending=false;self.emit("rebuild",self)}},this.options.minRebuildInterval)};DynamicView.prototype.queueSortPhase=function(){if(this.sortDirty){return}this.sortDirty=true;var self=this;if(this.options.sortPriority==="active"){setTimeout(function(){self.performSortPhase()},this.options.minRebuildInterval)}else{this.queueRebuildEvent()}};DynamicView.prototype.performSortPhase=function(options){if(!this.sortDirty&&!this.resultsdirty){return}options=options||{};if(this.sortDirty){if(this.sortFunction){this.resultset.sort(this.sortFunction)}else if(this.sortCriteria){this.resultset.compoundsort(this.sortCriteria)}else if(this.sortCriteriaSimple){this.resultset.simplesort(this.sortCriteriaSimple.propname,this.sortCriteriaSimple.options)}this.sortDirty=false}if(this.options.persistent){this.resultdata=this.resultset.data();this.resultsdirty=false}if(!options.suppressRebuildEvent){this.emit("rebuild",this)}};DynamicView.prototype.evaluateDocument=function(objIndex,isNew){if(!this.resultset.filterInitialized){if(this.options.persistent){this.resultdata=this.resultset.data()}if(this.sortFunction||this.sortCriteria||this.sortCriteriaSimple){this.queueSortPhase()}else{this.queueRebuildEvent()}return}var ofr=this.resultset.filteredrows;var oldPos=isNew?-1:ofr.indexOf(+objIndex);var oldlen=ofr.length;var evalResultset=new Resultset(this.collection);evalResultset.filteredrows=[objIndex];evalResultset.filterInitialized=true;var filter;for(var idx=0,len=this.filterPipeline.length;idx0){this.resultset.filteredrows=this.resultset.filteredrows.filter(function(di,idx){return!fxo[idx]});if(this.options.persistent){this.resultdata=this.resultdata.filter(function(obj,idx){return!fxo[idx]})}if(this.sortFunction||this.sortCriteria||this.sortCriteriaSimple){this.queueSortPhase()}else{this.queueRebuildEvent()}}var filt=function(idx){return function(di){return di=0||propertyName=="$loki"||propertyName=="meta"){delta[propertyName]=newObject[propertyName]}else{var propertyDelta=getObjectDelta(oldObject[propertyName],newObject[propertyName]);if(typeof propertyDelta!=="undefined"&&propertyDelta!={}){delta[propertyName]=propertyDelta}}}}return Object.keys(delta).length===0?undefined:delta}else{return oldObject===newObject?undefined:newObject}}this.getObjectDelta=getObjectDelta;function flushChanges(){self.changes=[]}this.getChanges=function(){return self.changes};this.flushChanges=flushChanges;this.setChangesApi=function(enabled){self.disableChangesApi=!enabled;if(!enabled){self.disableDeltaChangesApi=false}};this.on("delete",function deleteCallback(obj){if(!self.disableChangesApi){self.createChange(self.name,"R",obj)}});this.on("warning",function(warning){self.console.warn(warning)});flushChanges()}Collection.prototype=new LokiEventEmitter;Collection.prototype.createChange=function(name,op,obj,old){this.changes.push({name:name,operation:op,obj:op=="U"&&!this.disableDeltaChangesApi?this.getChangeDelta(obj,old):JSON.parse(JSON.stringify(obj))})} +;Collection.prototype.insertMeta=function(obj){var len,idx;if(this.disableMeta||!obj){return}if(Array.isArray(obj)){len=obj.length;for(idx=0;idx1){options.randomSamplingFactor=.1}var valid=true,idx,iter,pos,len,biv;if(!this.binaryIndices.hasOwnProperty(property)){throw new Error("called checkIndex on property without an index: "+property)}if(!this.adaptiveBinaryIndices){this.ensureIndex(property)}biv=this.binaryIndices[property].values;len=biv.length;if(len!==this.data.length){if(options.repair){this.ensureIndex(property,true)}return false}if(len===0){return true}if(len===1){valid=biv[0]===0}else{if(options.randomSampling){if(!LokiOps.$lte(this.data[biv[0]][property],this.data[biv[1]][property])){valid=false}if(!LokiOps.$lte(this.data[biv[len-2]][property],this.data[biv[len-1]][property])){valid=false}if(valid){iter=Math.floor((len-1)*options.randomSamplingFactor);for(idx=0;idx0;if(adaptiveBatchOverride){this.adaptiveBinaryIndices=false}try{for(k=0;k0;var doc,self=this;try{this.startTransaction();for(idx=0;idx0||bic>0||uic>0){if(dlen>0){for(didx=0;didx1){for(idx=0;idx>1;id=typeof id==="number"?id:parseInt(id,10);if(isNaN(id)){throw new TypeError("Passed id is not an integer")}while(data[min]>1;if(data[mid]sortedPositions[rmidx];rmidx++){shift++}bi.values[idx]-=shift}return}}idxPos=this.getBinaryIndexPosition(dataPosition,binaryIndexName);if(idxPos===null){return null}bi.values.splice(idxPos,1);if(removedFromIndexOnly===true){return}len=bi.values.length;for(idx=0;idxdataPosition){bi.values[idx]--}}};Collection.prototype.calculateRangeStart=function(prop,val,adaptive){var rcd=this.data;var index=this.binaryIndices[prop].values;var min=0;var max=index.length-1;var mid=0;if(index.length===0){return-1}var minVal=rcd[index[min]][prop];var maxVal=rcd[index[max]][prop];while(min>1;if(Comparators.lt(rcd[index[mid]][prop],val,false)){min=mid+1}else{max=mid}}var lbound=min;if(Comparators.aeq(val,rcd[index[lbound]][prop])){return lbound}if(Comparators.lt(val,rcd[index[lbound]][prop],false)){return adaptive?lbound:lbound-1}return adaptive?lbound+1:lbound};Collection.prototype.calculateRangeEnd=function(prop,val){var rcd=this.data;var index=this.binaryIndices[prop].values;var min=0;var max=index.length-1;var mid=0;if(index.length===0){return-1}var minVal=rcd[index[min]][prop];var maxVal=rcd[index[max]][prop];while(min>1;if(Comparators.lt(val,rcd[index[mid]][prop],false)){max=mid}else{min=mid+1}}var ubound=max;if(Comparators.aeq(val,rcd[index[ubound]][prop])){return ubound}if(Comparators.gt(val,rcd[index[ubound]][prop],false)){return ubound+1}if(Comparators.aeq(val,rcd[index[ubound-1]][prop])){return ubound-1}return ubound};Collection.prototype.calculateRange=function(op,prop,val){var rcd=this.data;var index=this.binaryIndices[prop].values;var min=0;var max=index.length-1;var mid=0;var lbound,lval;var ubound,uval;if(rcd.length===0){return[0,-1]}var minVal=rcd[index[min]][prop];var maxVal=rcd[index[max]][prop];switch(op){case"$eq":case"$aeq":if(Comparators.lt(val,minVal,false)||Comparators.gt(val,maxVal,false)){return[0,-1]}break;case"$dteq":if(Comparators.lt(val,minVal,false)||Comparators.gt(val,maxVal,false)){return[0,-1]}break;case"$gt":if(Comparators.gt(val,maxVal,true)){return[0,-1]}if(Comparators.gt(minVal,val,false)){return[min,max]}break;case"$gte":if(Comparators.gt(val,maxVal,false)){return[0,-1]}if(Comparators.gt(minVal,val,true)){return[min,max]}break;case"$lt":if(Comparators.lt(val,minVal,true)){return[0,-1]}if(Comparators.lt(maxVal,val,false)){return[min,max]}break;case"$lte":if(Comparators.lt(val,minVal,false)){return[0,-1]}if(Comparators.lt(maxVal,val,true)){return[min,max]}break;case"$between":if(Comparators.gt(val[0],maxVal,false)){return[0,-1]}if(Comparators.lt(val[1],minVal,false)){return[0,-1]}lbound=this.calculateRangeStart(prop,val[0]);ubound=this.calculateRangeEnd(prop,val[1]);if(lbound<0)lbound++;if(ubound>max)ubound--;if(!Comparators.gt(rcd[index[lbound]][prop],val[0],true))lbound++;if(!Comparators.lt(rcd[index[ubound]][prop],val[1],true))ubound--;if(ubounddeepProperty(this.data[i],field,deep)){min=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}else{min=deepProperty(this.data[i],field,deep);result.index=this.data[i].$loki}}result.value=min;return result};Collection.prototype.extractNumerical=function(field){return this.extract(field).map(parseBase10).filter(Number).filter(function(n){return!isNaN(n)})};Collection.prototype.avg=function(field){return average(this.extractNumerical(field))};Collection.prototype.stdDev=function(field){return standardDeviation(this.extractNumerical(field))};Collection.prototype.mode=function(field){var dict={},data=this.extract(field);data.forEach(function(obj){if(dict[obj]){dict[obj]+=1}else{dict[obj]=1}});var max,prop,mode;for(prop in dict){if(max){if(max0){root=root[pieces.shift()]}return root}function binarySearch(array,item,fun){var lo=0,hi=array.length,compared,mid;while(lo>1;compared=fun.apply(null,[item,array[mid]]);if(compared===0){return{found:true,index:mid}}else if(compared<0){hi=mid}else{lo=mid+1}}return{found:false,index:hi}}function BSonSort(fun){return function(array,item){return binarySearch(array,item,fun)}}function KeyValueStore(){}KeyValueStore.prototype={keys:[],values:[],sort:function(a,b){return ab?1:0},setSort:function(fun){this.bs=new BSonSort(fun)},bs:function(){return new BSonSort(this.sort)},set:function(key,value){var pos=this.bs(this.keys,key);if(pos.found){this.values[pos.index]=value}else{this.keys.splice(pos.index,0,key);this.values.splice(pos.index,0,value)}},get:function(key){return this.values[binarySearch(this.keys,key,this.sort).index]}};function UniqueIndex(uniqueField){this.field=uniqueField;this.keyMap={};this.lokiMap={}}UniqueIndex.prototype.keyMap={};UniqueIndex.prototype.lokiMap={};UniqueIndex.prototype.set=function(obj){var fieldValue=obj[this.field];if(fieldValue!==null&&typeof fieldValue!=="undefined"){if(this.keyMap[fieldValue]){throw new Error("Duplicate key for property "+this.field+": "+fieldValue)}else{this.keyMap[fieldValue]=obj;this.lokiMap[obj.$loki]=fieldValue}}};UniqueIndex.prototype.get=function(key){return this.keyMap[key]};UniqueIndex.prototype.byId=function(id){return this.keyMap[this.lokiMap[id]]};UniqueIndex.prototype.update=function(obj,doc){if(this.lokiMap[obj.$loki]!==doc[this.field]){var old=this.lokiMap[obj.$loki];this.set(doc);this.keyMap[old]=undefined}else{this.keyMap[obj[this.field]]=doc}};UniqueIndex.prototype.remove=function(key){var obj=this.keyMap[key];if(obj!==null&&typeof obj!=="undefined"){this.keyMap[key]=undefined;this.lokiMap[obj.$loki]=undefined}else{throw new Error("Key is not in unique index: "+this.field)}};UniqueIndex.prototype.clear=function(){this.keyMap={};this.lokiMap={}};function ExactIndex(exactField){this.index={};this.field=exactField}ExactIndex.prototype={set:function add(key,val){if(this.index[key]){this.index[key].push(val)}else{this.index[key]=[val]}},remove:function remove(key,val){var idxSet=this.index[key];for(var i in idxSet){if(idxSet[i]==val){idxSet.splice(i,1)}}if(idxSet.length<1){this.index[key]=undefined}},get:function get(key){return this.index[key]},clear:function clear(key){this.index={}}};function SortedIndex(sortedField){this.field=sortedField}SortedIndex.prototype={keys:[],values:[],sort:function(a,b){return ab?1:0},bs:function(){return new BSonSort(this.sort)},setSort:function(fun){this.bs=new BSonSort(fun)},set:function(key,value){var pos=binarySearch(this.keys,key,this.sort);if(pos.found){this.values[pos.index].push(value)}else{this.keys.splice(pos.index,0,key);this.values.splice(pos.index,0,[value])}},get:function(key){var bsr=binarySearch(this.keys,key,this.sort);if(bsr.found){return this.values[bsr.index]}else{return[]}},getLt:function(key){var bsr=binarySearch(this.keys,key,this.sort);var pos=bsr.index;if(bsr.found)pos--;return this.getAll(key,0,pos)},getGt:function(key){var bsr=binarySearch(this.keys,key,this.sort);var pos=bsr.index;if(bsr.found)pos++;return this.getAll(key,pos,this.keys.length)},getAll:function(key,start,end){var results=[];for(var i=start;i build/loki-indexed-adapter.min.js", + "build:lokijs": "uglifyjs src/lokijs.js > build/lokijs.min.js", + "clean": "rimraf build/* coverage/* node_modules", + "jsdoc": "jsdoc -c jsdoc-conf.json", + "lint": "jshint src", + "postbuild": "karma start karma.build.conf.js --single-run", + "pour:beer": "echo New npm version published, one beer for you !", + "prepublish": "npm run build", + "pretest": "npm run lint", + "test": "npm run test:browser && npm run test:node", + "test:browser": "karma start karma.conf.js --single-run", + "test:node": "istanbul cover --dir coverage/nodejs node_modules/jasmine/bin/jasmine.js" + }, + "version": "1.5.5" +} diff --git a/node_modules/lokijs/src/aws-s3-sync-adapter.js b/node_modules/lokijs/src/aws-s3-sync-adapter.js new file mode 100644 index 00000000..154c67fe --- /dev/null +++ b/node_modules/lokijs/src/aws-s3-sync-adapter.js @@ -0,0 +1,175 @@ +/** + * LokiJS AWSS3SyncAdapter + * @author Simon Hutchison + * + * A remote sync adapter for LokiJS to AWS S3 + * + * Basic usage: + * + const AWS = require('aws-sdk') + const Loki = require('lokijs') + const AWSS3SyncAdapter = require('./aws-s3-sync-adapter.js') + var db + + var _init = function () { + const options = { + 'AWS': AWS, + 'accessKeyId': process.env.accessKeyId, // Avoid hardcoding credentials + 'secretAccessKey': process.env.secretAccessKey, // Avoid hardcoding credentials + 'bucket': '...' + } + const adapter = new AWSS3SyncAdapter(options); + db = new Loki('somefile.json', { + autoload: false, + autosave: true, + adapter: adapter + }) + } + + var _save = function () { + db.saveDatabase(function (err, data) { + if (err) { + console.log(err) + process.exit() + } else { + console.log('DB saved to AWS S3') + _load() // Now attempt to load it back. + } + }) + } + + var _load = function () { + db.loadDatabase({}, function (err) { + if (err) { + console.log(err) + process.exit() + } else { + console.log('DB loaded from AWS S3') + process.exit() + } + }) + } + + _init() + _save() + * + */ + +/* eslint */ +/* global define */ + +/* jslint browser: true, node: true, plusplus: true, indent: 2 */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD + define([], factory); + } else if (typeof exports === 'object') { + // CommonJS + module.exports = factory(); + } else { + // Browser globals + root.lokiAWSS3SyncAdapter = factory(); + } +}(this, function () { + return (function (options) { + 'use strict'; + + function AWSS3SyncAdapterError (message) { + this.name = 'AWSS3SyncAdapterError'; + this.message = (message || ''); + } + + AWSS3SyncAdapterError.prototype = Error.prototype; + + /** + * This adapter requires an object options is passed containing the following properties: + * AWS: Reference to the AWS SDK. + * accessKeyId: AWS access key ID + * secretAccessKey: AWS secret access key + * bucket: A global aws bucket name + */ + + function AWSS3SyncAdapter (options) { + this.options = options; + + if (!options) { + throw new AWSS3SyncAdapterError('No options configured in AWSS3SyncAdapter'); + } + + if (!options.AWS) { + throw new AWSS3SyncAdapterError('No AWS library specified in options'); + } + + if (!options.accessKeyId) { + throw new AWSS3SyncAdapterError('No accessKeyId property specified in options'); + } + + if (!options.secretAccessKey) { + throw new AWSS3SyncAdapterError('No secretAccessKey property specified in options'); + } + + if (!options.bucket) { + throw new AWSS3SyncAdapterError('No bucket property specified in options'); + } + + this.options.AWS.config.update({accessKeyId: options.accessKeyId, secretAccessKey: options.secretAccessKey}); + } + + AWSS3SyncAdapter.prototype.saveDatabase = function (name, data, callback) { + console.log('AWSS3SyncAdapter.prototype.saveDatabase():', name); + + const s3 = new this.options.AWS.S3(); + const base64str = Buffer.from(data).toString('base64'); + + var params = { + Body: base64str, + Bucket: this.options.bucket, + Key: name, + ServerSideEncryption: 'AES256', + Tagging: '' // key1=value1&key2=value2 + }; + + s3.putObject(params, function (err, data) { + if (err) { + console.log('AWSS3SyncAdapter.prototype.saveDatabase() Error:', err, err.stack); + throw new AWSS3SyncAdapterError('Remote sync failed'); + } else { + return callback(null, data); + } + }); + }; + + AWSS3SyncAdapter.prototype.loadDatabase = function (name, callback) { + console.log('AWSS3SyncAdapter.prototype.loadDatabase():', name); + const s3 = new this.options.AWS.S3(); + + var params = { + Bucket: this.options.bucket, + Key: name + }; + + s3.getObject(params, function (err, data) { + if (err) { + console.log('AWSS3SyncAdapter.prototype.loadDatabase() Error:', err, err.stack); + throw new AWSS3SyncAdapterError('Remote load failed'); + } else { + if (!data.Body) { + throw new AWSS3SyncAdapterError('Remote load failed, no data found'); + } + try { + var base64data = data.Body.toString(); + var asciiData = Buffer.from(base64data, 'base64').toString(); + var lokiDBObj = JSON.parse(asciiData); // For json objects + console.log('AWSS3SyncAdapter.prototype.loadDatabase() asciiData:', lokiDBObj); + return callback(lokiDBObj); + } catch (e) { + throw new AWSS3SyncAdapterError('Remote load failed, invalid loki database'); + } + } + }); + }; + + return AWSS3SyncAdapter; + }()); +})); diff --git a/node_modules/lokijs/src/jquery-sync-adapter.js b/node_modules/lokijs/src/jquery-sync-adapter.js new file mode 100644 index 00000000..3366f168 --- /dev/null +++ b/node_modules/lokijs/src/jquery-sync-adapter.js @@ -0,0 +1,92 @@ +/** + * LokiJS JquerySyncAdapter + * @author Joe Minichino + * + * A remote sync adapter example for LokiJS + */ + +/*jslint browser: true, node: true, plusplus: true, indent: 2 */ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD + define([], factory); + } else if (typeof exports === 'object') { + // CommonJS + module.exports = factory(); + } else { + // Browser globals + root.lokiJquerySyncAdapter = factory(); + } +}(this, function () { + + return (function (options) { + 'use strict'; + + function JquerySyncAdapterError(message) { + this.name = "JquerySyncAdapterError"; + this.message = (message || ""); + } + + JquerySyncAdapterError.prototype = Error.prototype; + + /** + * this adapter assumes an object options is passed, + * containing the following properties: + * ajaxLib: jquery or compatible ajax library + * save: { url: the url to save to, dataType [optional]: json|xml|etc., type [optional]: POST|GET|PUT} + * load: { url: the url to load from, dataType [optional]: json|xml| etc., type [optional]: POST|GET|PUT } + */ + + function JquerySyncAdapter(options) { + this.options = options; + + if (!options) { + throw new JquerySyncAdapterError('No options configured in JquerySyncAdapter'); + } + + if (!options.ajaxLib) { + throw new JquerySyncAdapterError('No ajaxLib property specified in options'); + } + + if (!options.save || !options.load) { + throw new JquerySyncAdapterError('Please specify load and save properties in options'); + } + if (!options.save.url || !options.load.url) { + throw new JquerySyncAdapterError('load and save objects must have url property'); + } + } + + JquerySyncAdapter.prototype.saveDatabase = function (name, data, callback) { + this.options.ajaxLib.ajax({ + type: this.options.save.type || 'POST', + url: this.options.save.url, + data: data, + success: callback, + failure: function () { + throw new JquerySyncAdapterError("Remote sync failed"); + }, + dataType: this.options.save.dataType || 'json' + }); + }; + + JquerySyncAdapter.prototype.loadDatabase = function (name, callback) { + this.options.ajaxLib.ajax({ + type: this.options.load.type || 'GET', + url: this.options.load.url, + data: { + // or whatever parameter to fetch the db from a server + name: name + }, + success: callback, + failure: function () { + throw new JquerySyncAdapterError("Remote load failed"); + }, + dataType: this.options.load.dataType || 'json' + }); + }; + + return JquerySyncAdapter; + + }()); +})); \ No newline at end of file diff --git a/node_modules/lokijs/src/loki-angular.js b/node_modules/lokijs/src/loki-angular.js new file mode 100644 index 00000000..da8cfefe --- /dev/null +++ b/node_modules/lokijs/src/loki-angular.js @@ -0,0 +1,621 @@ +/* + Loki Angular Adapter (need to include this script to use it) + * @author Joe Minichino + * + * A lightweight document oriented javascript database + */ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['angular', 'lokijs'], factory); + } else if (typeof exports === 'object') { + // CommonJS + module.exports = factory(); + } else { + // Browser globals + root.lokiAngular = factory( + root.angular, + // Use thirdParty.loki if available to cover all legacy cases + root.thirdParty && root.thirdParty.loki ? + root.thirdParty.loki : root.loki + ); + } +}(this, function (angular, lokijs) { + var module = angular.module('lokijs', []) + .factory('Loki', Loki) + .service('Lokiwork', Lokiwork); + + function Loki() { + return loki; + } + Lokiwork.$inject = ['Loki', '$q', '$injector', '$window']; + + function Lokiwork(Loki, $q, $injector, $window) { + var vm = this; + vm.checkStates = checkStates; + var statesChecked = false; + var db; + var userDbPreference = ''; + var userPrefJsonFile = 0; + var numOfJsonDatabases = 0; + var dbitems = []; + var lokidbs = []; + vm.dbExists = dbExists; + vm.closeDb = closeDb; + vm.closeAllDbs = closeAllDbs; + vm.getCollection = getCollection; + vm.addCollection = addCollection; + vm.removeCollection = removeCollection; + vm.getDoc = getDoc; + vm.updateDoc = updateDoc; + vm.updateCurrentDoc = updateCurrentDoc; + vm.setCurrentDoc = setCurrentDoc; + vm.getCurrentDoc = getCurrentDoc; + vm.deleteDocument = deleteDocument; + vm.deleteCurrentDoc = deleteCurrentDoc; + vm.deleteDatabase = deleteDatbase; + vm.addDocument = addDocument; + vm.insertItemInDoc = insertItemInDoc; + var currentDoc = {}; + var currentColl = {}; + numOfJsonDatabases = getNumberOfJsonDatabases(); + + function getCurrentDoc() { + return currentDoc; + } + + function deleteDatbase(data) { + localStorage.removeItem(data); + } + + function deleteDocument(dbName, collName, doc) { //doc should be in {name:value} format + return $q(function (resolve, reject) { + userDbPreference = dbName; + _getem('delete_doc', dbName, collName, doc) + .then(function (data) { + currentDoc = {}; + resolve(data); + }, function(data){ + reject(data); + }); + }); + } + + + function insertItemInDoc(item) { + return $q(function (resolve, reject) { + _getem('insert_item_in_doc', currentDoc.dbName, currentDoc.collName, currentDoc.doc, "", item) + .then(function (data) { + resolve(data); + }, function (data) { + reject(data); + }); + }); + } + + function deleteCurrentDoc() { + return $q(function (resolve, reject) { + _getem('delete_current_doc') + .then(function (data) { + resolve(data); + }, function (data) { + reject(data); + }); + }); + } + + function addDocument(dbName, collName, newDoc) { + return $q(function (resolve, reject) { + userDbPreference = dbName; + _getem('create_doc', dbName, collName, "", "", newDoc) + .then(function (data) { + currentDoc.dbName = dbName; + currentDoc.collName = collName; + currentDoc.doc = data; + currentDoc.lokiNum = data[0].$loki; + resolve(data[0]); + }, function(data){ + reject(data); + }); + }); + } + + function setCurrentDoc(dbName, collName, docName) { + return $q(function (resolve, reject) { + userDbPreference = dbName; + _getem('set_doc', dbName, collName, docName) + .then(function (data) { + currentDoc.dbName = dbName; + currentDoc.collName = collName; + currentDoc.doc = data; + currentDoc.lokiNum = data[0].$loki; + resolve(data[0]); + }, function(data){ + reject(data); + }); + }); + } + + function updateCurrentDoc(thekey, thevalue) { + return $q(function (resolve, reject) { + if (currentDoc) { + _getem('update_current_doc', currentDoc.dbName, currentDoc.collName, currentDoc.doc, thekey, thevalue) + .then(function (data) { + resolve(data[0]); + }, function(data){ + reject(data); + }); + } else { + reject("you have to set a current doc first, use: setCurrentDoc(dbName, collName, docName)"); + } + }); + } + + function updateDoc(dbName, collName, docName, thekey, thevalue) { + return $q(function (resolve, reject) { + userDbPreference = dbName; + if (currentDoc) { + _getem('update_doc', dbName, collName, docName, thekey, thevalue) + .then(function (data) { + resolve(data[0]); + }, function(data){ + reject(data); + }); + } else { + reject("bad, check parameters)"); + } + }); + } + + function getDoc(dbName, collName, docName) { + return $q(function (resolve, reject) { + userDbPreference = dbName; + _getem('get_doc', dbName, collName, docName) + .then(function (data) { + currentDoc.dbName = dbName; + currentDoc.collName = collName; + currentDoc.doc = data; + currentDoc.lokiNum = data[0].$loki; + resolve(data[0]); + }, function(data){ + reject(data); + }); + }); + } + + function getCollection(dbName, collName) { + return $q(function (resolve, reject) { + userDbPreference = dbName; + _getem('get_collection', dbName, collName) + .then(function (data) { + currentColl.dbName = dbName; + currentColl.collName = collName; + resolve(data); + }, function(data){ + reject(data); + }); + }); + } + + function removeCollection(dbName, collName) { + return $q(function (resolve, reject) { + userDbPreference = dbName; + _getem('remove_collection', dbName, collName) + .then(function (data) { + currentColl = {}; + resolve(data); + }, function(data){ + reject(data); + }); + }); + } + + function addCollection(collData) { + return $q(function (resolve, reject) { + var dbobj = breakdown_components(collData); + userDbPreference = collData[dbobj.db]; + _getem('add_collection', userDbPreference, '', '', '', collData) + .then(function (data) { + currentColl.dbName = userDbPreference; + resolve(data); + }, function(data){ + reject(data); + }); + }); + } + + function _getem(operation, dbName, collName, docName, thekey, thevalue) { + return $q(function (resolve, reject) { + if (db) { + if (db.filename === dbName) { + getdata(); + } else { + loadDb(dbName) + .then(function () { + getdata(); + }); + } + } else { + if (statesChecked) { + loadDb(dbName) + .then(function () { + getdata(); + }); + } else { + checkStates().then(function () { + getdata(); + }, function(data){ + reject(data); + }); + } + } + + + + function getdata() { + var found; + + if (operation === 'update_doc' || operation === 'insert_item_in_doc') { + db.loadDatabase(dbName); + var coll = db.getCollection(collName); + + //docName is not simply a docname, this is an object like: {name: 'user settings'} + for(var i in docName) { + currentDoc.key = i; + currentDoc.value = docName[i]; + } + for (var x = 0; x < coll.data.length; x++){ + if (coll.data[x][currentDoc.key] === currentDoc.value){ + currentDoc.lokiNum = coll.data[x].$loki; + } + } + found = coll.get(parseInt(currentDoc.lokiNum, 10)); + + if (operation === 'update_doc') { + found[thekey] = thevalue; + coll.update(found); + } else { + found.insert(thevalue); + } + db.save(); + resolve(true); + } + else if(operation === 'update_current_doc'){ + db.loadDatabase(dbName); + var coll0 = db.getCollection(collName); + found = coll0.get(parseInt(currentDoc.lokiNum, 10)); + found[thekey] = thevalue; + coll0.update(found); + + db.save(); + resolve(true); + } + else if (operation === 'delete_current_doc' || operation === 'delete_doc') { + db.loadDatabase(dbName); + var coll6 = db.getCollection(collName); + if(operation === 'delete_doc'){ + for(var j in docName) { + currentDoc.key = j; + currentDoc.value = docName[j]; + } + for (var y = 0; y < coll6.data.length; y++){ + if (coll6.data[y][currentDoc.key] === currentDoc.value){ + currentDoc.lokiNum = coll6.data[y].$loki; + } + } + } + coll6.remove(currentDoc.lokiNum); + db.save(); + resolve(true); + } + else if (operation === 'get_doc' || operation === 'set_doc') { + db.loadDatabase(dbName); + var coll1 = db.getCollection(collName); + found = coll1.find(docName); + resolve(angular.fromJson(found)); + } else if (operation === 'get_collection') { + db.loadDatabase(dbName); + var coll2 = db.getCollection(collName); + resolve(angular.fromJson(coll2)); + } else if (operation === 'remove_collection') { + db.loadDatabase(dbName); + db.removeCollection(collName); + //coll = db.getCollection(collName); + db.save(function () { + resolve('collection deleted'); + }); + } else if (operation === 'add_collection') { + db.loadDatabase(dbName); + var dbobj = breakdown_components(thevalue); + + for (var w=0; w< dbobj.coll_array.length; w++){ + var items = db.addCollection(thevalue[dbobj.coll_array[w].coll]); + items.insert(thevalue[dbobj.coll_array[w].docs]); + } + + db.save(function () { + resolve('collection(s) added'); + }); + + } else if (operation === 'create_doc') { + db.loadDatabase(dbName); + var coll3 = db.getCollection(collName); + coll3.insert(thevalue); + db.save(function () { + var found = coll3.find({ + name: thevalue.name + }); + resolve(angular.fromJson(found)); + }); + + } + // _getem('delete_doc', dbName, collName, "", "", doc) + else if (operation === 'delete_current_doc') { + var coll5 = db.getCollection(currentDoc.collName); + if (!coll5) { + reject('You forgot to specify a current doc first'); + } else { + coll5.remove(parseInt(currentDoc.lokiNum, 10)); + db.save(); + resolve(true); + } + } + } + }); + } + + function dbExists(databaseName) { + var value = window.localStorage.getItem(databaseName); + if (value) { + return true; + } else { + return false; + } + } + + function closeAllDbs() { + return $q(function (resolve, reject) { + var current = 0; + for (var x = 0; x < lokidbs.length; x++) { + current++; + lokidbs[x].close(); + if (x === (lokidbs.length - 1)) { + resolve(); + } + } + }); + } + + function closeDb(databaseName) { + return $q(function (resolve, reject) { + + for (var x = 0; x < lokidbs.length; x++) { + if (lokidbs.filename === databaseName) { + lokidbs[x].close(); + resolve(); + break; + } + } + + }); + } + + + function checkStates() { + return $q(function (resolve, reject) { + if (dbitems.length === 0) { + initialiseAll().then(function () { + console.log('had to initialize all dbs'); + statesChecked = true; + resolve(); + }, function (data) { + reject(data); + }); + } else { + console.log('db list already initialized'); + resolve(); + } + }); + } + + function firstFewItemsOfDbList() { + return $q(function (resolve, reject) { + for (var x = 0; x >= 0; x++) { + if ($injector.has('json' + (x + 1))) { + var item = {}; + var setting = $injector.get('json' + (x + 1)); + var dbobj = breakdown_components(setting); + if (setting[dbobj.db] === userDbPreference) { //userDbPreference is the name + userPrefJsonFile = x + 1; //userPrefJsonFile is the index + if (x === (numOfJsonDatabases - 1)) { + resolve(); + } + } else { + item.filename = dbobj.db; + item.json = x + 1; + dbitems.push(item); + if (x === (numOfJsonDatabases - 1)) { + resolve(); + } + } + } + else { + resolve(); + break; + } + } + }); + } + + function initialiseDbList() { + return $q(function (resolve, reject) { + firstFewItemsOfDbList() + .then(function () { + if (userPrefJsonFile === 0){ + reject('Oops!, you didn\'t specify any starting document'); + } + var currentdb = $injector.get('json' + userPrefJsonFile); + var item = {}; + var dbobj = breakdown_components(currentdb); + item.filename = dbobj.db; + item.json = userPrefJsonFile; + dbitems.push(item); + resolve(); + }); + }); + } + + function getNumberOfJsonDatabases() { + if (numOfJsonDatabases >= 1) { + return numOfJsonDatabases; + } else { + for (var x = 0; x >= 0; x++) { + if ($injector.has('json' + (x + 1))) { + numOfJsonDatabases++; + } + else { + break; + } + + } + return numOfJsonDatabases; + } + } + + var still_running = false; + var current_iteration = 1; + + function initialiseAll() { + return $q(function (resolve, reject) { + initialiseDbList() + .then(function () { + + function iterate_me() { + if ($injector.has('json' + dbitems[current_iteration - 1].json)) { + var setting = $injector.get('json' + dbitems[current_iteration - 1].json); + + console.log('number = ' + current_iteration); + var set = angular.fromJson(setting); + still_running = true; + initiateDb(set) + .then(function () { + //lokidbs.push(angular.copy(db)); + if (!doesDBAlreadyExistInArray(db.filename)) { + lokidbs.push(angular.copy(db)); + } + still_running = false; + if (current_iteration === (dbitems.length)) { + resolve(); + } else { + current_iteration++; + iterate_me(); + return; + } + }); + } + } + iterate_me(); + }, function(data){ + reject(data); + }); + }); + } + + function doesDBAlreadyExistInArray(dbname) { + var answer = false; + for (var x = 0; x < lokidbs.length; x++) { + if (lokidbs[x].filename === dbname) { + answer = true; + } + } + return answer; + } + + function getIndexOfDbItem(dbname) { + var answer = -1; + for (var x = 0; x < numOfJsonDatabases; x++) { + if (dbitems[x].filename === dbname) { + answer = x; + } + } + return answer; + } + + function loadDb(databaseName) { + return $q(function (resolve, reject) { + for (var x = 0; x < lokidbs.length; x++) { + if (lokidbs[x].filename === databaseName) { + db = lokidbs[x]; + resolve(); + } + } + }); + } + + + + function initiateDb(database) { + return $q(function (resolve, reject) { + var dbobj = breakdown_components(database); + var db_does_exist = false; + if (dbExists(database[dbobj.db])) { + db_does_exist = true; + } + db = new loki(database[dbobj.db], { + autoload: true, + autoloadCallback: loadHandler, //loadHandler, //for some reason this has to be called like this + autosave: true, + autosaveInterval: 10000 + }); + + function loadHandler() { + if (db_does_exist) { + + resolve(); + } else { + var dbobj = breakdown_components(database); + for(var x = 0; x < dbobj.coll_array.length; x++){ + var items = db.addCollection(database[dbobj.coll_array[x].coll]); + items.insert(database[dbobj.coll_array[x].docs]); + } + db.save(); + resolve(); + } + } + }); + } + function breakdown_components(db_obj){ + var iterate = 1; + var db_id = ''; + var coll_id = ""; + var doc_id = ""; + var collections = []; + for(var i in db_obj){ + if (iterate > 1){ + if(isEven(iterate)){ + coll_id = i; + } + else{ + doc_id = i; + var tempobj = {coll: coll_id, docs: doc_id}; + collections.push(tempobj); + } + } + else { + db_id = i; + } + iterate ++; + } + + var dataobj = {db: db_id, coll_array: collections}; + return dataobj; + } + function isEven(n) { + return n % 2 === 0; + } + function isOdd(n) { + return Boolean(n % 2); + } + } + return module; +})); diff --git a/node_modules/lokijs/src/loki-crypted-file-adapter.js b/node_modules/lokijs/src/loki-crypted-file-adapter.js new file mode 100644 index 00000000..e5795ceb --- /dev/null +++ b/node_modules/lokijs/src/loki-crypted-file-adapter.js @@ -0,0 +1,197 @@ +/** + * @file lokiCryptedFileAdapter.js + * @author Hans Klunder + */ + + /* + * The default Loki File adapter uses plain text JSON files. This adapter crypts the database string and wraps the result + * in a JSON including enough info to be able to decrypt it (except for the 'secret' of course !) + * + * The idea is that the 'secret' does not reside in your source code but is supplied by some other source (e.g. the user in node-webkit) + * + * The idea + encrypt/decrypt routines are borrowed from https://github.com/mmoulton/krypt/blob/develop/lib/krypt.js + * not using the krypt module to avoid third party dependencies + */ + + +/** + * require libs + * @ignore +*/ +var fs = require('fs'); +var cryptoLib = require('crypto'); +var isError = require('util').isError; + +/* + * sensible defaults + */ +var CIPHER = 'aes-256-cbc', + KEY_DERIVATION = 'pbkdf2', + KEY_LENGTH = 256, + ITERATIONS = 64000; + +/** + * encrypt() - encrypt a string + * @private + * @param {string} input - the serialized JSON object to decrypt. + * @param {string} secret - the secret to use for encryption + */ +function encrypt(input, secret) { + if (!secret) { + return new Error('A \'secret\' is required to encrypt'); + } + + + var salt = cryptoLib.randomBytes(KEY_LENGTH / 8), + iv = cryptoLib.randomBytes(16); + + try { + + var key = cryptoLib.pbkdf2Sync(secret, salt, ITERATIONS, KEY_LENGTH / 8, 'sha1'), + cipher = cryptoLib.createCipheriv(CIPHER, key, iv); + + var encryptedValue = cipher.update(input, 'utf8', 'base64'); + encryptedValue += cipher.final('base64'); + + var result = { + cipher: CIPHER, + keyDerivation: KEY_DERIVATION, + keyLength: KEY_LENGTH, + iterations: ITERATIONS, + iv: iv.toString('base64'), + salt: salt.toString('base64'), + value: encryptedValue + }; + return result; + + } catch (err) { + return new Error('Unable to encrypt value due to: ' + err); + } +} + +/** + * decrypt() - Decrypt a serialized JSON object + * @private + * @param {string} input - the serialized JSON object to decrypt. + * @param {string} secret - the secret to use for decryption + */ +function decrypt(input, secret) { + // Ensure we have something to decrypt + if (!input) { + return new Error('You must provide a value to decrypt'); + } + // Ensure we have the secret used to encrypt this value + if (!secret) { + return new Error('A \'secret\' is required to decrypt'); + } + + // turn string into an object + try { + input = JSON.parse(input); + } catch (err) { + return new Error('Unable to parse string input as JSON'); + } + + // Ensure our input is a valid object with 'iv', 'salt', and 'value' + if (!input.iv || !input.salt || !input.value) { + return new Error('Input must be a valid object with \'iv\', \'salt\', and \'value\' properties'); + } + + var salt = new Buffer(input.salt, 'base64'), + iv = new Buffer(input.iv, 'base64'), + keyLength = input.keyLength, + iterations = input.iterations; + + try { + + var key = cryptoLib.pbkdf2Sync(secret, salt, iterations, keyLength / 8, 'sha1'), + decipher = cryptoLib.createDecipheriv(CIPHER, key, iv); + + var decryptedValue = decipher.update(input.value, 'base64', 'utf8'); + decryptedValue += decipher.final('utf8'); + + return decryptedValue; + + } catch (err) { + return new Error('Unable to decrypt value due to: ' + err); + } +} + +/** + * The constructor is automatically called on `require` , see examples below + * @constructor + */ +function lokiCryptedFileAdapter() {} + +/** + * setSecret() - set the secret to be used during encryption and decryption + * + * @param {string} secret - the secret to be used + */ +lokiCryptedFileAdapter.prototype.setSecret = function setSecret(secret) { + this.secret = secret; +}; + +/** + * loadDatabase() - Retrieves a serialized db string from the catalog. + * + * @example + // LOAD + var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); + cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user + var db = new loki('test.crypted', { adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' + db.loadDatabase(function(result) { + console.log('done'); + }); + * + * @param {string} dbname - the name of the database to retrieve. + * @param {function} callback - callback should accept string param containing serialized db string. + */ +lokiCryptedFileAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) { + var secret = this.secret; + var cFun = callback || console.log; + + fs.readFile(dbname,'utf8',function(err,data){ + var decrypted = err || decrypt(data, secret); + cFun(decrypted); + }); +}; + +/** + * + @example + // SAVE : will save database in 'test.crypted' + var cryptedFileAdapter = require('./lokiCryptedFileAdapter'); + cryptedFileAdapter.setSecret('mySecret'); // you should change 'mySecret' to something supplied by the user + var loki=require('lokijs'); + var db = new loki('test.crypted',{ adapter: cryptedFileAdapter }); //you can use any name, not just '*.crypted' + var coll = db.addCollection('testColl'); + coll.insert({test: 'val'}); + db.saveDatabase(); // could pass callback if needed for async complete + + @example + // if you have the krypt module installed you can use: + krypt --decrypt test.crypted --secret mySecret + to view the contents of the database + + * saveDatabase() - Saves a serialized db to the catalog. + * + * @param {string} dbname - the name to give the serialized database within the catalog. + * @param {string} dbstring - the serialized db string to save. + * @param {function} callback - (Optional) callback passed obj.success with true or false + */ +lokiCryptedFileAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) { + var cFun = callback || function (){}; + var encrypted = encrypt(dbstring, this.secret); + if (! isError(encrypted)){ + fs.writeFile(dbname, + JSON.stringify(encrypted, null, ' '), + 'utf8',cFun); + } + else { // Error ! + cFun(encrypted); + } +}; + +module.exports = new lokiCryptedFileAdapter(); +exports.lokiCryptedFileAdapter = lokiCryptedFileAdapter; diff --git a/node_modules/lokijs/src/loki-fs-structured-adapter.js b/node_modules/lokijs/src/loki-fs-structured-adapter.js new file mode 100644 index 00000000..5b2c13e0 --- /dev/null +++ b/node_modules/lokijs/src/loki-fs-structured-adapter.js @@ -0,0 +1,263 @@ + +/* + Loki (node) fs structured Adapter (need to require this script to instance and use it). + + This adapter will save database container and each collection to separate files and + save collection only if it is dirty. It is also designed to use a destructured serialization + method intended to lower the memory overhead of json serialization. + + This adapter utilizes ES6 generator/iterator functionality to stream output and + uses node linereader module to stream input. This should lower memory pressure + in addition to individual object serializations rather than loki's default deep object + serialization. +*/ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD + define([], factory); + } else if (typeof exports === 'object') { + // Node, CommonJS-like + module.exports = factory(); + } else { + // Browser globals (root is window) + root.LokiFsStructuredAdapter = factory(); + } +}(this, function () { + return (function() { + + const fs = require('fs'); + const readline = require('readline'); + const stream = require('stream'); + + /** + * Loki structured (node) filesystem adapter class. + * This class fulfills the loki 'reference' abstract adapter interface which can be applied to other storage methods. + * + * @constructor LokiFsStructuredAdapter + * + */ + function LokiFsStructuredAdapter() + { + this.mode = "reference"; + this.dbref = null; + this.dirtyPartitions = []; + } + + /** + * Generator for constructing lines for file streaming output of db container or collection. + * + * @param {object=} options - output format options for use externally to loki + * @param {int=} options.partition - can be used to only output an individual collection or db (-1) + * + * @returns {string|array} A custom, restructured aggregation of independent serializations. + * @memberof LokiFsStructuredAdapter + */ + LokiFsStructuredAdapter.prototype.generateDestructured = function*(options) { + var idx, sidx; + var dbcopy; + + options = options || {}; + + if (!options.hasOwnProperty("partition")) { + options.partition = -1; + } + + // if partition is -1 we will return database container with no data + if (options.partition === -1) { + // instantiate lightweight clone and remove its collection data + dbcopy = this.dbref.copy(); + + for(idx=0; idx < dbcopy.collections.length; idx++) { + dbcopy.collections[idx].data = []; + } + + yield dbcopy.serialize({ + serializationMethod: "normal" + }); + + return; + } + + // 'partitioned' along with 'partition' of 0 or greater is a request for single collection serialization + if (options.partition >= 0) { + var doccount, + docidx; + + // dbref collections have all data so work against that + doccount = this.dbref.collections[options.partition].data.length; + + for(docidx=0; docidx 0) { + self.loadNextCollection(dbname, 0, function() { + callback(self.dbref); + }); + } + }); + } + else { + // file does not exist, so callback with null + callback(null); + } + }); + }; + + /** + * Recursive function to chain loading of each collection one at a time. + * If at some point i can determine how to make async driven generator, this may be converted to generator. + * + * @param {string} dbname - the name to give the serialized database within the catalog. + * @param {int} collectionIndex - the ordinal position of the collection to load. + * @param {function} callback - callback to pass to next invocation or to call when done + * @memberof LokiFsStructuredAdapter + */ + LokiFsStructuredAdapter.prototype.loadNextCollection = function(dbname, collectionIndex, callback) { + var instream = fs.createReadStream(dbname + "." + collectionIndex); + var outstream = new stream(); + var rl = readline.createInterface(instream, outstream); + var self=this, + obj; + + rl.on('line', function (line) { + if (line !== "") { + obj = JSON.parse(line); + self.dbref.collections[collectionIndex].data.push(obj); + } + }); + + rl.on('close', function (line) { + instream = null; + outstream = null; + rl = null; + obj = null; + + // if there are more collections, load the next one + if (++collectionIndex < self.dbref.collections.length) { + self.loadNextCollection(dbname, collectionIndex, callback); + } + // otherwise we are done, callback to loadDatabase so it can return the new db object representation. + else { + callback(); + } + }); + }; + + /** + * Generator for yielding sequence of dirty partition indices to iterate. + * + * @memberof LokiFsStructuredAdapter + */ + LokiFsStructuredAdapter.prototype.getPartition = function*() { + var idx, + clen = this.dbref.collections.length; + + // since database container (partition -1) doesn't have dirty flag at db level, always save + yield -1; + + // yield list of dirty partitions for iterateration + for(idx=0; idx { + return new Promise((resolve, reject) => { + fs.lstat(datadir, (err, stats) => { + if (err) { + reject({ + message: 'Dir does not exist' + }); + } + resolve(stats); + }); + }); + }; + + const saveRecord = (coll, obj, dir) => { + console.log(`File is ${dir}/${coll}/${obj.$loki}.json`); + fs.writeFile(`${dir}/${coll}/${obj.$loki}.json`, JSON.stringify(obj), { + encoding: 'utf8' + }, (err) => { + if (err) { + console.log('Document save failed.'); + throw err; + } + console.log('Document saved correctly'); + }); + }; + + const iterateFolders = (db, dir) => { + console.log(`Colls: ${db.listCollections().length}`); + + console.log(`Changes: ${db.generateChangesNotification().length}`); + db.generateChangesNotification().forEach(change => { + saveRecord(change.name, change.obj, dir); + }); + }; + + class LokiIncrementalAdapter { + constructor(options) { + const config = options || { + journaling: false, + format: 'json' + }; + this.mode = 'reference'; + this.journaling = config.journaling; + this.format = config.format; + } + + checkAvailability() { + if (typeof fs !== 'undefined' && fs) return true; + return false; + } + + exportDatabase(dir, dbref, callback) { + console.log('Saving with incremental adapter'); + + console.log('Database dir is ' + dir); + const promise = accessDataDir(dir); + console.log(promise); + promise.then(() => { + console.log('iterating folders...'); + iterateFolders(dbref, dir); + }); + promise.catch((err) => { + console.log(err); + }); + if (callback) { + callback(); + } + } + + loadDatabase(dbname, callback) { + console.log(this, dbname, callback); + } + } + + return LokiIncrementalAdapter; + + }()); +})); diff --git a/node_modules/lokijs/src/loki-indexed-adapter.js b/node_modules/lokijs/src/loki-indexed-adapter.js new file mode 100644 index 00000000..b0c94eb1 --- /dev/null +++ b/node_modules/lokijs/src/loki-indexed-adapter.js @@ -0,0 +1,617 @@ +/* + Loki IndexedDb Adapter (need to include this script to use it) + + Console Usage can be used for management/diagnostic, here are a few examples : + adapter.getDatabaseList(); // with no callback passed, this method will log results to console + adapter.saveDatabase('UserDatabase', JSON.stringify(myDb)); + adapter.loadDatabase('UserDatabase'); // will log the serialized db to console + adapter.deleteDatabase('UserDatabase'); +*/ + +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD + define([], factory); + } else if (typeof exports === 'object') { + // Node, CommonJS-like + module.exports = factory(); + } else { + // Browser globals (root is window) + root.LokiIndexedAdapter = factory(); + } +}(this, function () { + return (function() { + + /** + * Loki persistence adapter class for indexedDb. + * This class fulfills abstract adapter interface which can be applied to other storage methods. + * Utilizes the included LokiCatalog app/key/value database for actual database persistence. + * Indexeddb is highly async, but this adapter has been made 'console-friendly' as well. + * Anywhere a callback is omitted, it should return results (if applicable) to console. + * IndexedDb storage is provided per-domain, so we implement app/key/value database to + * allow separate contexts for separate apps within a domain. + * + * @example + * var idbAdapter = new LokiIndexedAdapter('finance'); + * + * @constructor LokiIndexedAdapter + * + * @param {string} appname - (Optional) Application name context can be used to distinguish subdomains, 'loki' by default + */ + function LokiIndexedAdapter(appname) + { + this.app = 'loki'; + + if (typeof (appname) !== 'undefined') + { + this.app = appname; + } + + // keep reference to catalog class for base AKV operations + this.catalog = null; + + if (!this.checkAvailability()) { + throw new Error('indexedDB does not seem to be supported for your environment'); + } + } + + /** + * Used to check if adapter is available + * + * @returns {boolean} true if indexeddb is available, false if not. + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.checkAvailability = function() + { + if (typeof indexedDB !== 'undefined' && indexedDB) return true; + + return false; + }; + + /** + * Retrieves a serialized db string from the catalog. + * + * @example + * // LOAD + * var idbAdapter = new LokiIndexedAdapter('finance'); + * var db = new loki('test', { adapter: idbAdapter }); + * db.loadDatabase(function(result) { + * console.log('done'); + * }); + * + * @param {string} dbname - the name of the database to retrieve. + * @param {function} callback - callback should accept string param containing serialized db string. + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.loadDatabase = function(dbname, callback) + { + var appName = this.app; + var adapter = this; + + // lazy open/create db reference so dont -need- callback in constructor + if (this.catalog === null || this.catalog.db === null) { + this.catalog = new LokiCatalog(function(cat) { + adapter.catalog = cat; + + adapter.loadDatabase(dbname, callback); + }); + + return; + } + + // lookup up db string in AKV db + this.catalog.getAppKey(appName, dbname, function(result) { + if (typeof (callback) === 'function') { + if (result.id === 0) { + callback(null); + return; + } + callback(result.val); + } + else { + // support console use of api + console.log(result.val); + } + }); + }; + + // alias + LokiIndexedAdapter.prototype.loadKey = LokiIndexedAdapter.prototype.loadDatabase; + + /** + * Saves a serialized db to the catalog. + * + * @example + * // SAVE : will save App/Key/Val as 'finance'/'test'/{serializedDb} + * var idbAdapter = new LokiIndexedAdapter('finance'); + * var db = new loki('test', { adapter: idbAdapter }); + * var coll = db.addCollection('testColl'); + * coll.insert({test: 'val'}); + * db.saveDatabase(); // could pass callback if needed for async complete + * + * @param {string} dbname - the name to give the serialized database within the catalog. + * @param {string} dbstring - the serialized db string to save. + * @param {function} callback - (Optional) callback passed obj.success with true or false + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.saveDatabase = function(dbname, dbstring, callback) + { + var appName = this.app; + var adapter = this; + + function saveCallback(result) { + if (result && result.success === true) { + callback(null); + } + else { + callback(new Error("Error saving database")); + } + } + + // lazy open/create db reference so dont -need- callback in constructor + if (this.catalog === null || this.catalog.db === null) { + this.catalog = new LokiCatalog(function(cat) { + adapter.catalog = cat; + + // now that catalog has been initialized, set (add/update) the AKV entry + cat.setAppKey(appName, dbname, dbstring, saveCallback); + }); + + return; + } + + // set (add/update) entry to AKV database + this.catalog.setAppKey(appName, dbname, dbstring, saveCallback); + }; + + // alias + LokiIndexedAdapter.prototype.saveKey = LokiIndexedAdapter.prototype.saveDatabase; + + /** + * Deletes a serialized db from the catalog. + * + * @example + * // DELETE DATABASE + * // delete 'finance'/'test' value from catalog + * idbAdapter.deleteDatabase('test', function { + * // database deleted + * }); + * + * @param {string} dbname - the name of the database to delete from the catalog. + * @param {function=} callback - (Optional) executed on database delete + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.deleteDatabase = function(dbname, callback) + { + var appName = this.app; + var adapter = this; + + // lazy open/create db reference and pass callback ahead + if (this.catalog === null || this.catalog.db === null) { + this.catalog = new LokiCatalog(function(cat) { + adapter.catalog = cat; + + adapter.deleteDatabase(dbname, callback); + }); + + return; + } + + // catalog was already initialized, so just lookup object and delete by id + this.catalog.getAppKey(appName, dbname, function(result) { + var id = result.id; + + if (id !== 0) { + adapter.catalog.deleteAppKey(id, callback); + } else if (typeof (callback) === 'function') { + callback({ success: true }); + } + }); + }; + + // alias + LokiIndexedAdapter.prototype.deleteKey = LokiIndexedAdapter.prototype.deleteDatabase; + + /** + * Removes all database partitions and pages with the base filename passed in. + * This utility method does not (yet) guarantee async deletions will be completed before returning + * + * @param {string} dbname - the base filename which container, partitions, or pages are derived + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.deleteDatabasePartitions = function(dbname) { + var self=this; + this.getDatabaseList(function(result) { + result.forEach(function(str) { + if (str.startsWith(dbname)) { + self.deleteDatabase(str); + } + }); + }); + }; + + /** + * Retrieves object array of catalog entries for current app. + * + * @example + * idbAdapter.getDatabaseList(function(result) { + * // result is array of string names for that appcontext ('finance') + * result.forEach(function(str) { + * console.log(str); + * }); + * }); + * + * @param {function} callback - should accept array of database names in the catalog for current app. + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.getDatabaseList = function(callback) + { + var appName = this.app; + var adapter = this; + + // lazy open/create db reference so dont -need- callback in constructor + if (this.catalog === null || this.catalog.db === null) { + this.catalog = new LokiCatalog(function(cat) { + adapter.catalog = cat; + + adapter.getDatabaseList(callback); + }); + + return; + } + + // catalog already initialized + // get all keys for current appName, and transpose results so just string array + this.catalog.getAppKeys(appName, function(results) { + var names = []; + + for(var idx = 0; idx < results.length; idx++) { + names.push(results[idx].key); + } + + if (typeof (callback) === 'function') { + callback(names); + } + else { + names.forEach(function(obj) { + console.log(obj); + }); + } + }); + }; + + // alias + LokiIndexedAdapter.prototype.getKeyList = LokiIndexedAdapter.prototype.getDatabaseList; + + /** + * Allows retrieval of list of all keys in catalog along with size + * + * @param {function} callback - (Optional) callback to accept result array. + * @memberof LokiIndexedAdapter + */ + LokiIndexedAdapter.prototype.getCatalogSummary = function(callback) + { + var appName = this.app; + var adapter = this; + + // lazy open/create db reference + if (this.catalog === null || this.catalog.db === null) { + this.catalog = new LokiCatalog(function(cat) { + adapter.catalog = cat; + + adapter.getCatalogSummary(callback); + }); + + return; + } + + // catalog already initialized + // get all keys for current appName, and transpose results so just string array + this.catalog.getAllKeys(function(results) { + var entries = []; + var obj, + size, + oapp, + okey, + oval; + + for(var idx = 0; idx < results.length; idx++) { + obj = results[idx]; + oapp = obj.app || ''; + okey = obj.key || ''; + oval = obj.val || ''; + + // app and key are composited into an appkey column so we will mult by 2 + size = oapp.length * 2 + okey.length * 2 + oval.length + 1; + + entries.push({ "app": obj.app, "key": obj.key, "size": size }); + } + + if (typeof (callback) === 'function') { + callback(entries); + } + else { + entries.forEach(function(obj) { + console.log(obj); + }); + } + }); + }; + + /** + * LokiCatalog - underlying App/Key/Value catalog persistence + * This non-interface class implements the actual persistence. + * Used by the IndexedAdapter class. + */ + function LokiCatalog(callback) + { + this.db = null; + this.initializeLokiCatalog(callback); + } + + LokiCatalog.prototype.initializeLokiCatalog = function(callback) { + var openRequest = indexedDB.open('LokiCatalog', 1); + var cat = this; + + // If database doesn't exist yet or its version is lower than our version specified above (2nd param in line above) + openRequest.onupgradeneeded = function(e) { + var thisDB = e.target.result; + if (thisDB.objectStoreNames.contains('LokiAKV')) { + thisDB.deleteObjectStore('LokiAKV'); + } + + if(!thisDB.objectStoreNames.contains('LokiAKV')) { + var objectStore = thisDB.createObjectStore('LokiAKV', { keyPath: 'id', autoIncrement:true }); + objectStore.createIndex('app', 'app', {unique:false}); + objectStore.createIndex('key', 'key', {unique:false}); + // hack to simulate composite key since overhead is low (main size should be in val field) + // user (me) required to duplicate the app and key into comma delimited appkey field off object + // This will allow retrieving single record with that composite key as well as + // still supporting opening cursors on app or key alone + objectStore.createIndex('appkey', 'appkey', {unique:true}); + } + }; + + openRequest.onsuccess = function(e) { + cat.db = e.target.result; + + if (typeof (callback) === 'function') callback(cat); + }; + + openRequest.onerror = function(e) { + throw e; + }; + }; + + LokiCatalog.prototype.getAppKey = function(app, key, callback) { + var transaction = this.db.transaction(['LokiAKV'], 'readonly'); + var store = transaction.objectStore('LokiAKV'); + var index = store.index('appkey'); + var appkey = app + "," + key; + var request = index.get(appkey); + + request.onsuccess = (function(usercallback) { + return function(e) { + var lres = e.target.result; + + if (lres === null || typeof(lres) === 'undefined') { + lres = { + id: 0, + success: false + }; + } + + if (typeof(usercallback) === 'function') { + usercallback(lres); + } + else { + console.log(lres); + } + }; + })(callback); + + request.onerror = (function(usercallback) { + return function(e) { + if (typeof(usercallback) === 'function') { + usercallback({ id: 0, success: false }); + } + else { + throw e; + } + }; + })(callback); + }; + + LokiCatalog.prototype.getAppKeyById = function (id, callback, data) { + var transaction = this.db.transaction(['LokiAKV'], 'readonly'); + var store = transaction.objectStore('LokiAKV'); + var request = store.get(id); + + request.onsuccess = (function(data, usercallback){ + return function(e) { + if (typeof(usercallback) === 'function') { + usercallback(e.target.result, data); + } + else { + console.log(e.target.result); + } + }; + })(data, callback); + }; + + LokiCatalog.prototype.setAppKey = function (app, key, val, callback) { + var transaction = this.db.transaction(['LokiAKV'], 'readwrite'); + var store = transaction.objectStore('LokiAKV'); + var index = store.index('appkey'); + var appkey = app + "," + key; + var request = index.get(appkey); + + // first try to retrieve an existing object by that key + // need to do this because to update an object you need to have id in object, otherwise it will append id with new autocounter and clash the unique index appkey + request.onsuccess = function(e) { + var res = e.target.result; + + if (res === null || res === undefined) { + res = { + app:app, + key:key, + appkey: app + ',' + key, + val:val + }; + } + else { + res.val = val; + } + + var requestPut = store.put(res); + + requestPut.onerror = (function(usercallback) { + return function(e) { + if (typeof(usercallback) === 'function') { + usercallback({ success: false }); + } + else { + console.error('LokiCatalog.setAppKey (set) onerror'); + console.error(request.error); + } + }; + + })(callback); + + requestPut.onsuccess = (function(usercallback) { + return function(e) { + if (typeof(usercallback) === 'function') { + usercallback({ success: true }); + } + }; + })(callback); + }; + + request.onerror = (function(usercallback) { + return function(e) { + if (typeof(usercallback) === 'function') { + usercallback({ success: false }); + } + else { + console.error('LokiCatalog.setAppKey (get) onerror'); + console.error(request.error); + } + }; + })(callback); + }; + + LokiCatalog.prototype.deleteAppKey = function (id, callback) { + var transaction = this.db.transaction(['LokiAKV'], 'readwrite'); + var store = transaction.objectStore('LokiAKV'); + var request = store.delete(id); + + request.onsuccess = (function(usercallback) { + return function(evt) { + if (typeof(usercallback) === 'function') usercallback({ success: true }); + }; + })(callback); + + request.onerror = (function(usercallback) { + return function(evt) { + if (typeof(usercallback) === 'function') { + usercallback({ success: false }); + } + else { + console.error('LokiCatalog.deleteAppKey raised onerror'); + console.error(request.error); + } + }; + })(callback); + }; + + LokiCatalog.prototype.getAppKeys = function(app, callback) { + var transaction = this.db.transaction(['LokiAKV'], 'readonly'); + var store = transaction.objectStore('LokiAKV'); + var index = store.index('app'); + + // We want cursor to all values matching our (single) app param + var singleKeyRange = IDBKeyRange.only(app); + + // To use one of the key ranges, pass it in as the first argument of openCursor()/openKeyCursor() + var cursor = index.openCursor(singleKeyRange); + + // cursor internally, pushing results into this.data[] and return + // this.data[] when done (similar to service) + var localdata = []; + + cursor.onsuccess = (function(data, callback) { + return function(e) { + var cursor = e.target.result; + if (cursor) { + var currObject = cursor.value; + + data.push(currObject); + + cursor.continue(); + } + else { + if (typeof(callback) === 'function') { + callback(data); + } + else { + console.log(data); + } + } + }; + })(localdata, callback); + + cursor.onerror = (function(usercallback) { + return function(e) { + if (typeof(usercallback) === 'function') { + usercallback(null); + } + else { + console.error('LokiCatalog.getAppKeys raised onerror'); + console.error(e); + } + }; + })(callback); + + }; + + // Hide 'cursoring' and return array of { id: id, key: key } + LokiCatalog.prototype.getAllKeys = function (callback) { + var transaction = this.db.transaction(['LokiAKV'], 'readonly'); + var store = transaction.objectStore('LokiAKV'); + var cursor = store.openCursor(); + + var localdata = []; + + cursor.onsuccess = (function(data, callback) { + return function(e) { + var cursor = e.target.result; + if (cursor) { + var currObject = cursor.value; + + data.push(currObject); + + cursor.continue(); + } + else { + if (typeof(callback) === 'function') { + callback(data); + } + else { + console.log(data); + } + } + }; + })(localdata, callback); + + cursor.onerror = (function(usercallback) { + return function(e) { + if (typeof(usercallback) === 'function') usercallback(null); + }; + })(callback); + + }; + + return LokiIndexedAdapter; + + }()); +})); diff --git a/node_modules/lokijs/src/loki-nativescript-adapter.js b/node_modules/lokijs/src/loki-nativescript-adapter.js new file mode 100644 index 00000000..a885ff69 --- /dev/null +++ b/node_modules/lokijs/src/loki-nativescript-adapter.js @@ -0,0 +1,61 @@ + /** + * LokiNativescriptAdapter + * @author Stefano Falda + * + * Lokijs adapter for nativescript framework (http://www.nativescript.org) + * + * The db file is created in the app documents folder. + + * How to use: + * Just create a new loki db and your ready to go: + * + * let db = new loki('loki.json',{autosave:true}); + * + */ + +function LokiNativescriptAdapter() { + this.fs = require("file-system"); + } + +LokiNativescriptAdapter.prototype.loadDatabase = function(dbname, callback){ + var documents = this.fs.knownFolders.documents(); + var myFile = documents.getFile(dbname); + //Read from filesystem + myFile.readText() + .then(function (content) { + //The file is empty or missing + if (content===""){ + callback(new Error("DB file does not exist")); + } else { + callback(content); + } + }, function (error) { + console.log("Error opening db "+dbname+": "+ error); + callback(new Error(error)); + }); +}; + +LokiNativescriptAdapter.prototype.saveDatabase = function(dbname, serialized, callback){ + var documents = this.fs.knownFolders.documents(); + var myFile = documents.getFile(dbname); + myFile.writeText(serialized) + .then(function () { + callback(); + }, function (error) { + console.log("Error saving db "+dbname+": "+ error); + }); + +}; + +LokiNativescriptAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) { + var documents = this.fs.knownFolders.documents(); + var file = documents.getFile(dbname); + file.remove() + .then(function (result) { + callback(); + }, function (error) { + callback(error); + }); + }; + +module.exports = LokiNativescriptAdapter; \ No newline at end of file diff --git a/node_modules/lokijs/src/lokijs.js b/node_modules/lokijs/src/lokijs.js new file mode 100644 index 00000000..357c4c4e --- /dev/null +++ b/node_modules/lokijs/src/lokijs.js @@ -0,0 +1,7358 @@ +/** + * LokiJS + * @author Joe Minichino + * + * A lightweight document oriented javascript database + */ +(function (root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD + define([], factory); + } else if (typeof exports === 'object') { + // CommonJS + module.exports = factory(); + } else { + // Browser globals + root.loki = factory(); + } +}(this, function () { + + return (function () { + 'use strict'; + + var hasOwnProperty = Object.prototype.hasOwnProperty; + + var Utils = { + copyProperties: function (src, dest) { + var prop; + for (prop in src) { + dest[prop] = src[prop]; + } + }, + // used to recursively scan hierarchical transform step object for param substitution + resolveTransformObject: function (subObj, params, depth) { + var prop, + pname; + + if (typeof depth !== 'number') { + depth = 0; + } + + if (++depth >= 10) return subObj; + + for (prop in subObj) { + if (typeof subObj[prop] === 'string' && subObj[prop].indexOf("[%lktxp]") === 0) { + pname = subObj[prop].substring(8); + if (params.hasOwnProperty(pname)) { + subObj[prop] = params[pname]; + } + } else if (typeof subObj[prop] === "object") { + subObj[prop] = Utils.resolveTransformObject(subObj[prop], params, depth); + } + } + + return subObj; + }, + // top level utility to resolve an entire (single) transform (array of steps) for parameter substitution + resolveTransformParams: function (transform, params) { + var idx, + clonedStep, + resolvedTransform = []; + + if (typeof params === 'undefined') return transform; + + // iterate all steps in the transform array + for (idx = 0; idx < transform.length; idx++) { + // clone transform so our scan/replace can operate directly on cloned transform + clonedStep = clone(transform[idx], "shallow-recurse-objects"); + resolvedTransform.push(Utils.resolveTransformObject(clonedStep, params)); + } + + return resolvedTransform; + } + }; + + // wrapping in object to expose to default export for potential user override. + // warning: overriding these methods will override behavior for all loki db instances in memory. + // warning: if you use binary indices these comparators should be the same for all inserts/updates/removes. + var Comparators = { + aeq: aeqHelper, + lt: ltHelper, + gt: gtHelper + }; + + /** Helper function for determining 'loki' abstract equality which is a little more abstract than == + * aeqHelper(5, '5') === true + * aeqHelper(5.0, '5') === true + * aeqHelper(new Date("1/1/2011"), new Date("1/1/2011")) === true + * aeqHelper({a:1}, {z:4}) === true (all objects sorted equally) + * aeqHelper([1, 2, 3], [1, 3]) === false + * aeqHelper([1, 2, 3], [1, 2, 3]) === true + * aeqHelper(undefined, null) === true + */ + function aeqHelper(prop1, prop2) { + var cv1, cv2, t1, t2; + + if (prop1 === prop2) return true; + + // 'falsy' and Boolean handling + if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) { + // dates and NaN conditions (typed dates before serialization) + switch (prop1) { + case undefined: t1 = 1; break; + case null: t1 = 1; break; + case false: t1 = 3; break; + case true: t1 = 4; break; + case "": t1 = 5; break; + default: t1 = (prop1 === prop1)?9:0; break; + } + + switch (prop2) { + case undefined: t2 = 1; break; + case null: t2 = 1; break; + case false: t2 = 3; break; + case true: t2 = 4; break; + case "": t2 = 5; break; + default: t2 = (prop2 === prop2)?9:0; break; + } + + // one or both is edge case + if (t1 !== 9 || t2 !== 9) { + return (t1===t2); + } + } + + // Handle 'Number-like' comparisons + cv1 = Number(prop1); + cv2 = Number(prop2); + + // if one or both are 'number-like'... + if (cv1 === cv1 || cv2 === cv2) { + return (cv1 === cv2); + } + + // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare + cv1 = prop1.toString(); + cv2 = prop2.toString(); + + return (cv1 == cv2); + } + + /** Helper function for determining 'less-than' conditions for ops, sorting, and binary indices. + * In the future we might want $lt and $gt ops to use their own functionality/helper. + * Since binary indices on a property might need to index [12, NaN, new Date(), Infinity], we + * need this function (as well as gtHelper) to always ensure one value is LT, GT, or EQ to another. + */ + function ltHelper(prop1, prop2, equal) { + var cv1, cv2, t1, t2; + + // if one of the params is falsy or strictly true or not equal to itself + // 0, 0.0, "", NaN, null, undefined, not defined, false, true + if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) { + switch (prop1) { + case undefined: t1 = 1; break; + case null: t1 = 1; break; + case false: t1 = 3; break; + case true: t1 = 4; break; + case "": t1 = 5; break; + // if strict equal probably 0 so sort higher, otherwise probably NaN so sort lower than even null + default: t1 = (prop1 === prop1)?9:0; break; + } + + switch (prop2) { + case undefined: t2 = 1; break; + case null: t2 = 1; break; + case false: t2 = 3; break; + case true: t2 = 4; break; + case "": t2 = 5; break; + default: t2 = (prop2 === prop2)?9:0; break; + } + + // one or both is edge case + if (t1 !== 9 || t2 !== 9) { + return (t1===t2)?equal:(t1 cv2) return false; + return equal; + } + + if (cv1 === cv1 && cv2 !== cv2) { + return true; + } + + if (cv2 === cv2 && cv1 !== cv1) { + return false; + } + + if (prop1 < prop2) return true; + if (prop1 > prop2) return false; + if (prop1 == prop2) return equal; + + // not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare + cv1 = prop1.toString(); + cv2 = prop2.toString(); + + if (cv1 < cv2) { + return true; + } + + if (cv1 == cv2) { + return equal; + } + + return false; + } + + function gtHelper(prop1, prop2, equal) { + var cv1, cv2, t1, t2; + + // 'falsy' and Boolean handling + if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) { + switch (prop1) { + case undefined: t1 = 1; break; + case null: t1 = 1; break; + case false: t1 = 3; break; + case true: t1 = 4; break; + case "": t1 = 5; break; + // NaN 0 + default: t1 = (prop1 === prop1)?9:0; break; + } + + switch (prop2) { + case undefined: t2 = 1; break; + case null: t2 = 1; break; + case false: t2 = 3; break; + case true: t2 = 4; break; + case "": t2 = 5; break; + default: t2 = (prop2 === prop2)?9:0; break; + } + + // one or both is edge case + if (t1 !== 9 || t2 !== 9) { + return (t1===t2)?equal:(t1>t2); + } + } + + // if both are numbers (string encoded or not), compare as numbers + cv1 = Number(prop1); + cv2 = Number(prop2); + if (cv1 === cv1 && cv2 === cv2) { + if (cv1 > cv2) return true; + if (cv1 < cv2) return false; + return equal; + } + + if (cv1 === cv1 && cv2 !== cv2) { + return false; + } + + if (cv2 === cv2 && cv1 !== cv1) { + return true; + } + + if (prop1 > prop2) return true; + if (prop1 < prop2) return false; + if (prop1 == prop2) return equal; + + // not strict equal nor less than nor gt so must be dates or mixed types + // convert to string and use that to compare + cv1 = prop1.toString(); + cv2 = prop2.toString(); + + if (cv1 > cv2) { + return true; + } + + if (cv1 == cv2) { + return equal; + } + + return false; + } + + function sortHelper(prop1, prop2, desc) { + if (Comparators.aeq(prop1, prop2)) return 0; + + if (Comparators.lt(prop1, prop2, false)) { + return (desc) ? (1) : (-1); + } + + if (Comparators.gt(prop1, prop2, false)) { + return (desc) ? (-1) : (1); + } + + // not lt, not gt so implied equality-- date compatible + return 0; + } + + /** + * compoundeval() - helper function for compoundsort(), performing individual object comparisons + * + * @param {array} properties - array of property names, in order, by which to evaluate sort order + * @param {object} obj1 - first object to compare + * @param {object} obj2 - second object to compare + * @returns {integer} 0, -1, or 1 to designate if identical (sortwise) or which should be first + */ + function compoundeval(properties, obj1, obj2) { + var res = 0; + var prop, field, val1, val2, arr; + for (var i = 0, len = properties.length; i < len; i++) { + prop = properties[i]; + field = prop[0]; + if (~field.indexOf('.')) { + arr = field.split('.'); + val1 = arr.reduce(function(obj, i) { return obj && obj[i] || undefined; }, obj1); + val2 = arr.reduce(function(obj, i) { return obj && obj[i] || undefined; }, obj2); + } else { + val1 = obj1[field]; + val2 = obj2[field]; + } + res = sortHelper(val1, val2, prop[1]); + if (res !== 0) { + return res; + } + } + return 0; + } + + /** + * dotSubScan - helper function used for dot notation queries. + * + * @param {object} root - object to traverse + * @param {array} paths - array of properties to drill into + * @param {function} fun - evaluation function to test with + * @param {any} value - comparative value to also pass to (compare) fun + * @param {number} poffset - index of the item in 'paths' to start the sub-scan from + */ + function dotSubScan(root, paths, fun, value, poffset) { + var pathOffset = poffset || 0; + var path = paths[pathOffset]; + if (root === undefined || root === null || !hasOwnProperty.call(root, path)) { + return false; + } + + var valueFound = false; + var element = root[path]; + if (pathOffset + 1 >= paths.length) { + // if we have already expanded out the dot notation, + // then just evaluate the test function and value on the element + valueFound = fun(element, value); + } else if (Array.isArray(element)) { + for (var index = 0, len = element.length; index < len; index += 1) { + valueFound = dotSubScan(element[index], paths, fun, value, pathOffset + 1); + if (valueFound === true) { + break; + } + } + } else { + valueFound = dotSubScan(element, paths, fun, value, pathOffset + 1); + } + + return valueFound; + } + + function containsCheckFn(a) { + if (typeof a === 'string' || Array.isArray(a)) { + return function (b) { + return a.indexOf(b) !== -1; + }; + } else if (typeof a === 'object' && a !== null) { + return function (b) { + return hasOwnProperty.call(a, b); + }; + } + return null; + } + + function doQueryOp(val, op) { + for (var p in op) { + if (hasOwnProperty.call(op, p)) { + return LokiOps[p](val, op[p]); + } + } + return false; + } + + var LokiOps = { + // comparison operators + // a is the value in the collection + // b is the query value + $eq: function (a, b) { + return a === b; + }, + + // abstract/loose equality + $aeq: function (a, b) { + return a == b; + }, + + $ne: function (a, b) { + // ecma 5 safe test for NaN + if (b !== b) { + // ecma 5 test value is not NaN + return (a === a); + } + + return a !== b; + }, + // date equality / loki abstract equality test + $dteq: function (a, b) { + return Comparators.aeq(a, b); + }, + + // loki comparisons: return identical unindexed results as indexed comparisons + $gt: function (a, b) { + return Comparators.gt(a, b, false); + }, + + $gte: function (a, b) { + return Comparators.gt(a, b, true); + }, + + $lt: function (a, b) { + return Comparators.lt(a, b, false); + }, + + $lte: function (a, b) { + return Comparators.lt(a, b, true); + }, + + // lightweight javascript comparisons + $jgt: function (a, b) { + return a > b; + }, + + $jgte: function (a, b) { + return a >= b; + }, + + $jlt: function (a, b) { + return a < b; + }, + + $jlte: function (a, b) { + return a <= b; + }, + + // ex : coll.find({'orderCount': {$between: [10, 50]}}); + $between: function (a, vals) { + if (a === undefined || a === null) return false; + return (Comparators.gt(a, vals[0], true) && Comparators.lt(a, vals[1], true)); + }, + + $jbetween: function (a, vals) { + if (a === undefined || a === null) return false; + return (a >= vals[0] && a <= vals[1]); + }, + + $in: function (a, b) { + return b.indexOf(a) !== -1; + }, + + $nin: function (a, b) { + return b.indexOf(a) === -1; + }, + + $keyin: function (a, b) { + return a in b; + }, + + $nkeyin: function (a, b) { + return !(a in b); + }, + + $definedin: function (a, b) { + return b[a] !== undefined; + }, + + $undefinedin: function (a, b) { + return b[a] === undefined; + }, + + $regex: function (a, b) { + return b.test(a); + }, + + $containsString: function (a, b) { + return (typeof a === 'string') && (a.indexOf(b) !== -1); + }, + + $containsNone: function (a, b) { + return !LokiOps.$containsAny(a, b); + }, + + $containsAny: function (a, b) { + var checkFn = containsCheckFn(a); + if (checkFn !== null) { + return (Array.isArray(b)) ? (b.some(checkFn)) : (checkFn(b)); + } + return false; + }, + + $contains: function (a, b) { + var checkFn = containsCheckFn(a); + if (checkFn !== null) { + return (Array.isArray(b)) ? (b.every(checkFn)) : (checkFn(b)); + } + return false; + }, + + $type: function (a, b) { + var type = typeof a; + if (type === 'object') { + if (Array.isArray(a)) { + type = 'array'; + } else if (a instanceof Date) { + type = 'date'; + } + } + return (typeof b !== 'object') ? (type === b) : doQueryOp(type, b); + }, + + $finite: function(a, b) { + return (b === isFinite(a)); + }, + + $size: function (a, b) { + if (Array.isArray(a)) { + return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b); + } + return false; + }, + + $len: function (a, b) { + if (typeof a === 'string') { + return (typeof b !== 'object') ? (a.length === b) : doQueryOp(a.length, b); + } + return false; + }, + + $where: function (a, b) { + return b(a) === true; + }, + + // field-level logical operators + // a is the value in the collection + // b is the nested query operation (for '$not') + // or an array of nested query operations (for '$and' and '$or') + $not: function (a, b) { + return !doQueryOp(a, b); + }, + + $and: function (a, b) { + for (var idx = 0, len = b.length; idx < len; idx += 1) { + if (!doQueryOp(a, b[idx])) { + return false; + } + } + return true; + }, + + $or: function (a, b) { + for (var idx = 0, len = b.length; idx < len; idx += 1) { + if (doQueryOp(a, b[idx])) { + return true; + } + } + return false; + } + }; + + // if an op is registered in this object, our 'calculateRange' can use it with our binary indices. + // if the op is registered to a function, we will run that function/op as a 2nd pass filter on results. + // those 2nd pass filter functions should be similar to LokiOps functions, accepting 2 vals to compare. + var indexedOps = { + $eq: LokiOps.$eq, + $aeq: true, + $dteq: true, + $gt: true, + $gte: true, + $lt: true, + $lte: true, + $in: true, + $between: true + }; + + function clone(data, method) { + if (data === null || data === undefined) { + return null; + } + + var cloneMethod = method || 'parse-stringify', + cloned; + + switch (cloneMethod) { + case "parse-stringify": + cloned = JSON.parse(JSON.stringify(data)); + break; + case "jquery-extend-deep": + cloned = jQuery.extend(true, {}, data); + break; + case "shallow": + // more compatible method for older browsers + cloned = Object.create(data.constructor.prototype); + Object.keys(data).map(function (i) { + cloned[i] = data[i]; + }); + break; + case "shallow-assign": + // should be supported by newer environments/browsers + cloned = Object.create(data.constructor.prototype); + Object.assign(cloned, data); + break; + case "shallow-recurse-objects": + // shallow clone top level properties + cloned = clone(data, "shallow"); + var keys = Object.keys(data); + // for each of the top level properties which are object literals, recursively shallow copy + keys.forEach(function(key) { + if (typeof data[key] === "object" && data[key].constructor.name === "Object") { + cloned[key] = clone(data[key], "shallow-recurse-objects"); + } + }); + break; + default: + break; + } + + return cloned; + } + + function cloneObjectArray(objarray, method) { + var i, + result = []; + + if (method == "parse-stringify") { + return clone(objarray, method); + } + + i = objarray.length - 1; + + for (; i <= 0; i--) { + result.push(clone(objarray[i], method)); + } + + return result; + } + + function localStorageAvailable() { + try { + return (window && window.localStorage !== undefined && window.localStorage !== null); + } catch (e) { + return false; + } + } + + + /** + * LokiEventEmitter is a minimalist version of EventEmitter. It enables any + * constructor that inherits EventEmitter to emit events and trigger + * listeners that have been added to the event through the on(event, callback) method + * + * @constructor LokiEventEmitter + */ + function LokiEventEmitter() {} + + /** + * @prop {hashmap} events - a hashmap, with each property being an array of callbacks + * @memberof LokiEventEmitter + */ + LokiEventEmitter.prototype.events = {}; + + /** + * @prop {boolean} asyncListeners - boolean determines whether or not the callbacks associated with each event + * should happen in an async fashion or not + * Default is false, which means events are synchronous + * @memberof LokiEventEmitter + */ + LokiEventEmitter.prototype.asyncListeners = false; + + /** + * on(eventName, listener) - adds a listener to the queue of callbacks associated to an event + * @param {string|string[]} eventName - the name(s) of the event(s) to listen to + * @param {function} listener - callback function of listener to attach + * @returns {int} the index of the callback in the array of listeners for a particular event + * @memberof LokiEventEmitter + */ + LokiEventEmitter.prototype.on = function (eventName, listener) { + var event; + var self = this; + + if (Array.isArray(eventName)) { + eventName.forEach(function(currentEventName) { + self.on(currentEventName, listener); + }); + return listener; + } + + event = this.events[eventName]; + if (!event) { + event = this.events[eventName] = []; + } + event.push(listener); + return listener; + }; + + /** + * emit(eventName, data) - emits a particular event + * with the option of passing optional parameters which are going to be processed by the callback + * provided signatures match (i.e. if passing emit(event, arg0, arg1) the listener should take two parameters) + * @param {string} eventName - the name of the event + * @param {object=} data - optional object passed with the event + * @memberof LokiEventEmitter + */ + LokiEventEmitter.prototype.emit = function (eventName) { + var self = this; + var selfArgs = Array.prototype.slice.call(arguments, 1); + if (eventName && this.events[eventName]) { + this.events[eventName].forEach(function (listener) { + if (self.asyncListeners) { + setTimeout(function () { + listener.apply(self, selfArgs); + }, 1); + } else { + listener.apply(self, selfArgs); + } + + }); + } else { + throw new Error('No event ' + eventName + ' defined'); + } + }; + + /** + * Alias of LokiEventEmitter.prototype.on + * addListener(eventName, listener) - adds a listener to the queue of callbacks associated to an event + * @param {string|string[]} eventName - the name(s) of the event(s) to listen to + * @param {function} listener - callback function of listener to attach + * @returns {int} the index of the callback in the array of listeners for a particular event + * @memberof LokiEventEmitter + */ + LokiEventEmitter.prototype.addListener = LokiEventEmitter.prototype.on; + + /** + * removeListener() - removes the listener at position 'index' from the event 'eventName' + * @param {string|string[]} eventName - the name(s) of the event(s) which the listener is attached to + * @param {function} listener - the listener callback function to remove from emitter + * @memberof LokiEventEmitter + */ + LokiEventEmitter.prototype.removeListener = function (eventName, listener) { + var self = this; + + if (Array.isArray(eventName)) { + eventName.forEach(function(currentEventName) { + self.removeListener(currentEventName, listener); + }); + + return; + } + + if (this.events[eventName]) { + var listeners = this.events[eventName]; + listeners.splice(listeners.indexOf(listener), 1); + } + }; + + /** + * Loki: The main database class + * @constructor Loki + * @implements LokiEventEmitter + * @param {string} filename - name of the file to be saved to + * @param {object=} options - (Optional) config options object + * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' + * @param {boolean} [options.verbose=false] - enable console output + * @param {boolean} [options.autosave=false] - enables autosave + * @param {int} [options.autosaveInterval=5000] - time interval (in milliseconds) between saves (if dirty) + * @param {boolean} [options.autoload=false] - enables autoload on loki instantiation + * @param {function} options.autoloadCallback - user callback called after database load + * @param {adapter} options.adapter - an instance of a loki persistence adapter + * @param {string} [options.serializationMethod='normal'] - ['normal', 'pretty', 'destructured'] + * @param {string} options.destructureDelimiter - string delimiter used for destructured serialization + * @param {boolean} [options.throttledSaves=true] - debounces multiple calls to to saveDatabase reducing number of disk I/O operations + and guaranteeing proper serialization of the calls. + */ + function Loki(filename, options) { + this.filename = filename || 'loki.db'; + this.collections = []; + + // persist version of code which created the database to the database. + // could use for upgrade scenarios + this.databaseVersion = 1.5; + this.engineVersion = 1.5; + + // autosave support (disabled by default) + // pass autosave: true, autosaveInterval: 6000 in options to set 6 second autosave + this.autosave = false; + this.autosaveInterval = 5000; + this.autosaveHandle = null; + this.throttledSaves = true; + + this.options = {}; + + // currently keeping persistenceMethod and persistenceAdapter as loki level properties that + // will not or cannot be deserialized. You are required to configure persistence every time + // you instantiate a loki object (or use default environment detection) in order to load the database anyways. + + // persistenceMethod could be 'fs', 'localStorage', or 'adapter' + // this is optional option param, otherwise environment detection will be used + // if user passes their own adapter we will force this method to 'adapter' later, so no need to pass method option. + this.persistenceMethod = null; + + // retain reference to optional (non-serializable) persistenceAdapter 'instance' + this.persistenceAdapter = null; + + // flags used to throttle saves + this.throttledSavePending = false; + this.throttledCallbacks = []; + + // enable console output if verbose flag is set (disabled by default) + this.verbose = options && options.hasOwnProperty('verbose') ? options.verbose : false; + + this.events = { + 'init': [], + 'loaded': [], + 'flushChanges': [], + 'close': [], + 'changes': [], + 'warning': [] + }; + + var getENV = function () { + if (typeof global !== 'undefined' && (global.android || global.NSObject)) { + // If no adapter assume nativescript which needs adapter to be passed manually + return 'NATIVESCRIPT'; //nativescript + } + + if (typeof window === 'undefined') { + return 'NODEJS'; + } + + if (typeof global !== 'undefined' && global.window && process) { + return 'NODEJS'; //node-webkit + } + + if (typeof document !== 'undefined') { + if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) { + return 'CORDOVA'; + } + return 'BROWSER'; + } + return 'CORDOVA'; + }; + + // refactored environment detection due to invalid detection for browser environments. + // if they do not specify an options.env we want to detect env rather than default to nodejs. + // currently keeping two properties for similar thing (options.env and options.persistenceMethod) + // might want to review whether we can consolidate. + if (options && options.hasOwnProperty('env')) { + this.ENV = options.env; + } else { + this.ENV = getENV(); + } + + // not sure if this is necessary now that i have refactored the line above + if (this.ENV === 'undefined') { + this.ENV = 'NODEJS'; + } + + this.configureOptions(options, true); + + this.on('init', this.clearChanges); + + } + + // db class is an EventEmitter + Loki.prototype = new LokiEventEmitter(); + Loki.prototype.constructor = Loki; + + // experimental support for browserify's abstract syntax scan to pick up dependency of indexed adapter. + // Hopefully, once this hits npm a browserify require of lokijs should scan the main file and detect this indexed adapter reference. + Loki.prototype.getIndexedAdapter = function () { + var adapter; + + if (typeof require === 'function') { + adapter = require("./loki-indexed-adapter.js"); + } + + return adapter; + }; + + + /** + * Allows reconfiguring database options + * + * @param {object} options - configuration options to apply to loki db object + * @param {string} options.env - override environment detection as 'NODEJS', 'BROWSER', 'CORDOVA' + * @param {boolean} options.verbose - enable console output (default is 'false') + * @param {boolean} options.autosave - enables autosave + * @param {int} options.autosaveInterval - time interval (in milliseconds) between saves (if dirty) + * @param {boolean} options.autoload - enables autoload on loki instantiation + * @param {function} options.autoloadCallback - user callback called after database load + * @param {adapter} options.adapter - an instance of a loki persistence adapter + * @param {string} options.serializationMethod - ['normal', 'pretty', 'destructured'] + * @param {string} options.destructureDelimiter - string delimiter used for destructured serialization + * @param {boolean} initialConfig - (internal) true is passed when loki ctor is invoking + * @memberof Loki + */ + Loki.prototype.configureOptions = function (options, initialConfig) { + var defaultPersistence = { + 'NODEJS': 'fs', + 'BROWSER': 'localStorage', + 'CORDOVA': 'localStorage', + 'MEMORY': 'memory' + }, + persistenceMethods = { + 'fs': LokiFsAdapter, + 'localStorage': LokiLocalStorageAdapter, + 'memory': LokiMemoryAdapter + }; + + this.options = {}; + + this.persistenceMethod = null; + // retain reference to optional persistence adapter 'instance' + // currently keeping outside options because it can't be serialized + this.persistenceAdapter = null; + + // process the options + if (typeof (options) !== 'undefined') { + this.options = options; + + if (this.options.hasOwnProperty('persistenceMethod')) { + // check if the specified persistence method is known + if (typeof (persistenceMethods[options.persistenceMethod]) == 'function') { + this.persistenceMethod = options.persistenceMethod; + this.persistenceAdapter = new persistenceMethods[options.persistenceMethod](); + } + // should be throw an error here, or just fall back to defaults ?? + } + + // if user passes adapter, set persistence mode to adapter and retain persistence adapter instance + if (this.options.hasOwnProperty('adapter')) { + this.persistenceMethod = 'adapter'; + this.persistenceAdapter = options.adapter; + this.options.adapter = null; + } + + + // if they want to load database on loki instantiation, now is a good time to load... after adapter set and before possible autosave initiation + if (options.autoload && initialConfig) { + // for autoload, let the constructor complete before firing callback + var self = this; + setTimeout(function () { + self.loadDatabase(options, options.autoloadCallback); + }, 1); + } + + if (this.options.hasOwnProperty('autosaveInterval')) { + this.autosaveDisable(); + this.autosaveInterval = parseInt(this.options.autosaveInterval, 10); + } + + if (this.options.hasOwnProperty('autosave') && this.options.autosave) { + this.autosaveDisable(); + this.autosave = true; + + if (this.options.hasOwnProperty('autosaveCallback')) { + this.autosaveEnable(options, options.autosaveCallback); + } else { + this.autosaveEnable(); + } + } + + if (this.options.hasOwnProperty('throttledSaves')) { + this.throttledSaves = this.options.throttledSaves; + } + } // end of options processing + + // ensure defaults exists for options which were not set + if (!this.options.hasOwnProperty('serializationMethod')) { + this.options.serializationMethod = 'normal'; + } + + // ensure passed or default option exists + if (!this.options.hasOwnProperty('destructureDelimiter')) { + this.options.destructureDelimiter = '$<\n'; + } + + // if by now there is no adapter specified by user nor derived from persistenceMethod: use sensible defaults + if (this.persistenceAdapter === null) { + this.persistenceMethod = defaultPersistence[this.ENV]; + if (this.persistenceMethod) { + this.persistenceAdapter = new persistenceMethods[this.persistenceMethod](); + } + } + + }; + + /** + * Copies 'this' database into a new Loki instance. Object references are shared to make lightweight. + * + * @param {object} options - apply or override collection level settings + * @param {bool} options.removeNonSerializable - nulls properties not safe for serialization. + * @memberof Loki + */ + Loki.prototype.copy = function(options) { + // in case running in an environment without accurate environment detection, pass 'NA' + var databaseCopy = new Loki(this.filename, { env: "NA" }); + var clen, idx; + + options = options || {}; + + // currently inverting and letting loadJSONObject do most of the work + databaseCopy.loadJSONObject(this, { retainDirtyFlags: true }); + + // since our JSON serializeReplacer is not invoked for reference database adapters, this will let us mimic + if(options.hasOwnProperty("removeNonSerializable") && options.removeNonSerializable === true) { + databaseCopy.autosaveHandle = null; + databaseCopy.persistenceAdapter = null; + + clen = databaseCopy.collections.length; + for (idx=0; idx 0) { + throw new Error("disableMeta option cannot be passed as true when ttl is enabled"); + } + } + + for (i = 0; i < len; i += 1) { + if (this.collections[i].name === name) { + return this.collections[i]; + } + } + + var collection = new Collection(name, options); + this.collections.push(collection); + + if (this.verbose) + collection.console = console; + + return collection; + }; + + Loki.prototype.loadCollection = function (collection) { + if (!collection.name) { + throw new Error('Collection must have a name property to be loaded'); + } + this.collections.push(collection); + }; + + /** + * Retrieves reference to a collection by name. + * @param {string} collectionName - name of collection to look up + * @returns {Collection} Reference to collection in database by that name, or null if not found + * @memberof Loki + */ + Loki.prototype.getCollection = function (collectionName) { + var i, + len = this.collections.length; + + for (i = 0; i < len; i += 1) { + if (this.collections[i].name === collectionName) { + return this.collections[i]; + } + } + + // no such collection + this.emit('warning', 'collection ' + collectionName + ' not found'); + return null; + }; + + /** + * Renames an existing loki collection + * @param {string} oldName - name of collection to rename + * @param {string} newName - new name of collection + * @returns {Collection} reference to the newly renamed collection + * @memberof Loki + */ + Loki.prototype.renameCollection = function (oldName, newName) { + var c = this.getCollection(oldName); + + if (c) { + c.name = newName; + } + + return c; + }; + + /** + * Returns a list of collections in the database. + * @returns {object[]} array of objects containing 'name', 'type', and 'count' properties. + * @memberof Loki + */ + Loki.prototype.listCollections = function () { + + var i = this.collections.length, + colls = []; + + while (i--) { + colls.push({ + name: this.collections[i].name, + type: this.collections[i].objType, + count: this.collections[i].data.length + }); + } + return colls; + }; + + /** + * Removes a collection from the database. + * @param {string} collectionName - name of collection to remove + * @memberof Loki + */ + Loki.prototype.removeCollection = function (collectionName) { + var i, + len = this.collections.length; + + for (i = 0; i < len; i += 1) { + if (this.collections[i].name === collectionName) { + var tmpcol = new Collection(collectionName, {}); + var curcol = this.collections[i]; + for (var prop in curcol) { + if (curcol.hasOwnProperty(prop) && tmpcol.hasOwnProperty(prop)) { + curcol[prop] = tmpcol[prop]; + } + } + this.collections.splice(i, 1); + return; + } + } + }; + + Loki.prototype.getName = function () { + return this.name; + }; + + /** + * serializeReplacer - used to prevent certain properties from being serialized + * + */ + Loki.prototype.serializeReplacer = function (key, value) { + switch (key) { + case 'autosaveHandle': + case 'persistenceAdapter': + case 'constraints': + case 'ttl': + return null; + case 'throttledSavePending': + case 'throttledCallbacks': + return undefined; + default: + return value; + } + }; + + /** + * Serialize database to a string which can be loaded via {@link Loki#loadJSON} + * + * @returns {string} Stringified representation of the loki database. + * @memberof Loki + */ + Loki.prototype.serialize = function (options) { + options = options || {}; + + if (!options.hasOwnProperty("serializationMethod")) { + options.serializationMethod = this.options.serializationMethod; + } + + switch(options.serializationMethod) { + case "normal": return JSON.stringify(this, this.serializeReplacer); + case "pretty": return JSON.stringify(this, this.serializeReplacer, 2); + case "destructured": return this.serializeDestructured(); // use default options + default: return JSON.stringify(this, this.serializeReplacer); + } + }; + + // alias of serialize + Loki.prototype.toJson = Loki.prototype.serialize; + + /** + * Database level destructured JSON serialization routine to allow alternate serialization methods. + * Internally, Loki supports destructuring via loki "serializationMethod' option and + * the optional LokiPartitioningAdapter class. It is also available if you wish to do + * your own structured persistence or data exchange. + * + * @param {object=} options - output format options for use externally to loki + * @param {bool=} options.partitioned - (default: false) whether db and each collection are separate + * @param {int=} options.partition - can be used to only output an individual collection or db (-1) + * @param {bool=} options.delimited - (default: true) whether subitems are delimited or subarrays + * @param {string=} options.delimiter - override default delimiter + * + * @returns {string|array} A custom, restructured aggregation of independent serializations. + * @memberof Loki + */ + Loki.prototype.serializeDestructured = function(options) { + var idx, sidx, result, resultlen; + var reconstruct = []; + var dbcopy; + + options = options || {}; + + if (!options.hasOwnProperty("partitioned")) { + options.partitioned = false; + } + + if (!options.hasOwnProperty("delimited")) { + options.delimited = true; + } + + if (!options.hasOwnProperty("delimiter")) { + options.delimiter = this.options.destructureDelimiter; + } + + // 'partitioned' along with 'partition' of 0 or greater is a request for single collection serialization + if (options.partitioned === true && options.hasOwnProperty("partition") && options.partition >= 0) { + return this.serializeCollection({ + delimited: options.delimited, + delimiter: options.delimiter, + collectionIndex: options.partition + }); + } + + // not just an individual collection, so we will need to serialize db container via shallow copy + dbcopy = new Loki(this.filename); + dbcopy.loadJSONObject(this); + + for(idx=0; idx < dbcopy.collections.length; idx++) { + dbcopy.collections[idx].data = []; + } + + // if we -only- wanted the db container portion, return it now + if (options.partitioned === true && options.partition === -1) { + // since we are deconstructing, override serializationMethod to normal for here + return dbcopy.serialize({ + serializationMethod: "normal" + }); + } + + // at this point we must be deconstructing the entire database + // start by pushing db serialization into first array element + reconstruct.push(dbcopy.serialize({ + serializationMethod: "normal" + })); + + dbcopy = null; + + // push collection data into subsequent elements + for(idx=0; idx < this.collections.length; idx++) { + result = this.serializeCollection({ + delimited: options.delimited, + delimiter: options.delimiter, + collectionIndex: idx + }); + + // NDA : Non-Delimited Array : one iterable concatenated array with empty string collection partitions + if (options.partitioned === false && options.delimited === false) { + if (!Array.isArray(result)) { + throw new Error("a nondelimited, non partitioned collection serialization did not return an expected array"); + } + + // Array.concat would probably duplicate memory overhead for copying strings. + // Instead copy each individually, and clear old value after each copy. + // Hopefully this will allow g.c. to reduce memory pressure, if needed. + resultlen = result.length; + + for (sidx=0; sidx < resultlen; sidx++) { + reconstruct.push(result[sidx]); + result[sidx] = null; + } + + reconstruct.push(""); + } + else { + reconstruct.push(result); + } + } + + // Reconstruct / present results according to four combinations : D, DA, NDA, NDAA + if (options.partitioned) { + // DA : Delimited Array of strings [0] db [1] collection [n] collection { partitioned: true, delimited: true } + // useful for simple future adaptations of existing persistence adapters to save collections separately + if (options.delimited) { + return reconstruct; + } + // NDAA : Non-Delimited Array with subArrays. db at [0] and collection subarrays at [n] { partitioned: true, delimited : false } + // This format might be the most versatile for 'rolling your own' partitioned sync or save. + // Memory overhead can be reduced by specifying a specific partition, but at this code path they did not, so its all. + else { + return reconstruct; + } + } + else { + // D : one big Delimited string { partitioned: false, delimited : true } + // This is the method Loki will use internally if 'destructured'. + // Little memory overhead improvements but does not require multiple asynchronous adapter call scheduling + if (options.delimited) { + // indicate no more collections + reconstruct.push(""); + + return reconstruct.join(options.delimiter); + } + // NDA : Non-Delimited Array : one iterable array with empty string collection partitions { partitioned: false, delimited: false } + // This format might be best candidate for custom synchronous syncs or saves + else { + // indicate no more collections + reconstruct.push(""); + + return reconstruct; + } + } + + reconstruct.push(""); + + return reconstruct.join(delim); + }; + + /** + * Collection level utility method to serialize a collection in a 'destructured' format + * + * @param {object=} options - used to determine output of method + * @param {int} options.delimited - whether to return single delimited string or an array + * @param {string} options.delimiter - (optional) if delimited, this is delimiter to use + * @param {int} options.collectionIndex - specify which collection to serialize data for + * + * @returns {string|array} A custom, restructured aggregation of independent serializations for a single collection. + * @memberof Loki + */ + Loki.prototype.serializeCollection = function(options) { + var doccount, + docidx, + resultlines = []; + + options = options || {}; + + if (!options.hasOwnProperty("delimited")) { + options.delimited = true; + } + + if (!options.hasOwnProperty("collectionIndex")) { + throw new Error("serializeCollection called without 'collectionIndex' option"); + } + + doccount = this.collections[options.collectionIndex].data.length; + + resultlines = []; + + for(docidx=0; docidx collCount) { + done = true; + } + } + else { + currObject = JSON.parse(workarray[lineIndex]); + cdb.collections[collIndex].data.push(currObject); + } + + // lower memory pressure and advance iterator + workarray[lineIndex++] = null; + } + + return cdb; + }; + + /** + * Collection level utility function to deserializes a destructured collection. + * + * @param {string|array} destructuredSource - destructured representation of collection to inflate + * @param {object=} options - used to describe format of destructuredSource input + * @param {int=} [options.delimited=false] - whether source is delimited string or an array + * @param {string=} options.delimiter - if delimited, this is delimiter to use (if other than default) + * + * @returns {array} an array of documents to attach to collection.data. + * @memberof Loki + */ + Loki.prototype.deserializeCollection = function(destructuredSource, options) { + var workarray=[]; + var idx, len; + + options = options || {}; + + if (!options.hasOwnProperty("partitioned")) { + options.partitioned = false; + } + + if (!options.hasOwnProperty("delimited")) { + options.delimited = true; + } + + if (!options.hasOwnProperty("delimiter")) { + options.delimiter = this.options.destructureDelimiter; + } + + if (options.delimited) { + workarray = destructuredSource.split(options.delimiter); + workarray.pop(); + } + else { + workarray = destructuredSource; + } + + len = workarray.length; + for (idx=0; idx < len; idx++) { + workarray[idx] = JSON.parse(workarray[idx]); + } + + return workarray; + }; + + /** + * Inflates a loki database from a serialized JSON string + * + * @param {string} serializedDb - a serialized loki database string + * @param {object=} options - apply or override collection level settings + * @param {bool} options.retainDirtyFlags - whether collection dirty flags will be preserved + * @memberof Loki + */ + Loki.prototype.loadJSON = function (serializedDb, options) { + var dbObject; + if (serializedDb.length === 0) { + dbObject = {}; + } else { + // using option defined in instantiated db not what was in serialized db + switch (this.options.serializationMethod) { + case "normal": + case "pretty": dbObject = JSON.parse(serializedDb); break; + case "destructured": dbObject = this.deserializeDestructured(serializedDb); break; + default: dbObject = JSON.parse(serializedDb); break; + } + } + + this.loadJSONObject(dbObject, options); + }; + + /** + * Inflates a loki database from a JS object + * + * @param {object} dbObject - a serialized loki database string + * @param {object=} options - apply or override collection level settings + * @param {bool} options.retainDirtyFlags - whether collection dirty flags will be preserved + * @memberof Loki + */ + Loki.prototype.loadJSONObject = function (dbObject, options) { + var i = 0, + len = dbObject.collections ? dbObject.collections.length : 0, + coll, + copyColl, + clen, + j, + loader, + collObj; + + this.name = dbObject.name; + + // restore save throttled boolean only if not defined in options + if (dbObject.hasOwnProperty('throttledSaves') && options && !options.hasOwnProperty('throttledSaves')) { + this.throttledSaves = dbObject.throttledSaves; + } + + this.collections = []; + + function makeLoader(coll) { + var collOptions = options[coll.name]; + var inflater; + + if(collOptions.proto) { + inflater = collOptions.inflate || Utils.copyProperties; + + return function(data) { + var collObj = new(collOptions.proto)(); + inflater(data, collObj); + return collObj; + }; + } + + return collOptions.inflate; + } + + for (i; i < len; i += 1) { + coll = dbObject.collections[i]; + + copyColl = this.addCollection(coll.name, { disableChangesApi: coll.disableChangesApi, disableDeltaChangesApi: coll.disableDeltaChangesApi, disableMeta: coll.disableMeta }); + + copyColl.adaptiveBinaryIndices = coll.hasOwnProperty('adaptiveBinaryIndices')?(coll.adaptiveBinaryIndices === true): false; + copyColl.transactional = coll.transactional; + copyColl.asyncListeners = coll.asyncListeners; + copyColl.cloneObjects = coll.cloneObjects; + copyColl.cloneMethod = coll.cloneMethod || "parse-stringify"; + copyColl.autoupdate = coll.autoupdate; + copyColl.changes = coll.changes; + + if (options && options.retainDirtyFlags === true) { + copyColl.dirty = coll.dirty; + } + else { + copyColl.dirty = false; + } + + // load each element individually + clen = coll.data.length; + j = 0; + if (options && options.hasOwnProperty(coll.name)) { + loader = makeLoader(coll); + + for (j; j < clen; j++) { + collObj = loader(coll.data[j]); + copyColl.data[j] = collObj; + copyColl.addAutoUpdateObserver(collObj); + } + } else { + + for (j; j < clen; j++) { + copyColl.data[j] = coll.data[j]; + copyColl.addAutoUpdateObserver(copyColl.data[j]); + } + } + + copyColl.maxId = (typeof coll.maxId === 'undefined') ? 0 : coll.maxId; + copyColl.idIndex = coll.idIndex; + if (typeof (coll.binaryIndices) !== 'undefined') { + copyColl.binaryIndices = coll.binaryIndices; + } + if (typeof coll.transforms !== 'undefined') { + copyColl.transforms = coll.transforms; + } + + copyColl.ensureId(); + + // regenerate unique indexes + copyColl.uniqueNames = []; + if (coll.hasOwnProperty("uniqueNames")) { + copyColl.uniqueNames = coll.uniqueNames; + for (j = 0; j < copyColl.uniqueNames.length; j++) { + copyColl.ensureUniqueIndex(copyColl.uniqueNames[j]); + } + } + + // in case they are loading a database created before we added dynamic views, handle undefined + if (typeof (coll.DynamicViews) === 'undefined') continue; + + // reinflate DynamicViews and attached Resultsets + for (var idx = 0; idx < coll.DynamicViews.length; idx++) { + var colldv = coll.DynamicViews[idx]; + + var dv = copyColl.addDynamicView(colldv.name, colldv.options); + dv.resultdata = colldv.resultdata; + dv.resultsdirty = colldv.resultsdirty; + dv.filterPipeline = colldv.filterPipeline; + + dv.sortCriteria = colldv.sortCriteria; + dv.sortFunction = null; + + dv.sortDirty = colldv.sortDirty; + dv.resultset.filteredrows = colldv.resultset.filteredrows; + dv.resultset.filterInitialized = colldv.resultset.filterInitialized; + + dv.rematerialize({ + removeWhereFilters: true + }); + } + + // Upgrade Logic for binary index refactoring at version 1.5 + if (dbObject.databaseVersion < 1.5) { + // rebuild all indices + copyColl.ensureAllIndexes(true); + copyColl.dirty = true; + } + } + }; + + /** + * Emits the close event. In autosave scenarios, if the database is dirty, this will save and disable timer. + * Does not actually destroy the db. + * + * @param {function=} callback - (Optional) if supplied will be registered with close event before emitting. + * @memberof Loki + */ + Loki.prototype.close = function (callback) { + // for autosave scenarios, we will let close perform final save (if dirty) + // For web use, you might call from window.onbeforeunload to shutdown database, saving pending changes + if (this.autosave) { + this.autosaveDisable(); + if (this.autosaveDirty()) { + this.saveDatabase(callback); + callback = undefined; + } + } + + if (callback) { + this.on('close', callback); + } + this.emit('close'); + }; + + /**-------------------------+ + | Changes API | + +--------------------------*/ + + /** + * The Changes API enables the tracking the changes occurred in the collections since the beginning of the session, + * so it's possible to create a differential dataset for synchronization purposes (possibly to a remote db) + */ + + /** + * (Changes API) : takes all the changes stored in each + * collection and creates a single array for the entire database. If an array of names + * of collections is passed then only the included collections will be tracked. + * + * @param {array=} optional array of collection names. No arg means all collections are processed. + * @returns {array} array of changes + * @see private method createChange() in Collection + * @memberof Loki + */ + Loki.prototype.generateChangesNotification = function (arrayOfCollectionNames) { + function getCollName(coll) { + return coll.name; + } + var changes = [], + selectedCollections = arrayOfCollectionNames || this.collections.map(getCollName); + + this.collections.forEach(function (coll) { + if (selectedCollections.indexOf(getCollName(coll)) !== -1) { + changes = changes.concat(coll.getChanges()); + } + }); + return changes; + }; + + /** + * (Changes API) - stringify changes for network transmission + * @returns {string} string representation of the changes + * @memberof Loki + */ + Loki.prototype.serializeChanges = function (collectionNamesArray) { + return JSON.stringify(this.generateChangesNotification(collectionNamesArray)); + }; + + /** + * (Changes API) : clears all the changes in all collections. + * @memberof Loki + */ + Loki.prototype.clearChanges = function () { + this.collections.forEach(function (coll) { + if (coll.flushChanges) { + coll.flushChanges(); + } + }); + }; + + /*------------------+ + | PERSISTENCE | + -------------------*/ + + /** there are two build in persistence adapters for internal use + * fs for use in Nodejs type environments + * localStorage for use in browser environment + * defined as helper classes here so its easy and clean to use + */ + + /** + * In in-memory persistence adapter for an in-memory database. + * This simple 'key/value' adapter is intended for unit testing and diagnostics. + * + * @param {object=} options - memory adapter options + * @param {boolean} [options.asyncResponses=false] - whether callbacks are invoked asynchronously + * @param {int} [options.asyncTimeout=50] - timeout in ms to queue callbacks + * @constructor LokiMemoryAdapter + */ + function LokiMemoryAdapter(options) { + this.hashStore = {}; + this.options = options || {}; + + if (!this.options.hasOwnProperty('asyncResponses')) { + this.options.asyncResponses = false; + } + + if (!this.options.hasOwnProperty('asyncTimeout')) { + this.options.asyncTimeout = 50; // 50 ms default + } + } + + /** + * Loads a serialized database from its in-memory store. + * (Loki persistence adapter interface function) + * + * @param {string} dbname - name of the database (filename/keyname) + * @param {function} callback - adapter callback to return load result to caller + * @memberof LokiMemoryAdapter + */ + LokiMemoryAdapter.prototype.loadDatabase = function (dbname, callback) { + var self=this; + + if (this.options.asyncResponses) { + setTimeout(function() { + if (self.hashStore.hasOwnProperty(dbname)) { + callback(self.hashStore[dbname].value); + } + else { + // database doesn't exist, return falsy + callback (null); + } + }, this.options.asyncTimeout); + } + else { + if (this.hashStore.hasOwnProperty(dbname)) { + // database doesn't exist, return falsy + callback(this.hashStore[dbname].value); + } + else { + callback (null); + } + } + }; + + /** + * Saves a serialized database to its in-memory store. + * (Loki persistence adapter interface function) + * + * @param {string} dbname - name of the database (filename/keyname) + * @param {function} callback - adapter callback to return load result to caller + * @memberof LokiMemoryAdapter + */ + LokiMemoryAdapter.prototype.saveDatabase = function (dbname, dbstring, callback) { + var self=this; + var saveCount; + + if (this.options.asyncResponses) { + setTimeout(function() { + saveCount = (self.hashStore.hasOwnProperty(dbname)?self.hashStore[dbname].savecount:0); + + self.hashStore[dbname] = { + savecount: saveCount+1, + lastsave: new Date(), + value: dbstring + }; + + callback(); + }, this.options.asyncTimeout); + } + else { + saveCount = (this.hashStore.hasOwnProperty(dbname)?this.hashStore[dbname].savecount:0); + + this.hashStore[dbname] = { + savecount: saveCount+1, + lastsave: new Date(), + value: dbstring + }; + + callback(); + } + }; + + /** + * Deletes a database from its in-memory store. + * + * @param {string} dbname - name of the database (filename/keyname) + * @param {function} callback - function to call when done + * @memberof LokiMemoryAdapter + */ + LokiMemoryAdapter.prototype.deleteDatabase = function(dbname, callback) { + if (this.hashStore.hasOwnProperty(dbname)) { + delete this.hashStore[dbname]; + } + + if (typeof callback === "function") { + callback(); + } + }; + + /** + * An adapter for adapters. Converts a non reference mode adapter into a reference mode adapter + * which can perform destructuring and partioning. Each collection will be stored in its own key/save and + * only dirty collections will be saved. If you turn on paging with default page size of 25megs and save + * a 75 meg collection it should use up roughly 3 save slots (key/value pairs sent to inner adapter). + * A dirty collection that spans three pages will save all three pages again + * Paging mode was added mainly because Chrome has issues saving 'too large' of a string within a + * single indexeddb row. If a single document update causes the collection to be flagged as dirty, all + * of that collection's pages will be written on next save. + * + * @param {object} adapter - reference to a 'non-reference' mode loki adapter instance. + * @param {object=} options - configuration options for partitioning and paging + * @param {bool} options.paging - (default: false) set to true to enable paging collection data. + * @param {int} options.pageSize - (default : 25MB) you can use this to limit size of strings passed to inner adapter. + * @param {string} options.delimiter - allows you to override the default delimeter + * @constructor LokiPartitioningAdapter + */ + function LokiPartitioningAdapter(adapter, options) { + this.mode = "reference"; + this.adapter = null; + this.options = options || {}; + this.dbref = null; + this.dbname = ""; + this.pageIterator = {}; + + // verify user passed an appropriate adapter + if (adapter) { + if (adapter.mode === "reference") { + throw new Error("LokiPartitioningAdapter cannot be instantiated with a reference mode adapter"); + } + else { + this.adapter = adapter; + } + } + else { + throw new Error("LokiPartitioningAdapter requires a (non-reference mode) adapter on construction"); + } + + // set collection paging defaults + if (!this.options.hasOwnProperty("paging")) { + this.options.paging = false; + } + + // default to page size of 25 megs (can be up to your largest serialized object size larger than this) + if (!this.options.hasOwnProperty("pageSize")) { + this.options.pageSize = 25*1024*1024; + } + + if (!this.options.hasOwnProperty("delimiter")) { + this.options.delimiter = '$<\n'; + } + } + + /** + * Loads a database which was partitioned into several key/value saves. + * (Loki persistence adapter interface function) + * + * @param {string} dbname - name of the database (filename/keyname) + * @param {function} callback - adapter callback to return load result to caller + * @memberof LokiPartitioningAdapter + */ + LokiPartitioningAdapter.prototype.loadDatabase = function (dbname, callback) { + var self=this; + this.dbname = dbname; + this.dbref = new Loki(dbname); + + // load the db container (without data) + this.adapter.loadDatabase(dbname, function(result) { + // empty database condition is for inner adapter return null/undefined/falsy + if (!result) { + // partition 0 not found so new database, no need to try to load other partitions. + // return same falsy result to loadDatabase to signify no database exists (yet) + callback(result); + return; + } + + if (typeof result !== "string") { + callback(new Error("LokiPartitioningAdapter received an unexpected response from inner adapter loadDatabase()")); + } + + // I will want to use loki destructuring helper methods so i will inflate into typed instance + var db = JSON.parse(result); + self.dbref.loadJSONObject(db); + db = null; + + var clen = self.dbref.collections.length; + + if (self.dbref.collections.length === 0) { + callback(self.dbref); + return; + } + + self.pageIterator = { + collection: 0, + pageIndex: 0 + }; + + self.loadNextPartition(0, function() { + callback(self.dbref); + }); + }); + }; + + /** + * Used to sequentially load each collection partition, one at a time. + * + * @param {int} partition - ordinal collection position to load next + * @param {function} callback - adapter callback to return load result to caller + */ + LokiPartitioningAdapter.prototype.loadNextPartition = function(partition, callback) { + var keyname = this.dbname + "." + partition; + var self=this; + + if (this.options.paging === true) { + this.pageIterator.pageIndex = 0; + this.loadNextPage(callback); + return; + } + + this.adapter.loadDatabase(keyname, function(result) { + var data = self.dbref.deserializeCollection(result, { delimited: true, collectionIndex: partition }); + self.dbref.collections[partition].data = data; + + if (++partition < self.dbref.collections.length) { + self.loadNextPartition(partition, callback); + } + else { + callback(); + } + }); + }; + + /** + * Used to sequentially load the next page of collection partition, one at a time. + * + * @param {function} callback - adapter callback to return load result to caller + */ + LokiPartitioningAdapter.prototype.loadNextPage = function(callback) { + // calculate name for next saved page in sequence + var keyname = this.dbname + "." + this.pageIterator.collection + "." + this.pageIterator.pageIndex; + var self=this; + + // load whatever page is next in sequence + this.adapter.loadDatabase(keyname, function(result) { + var data = result.split(self.options.delimiter); + result = ""; // free up memory now that we have split it into array + var dlen = data.length; + var idx; + + // detect if last page by presence of final empty string element and remove it if so + var isLastPage = (data[dlen-1] === ""); + if (isLastPage) { + data.pop(); + dlen = data.length; + // empty collections are just a delimiter meaning two blank items + if (data[dlen-1] === "" && dlen === 1) { + data.pop(); + dlen = data.length; + } + } + + // convert stringified array elements to object instances and push to collection data + for(idx=0; idx < dlen; idx++) { + self.dbref.collections[self.pageIterator.collection].data.push(JSON.parse(data[idx])); + data[idx] = null; + } + data = []; + + // if last page, we are done with this partition + if (isLastPage) { + + // if there are more partitions, kick off next partition load + if (++self.pageIterator.collection < self.dbref.collections.length) { + self.loadNextPartition(self.pageIterator.collection, callback); + } + else { + callback(); + } + } + else { + self.pageIterator.pageIndex++; + self.loadNextPage(callback); + } + }); + }; + + /** + * Saves a database by partioning into separate key/value saves. + * (Loki 'reference mode' persistence adapter interface function) + * + * @param {string} dbname - name of the database (filename/keyname) + * @param {object} dbref - reference to database which we will partition and save. + * @param {function} callback - adapter callback to return load result to caller + * + * @memberof LokiPartitioningAdapter + */ + LokiPartitioningAdapter.prototype.exportDatabase = function(dbname, dbref, callback) { + var self=this; + var idx, clen = dbref.collections.length; + + this.dbref = dbref; + this.dbname = dbname; + + // queue up dirty partitions to be saved + this.dirtyPartitions = [-1]; + for(idx=0; idx= cdlen) doneWithPartition = true; + } + // if our current page is bigger than defined pageSize, we are done with page + if (pageLen >= this.options.pageSize) doneWithPage = true; + + // if not done with current page, need delimiter before next item + // if done with partition we also want a delmiter to indicate 'end of pages' final empty row + if (!doneWithPage || doneWithPartition) { + pageBuilder += this.options.delimiter; + pageLen += delimlen; + } + + // if we are done with page save it and pass off to next recursive call or callback + if (doneWithPartition || doneWithPage) { + this.adapter.saveDatabase(keyname, pageBuilder, pageSaveCallback); + return; + } + } + }; + + /** + * A loki persistence adapter which persists using node fs module + * @constructor LokiFsAdapter + */ + function LokiFsAdapter() { + try { + this.fs = require('fs'); + }catch(e) { + this.fs = null; + } + } + + /** + * loadDatabase() - Load data from file, will throw an error if the file does not exist + * @param {string} dbname - the filename of the database to load + * @param {function} callback - the callback to handle the result + * @memberof LokiFsAdapter + */ + LokiFsAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) { + var self = this; + + this.fs.stat(dbname, function (err, stats) { + if (!err && stats.isFile()) { + self.fs.readFile(dbname, { + encoding: 'utf8' + }, function readFileCallback(err, data) { + if (err) { + callback(new Error(err)); + } else { + callback(data); + } + }); + } + else { + callback(null); + } + }); + }; + + /** + * saveDatabase() - save data to file, will throw an error if the file can't be saved + * might want to expand this to avoid dataloss on partial save + * @param {string} dbname - the filename of the database to load + * @param {function} callback - the callback to handle the result + * @memberof LokiFsAdapter + */ + LokiFsAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) { + var self = this; + var tmpdbname = dbname + '~'; + this.fs.writeFile(tmpdbname, dbstring, function writeFileCallback(err) { + if (err) { + callback(new Error(err)); + } else { + self.fs.rename(tmpdbname,dbname,callback); + } + }); + }; + + /** + * deleteDatabase() - delete the database file, will throw an error if the + * file can't be deleted + * @param {string} dbname - the filename of the database to delete + * @param {function} callback - the callback to handle the result + * @memberof LokiFsAdapter + */ + LokiFsAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) { + this.fs.unlink(dbname, function deleteDatabaseCallback(err) { + if (err) { + callback(new Error(err)); + } else { + callback(); + } + }); + }; + + + /** + * A loki persistence adapter which persists to web browser's local storage object + * @constructor LokiLocalStorageAdapter + */ + function LokiLocalStorageAdapter() {} + + /** + * loadDatabase() - Load data from localstorage + * @param {string} dbname - the name of the database to load + * @param {function} callback - the callback to handle the result + * @memberof LokiLocalStorageAdapter + */ + LokiLocalStorageAdapter.prototype.loadDatabase = function loadDatabase(dbname, callback) { + if (localStorageAvailable()) { + callback(localStorage.getItem(dbname)); + } else { + callback(new Error('localStorage is not available')); + } + }; + + /** + * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved + * might want to expand this to avoid dataloss on partial save + * @param {string} dbname - the filename of the database to load + * @param {function} callback - the callback to handle the result + * @memberof LokiLocalStorageAdapter + */ + LokiLocalStorageAdapter.prototype.saveDatabase = function saveDatabase(dbname, dbstring, callback) { + if (localStorageAvailable()) { + localStorage.setItem(dbname, dbstring); + callback(null); + } else { + callback(new Error('localStorage is not available')); + } + }; + + /** + * deleteDatabase() - delete the database from localstorage, will throw an error if it + * can't be deleted + * @param {string} dbname - the filename of the database to delete + * @param {function} callback - the callback to handle the result + * @memberof LokiLocalStorageAdapter + */ + LokiLocalStorageAdapter.prototype.deleteDatabase = function deleteDatabase(dbname, callback) { + if (localStorageAvailable()) { + localStorage.removeItem(dbname); + callback(null); + } else { + callback(new Error('localStorage is not available')); + } + }; + + /** + * Wait for throttledSaves to complete and invoke your callback when drained or duration is met. + * + * @param {function} callback - callback to fire when save queue is drained, it is passed a sucess parameter value + * @param {object=} options - configuration options + * @param {boolean} options.recursiveWait - (default: true) if after queue is drained, another save was kicked off, wait for it + * @param {bool} options.recursiveWaitLimit - (default: false) limit our recursive waiting to a duration + * @param {int} options.recursiveWaitLimitDelay - (default: 2000) cutoff in ms to stop recursively re-draining + * @memberof Loki + */ + Loki.prototype.throttledSaveDrain = function(callback, options) { + var self = this; + var now = (new Date()).getTime(); + + if (!this.throttledSaves) { + callback(true); + } + + options = options || {}; + if (!options.hasOwnProperty('recursiveWait')) { + options.recursiveWait = true; + } + if (!options.hasOwnProperty('recursiveWaitLimit')) { + options.recursiveWaitLimit = false; + } + if (!options.hasOwnProperty('recursiveWaitLimitDuration')) { + options.recursiveWaitLimitDuration = 2000; + } + if (!options.hasOwnProperty('started')) { + options.started = (new Date()).getTime(); + } + + // if save is pending + if (this.throttledSaves && this.throttledSavePending) { + // if we want to wait until we are in a state where there are no pending saves at all + if (options.recursiveWait) { + // queue the following meta callback for when it completes + this.throttledCallbacks.push(function() { + // if there is now another save pending... + if (self.throttledSavePending) { + // if we wish to wait only so long and we have exceeded limit of our waiting, callback with false success value + if (options.recursiveWaitLimit && (now - options.started > options.recursiveWaitLimitDuration)) { + callback(false); + return; + } + // it must be ok to wait on next queue drain + self.throttledSaveDrain(callback, options); + return; + } + // no pending saves so callback with true success + else { + callback(true); + return; + } + }); + } + // just notify when current queue is depleted + else { + this.throttledCallbacks.push(callback); + return; + } + } + // no save pending, just callback + else { + callback(true); + } + }; + + /** + * Internal load logic, decoupled from throttling/contention logic + * + * @param {object} options - not currently used (remove or allow overrides?) + * @param {function=} callback - (Optional) user supplied async callback / error handler + */ + Loki.prototype.loadDatabaseInternal = function (options, callback) { + var cFun = callback || function (err, data) { + if (err) { + throw err; + } + }, + self = this; + + // the persistenceAdapter should be present if all is ok, but check to be sure. + if (this.persistenceAdapter !== null) { + + this.persistenceAdapter.loadDatabase(this.filename, function loadDatabaseCallback(dbString) { + if (typeof (dbString) === 'string') { + var parseSuccess = false; + try { + self.loadJSON(dbString, options || {}); + parseSuccess = true; + } catch (err) { + cFun(err); + } + if (parseSuccess) { + cFun(null); + self.emit('loaded', 'database ' + self.filename + ' loaded'); + } + } else { + // falsy result means new database + if (!dbString) { + cFun(null); + self.emit('loaded', 'empty database ' + self.filename + ' loaded'); + return; + } + + // instanceof error means load faulted + if (dbString instanceof Error) { + cFun(dbString); + return; + } + + // if adapter has returned an js object (other than null or error) attempt to load from JSON object + if (typeof (dbString) === "object") { + self.loadJSONObject(dbString, options || {}); + cFun(null); // return null on success + self.emit('loaded', 'database ' + self.filename + ' loaded'); + return; + } + + cFun("unexpected adapter response : " + dbString); + } + }); + + } else { + cFun(new Error('persistenceAdapter not configured')); + } + }; + + /** + * Handles manually loading from file system, local storage, or adapter (such as indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * To avoid contention with any throttledSaves, we will drain the save queue first. + * + * If you are configured with autosave, you do not need to call this method yourself. + * + * @param {object} options - if throttling saves and loads, this controls how we drain save queue before loading + * @param {boolean} options.recursiveWait - (default: true) wait recursively until no saves are queued + * @param {bool} options.recursiveWaitLimit - (default: false) limit our recursive waiting to a duration + * @param {int} options.recursiveWaitLimitDelay - (default: 2000) cutoff in ms to stop recursively re-draining + * @param {function=} callback - (Optional) user supplied async callback / error handler + * @memberof Loki + * @example + * db.loadDatabase({}, function(err) { + * if (err) { + * console.log("error : " + err); + * } + * else { + * console.log("database loaded."); + * } + * }); + */ + Loki.prototype.loadDatabase = function (options, callback) { + var self=this; + + // if throttling disabled, just call internal + if (!this.throttledSaves) { + this.loadDatabaseInternal(options, callback); + return; + } + + // try to drain any pending saves in the queue to lock it for loading + this.throttledSaveDrain(function(success) { + if (success) { + // pause/throttle saving until loading is done + self.throttledSavePending = true; + + self.loadDatabaseInternal(options, function(err) { + // now that we are finished loading, if no saves were throttled, disable flag + if (self.throttledCallbacks.length === 0) { + self.throttledSavePending = false; + } + // if saves requests came in while loading, kick off new save to kick off resume saves + else { + self.saveDatabase(); + } + + if (typeof callback === 'function') { + callback(err); + } + }); + return; + } + else { + if (typeof callback === 'function') { + callback(new Error("Unable to pause save throttling long enough to read database")); + } + } + }, options); + }; + + /** + * Internal save logic, decoupled from save throttling logic + */ + Loki.prototype.saveDatabaseInternal = function (callback) { + var cFun = callback || function (err) { + if (err) { + throw err; + } + return; + }, + self = this; + + // the persistenceAdapter should be present if all is ok, but check to be sure. + if (this.persistenceAdapter !== null) { + // check if the adapter is requesting (and supports) a 'reference' mode export + if (this.persistenceAdapter.mode === "reference" && typeof this.persistenceAdapter.exportDatabase === "function") { + // filename may seem redundant but loadDatabase will need to expect this same filename + this.persistenceAdapter.exportDatabase(this.filename, this.copy({removeNonSerializable:true}), function exportDatabaseCallback(err) { + self.autosaveClearFlags(); + cFun(err); + }); + } + // otherwise just pass the serialized database to adapter + else { + // persistenceAdapter might be asynchronous, so we must clear `dirty` immediately + // or autosave won't work if an update occurs between here and the callback + self.autosaveClearFlags(); + this.persistenceAdapter.saveDatabase(this.filename, self.serialize(), function saveDatabasecallback(err) { + cFun(err); + }); + } + } else { + cFun(new Error('persistenceAdapter not configured')); + } + }; + + /** + * Handles manually saving to file system, local storage, or adapter (such as indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * If you are configured with autosave, you do not need to call this method yourself. + * + * @param {function=} callback - (Optional) user supplied async callback / error handler + * @memberof Loki + * @example + * db.saveDatabase(function(err) { + * if (err) { + * console.log("error : " + err); + * } + * else { + * console.log("database saved."); + * } + * }); + */ + Loki.prototype.saveDatabase = function (callback) { + if (!this.throttledSaves) { + this.saveDatabaseInternal(callback); + return; + } + + if (this.throttledSavePending) { + this.throttledCallbacks.push(callback); + return; + } + + var localCallbacks = this.throttledCallbacks; + this.throttledCallbacks = []; + localCallbacks.unshift(callback); + this.throttledSavePending = true; + + var self = this; + this.saveDatabaseInternal(function(err) { + self.throttledSavePending = false; + localCallbacks.forEach(function(pcb) { + if (typeof pcb === 'function') { + // Queue the callbacks so we first finish this method execution + setTimeout(function() { + pcb(err); + }, 1); + } + }); + + // since this is called async, future requests may have come in, if so.. kick off next save + if (self.throttledCallbacks.length > 0) { + self.saveDatabase(); + } + }); + }; + + // alias + Loki.prototype.save = Loki.prototype.saveDatabase; + + /** + * Handles deleting a database from file system, local + * storage, or adapter (indexeddb) + * This method utilizes loki configuration options (if provided) to determine which + * persistence method to use, or environment detection (if configuration was not provided). + * + * @param {function=} callback - (Optional) user supplied async callback / error handler + * @memberof Loki + */ + Loki.prototype.deleteDatabase = function (options, callback) { + var cFun = callback || function (err, data) { + if (err) { + throw err; + } + }; + + // we aren't even using options, so we will support syntax where + // callback is passed as first and only argument + if (typeof options === 'function' && !callback) { + cFun = options; + } + + // the persistenceAdapter should be present if all is ok, but check to be sure. + if (this.persistenceAdapter !== null) { + this.persistenceAdapter.deleteDatabase(this.filename, function deleteDatabaseCallback(err) { + cFun(err); + }); + } else { + cFun(new Error('persistenceAdapter not configured')); + } + }; + + /** + * autosaveDirty - check whether any collections are 'dirty' meaning we need to save (entire) database + * + * @returns {boolean} - true if database has changed since last autosave, false if not. + */ + Loki.prototype.autosaveDirty = function () { + for (var idx = 0; idx < this.collections.length; idx++) { + if (this.collections[idx].dirty) { + return true; + } + } + + return false; + }; + + /** + * autosaveClearFlags - resets dirty flags on all collections. + * Called from saveDatabase() after db is saved. + * + */ + Loki.prototype.autosaveClearFlags = function () { + for (var idx = 0; idx < this.collections.length; idx++) { + this.collections[idx].dirty = false; + } + }; + + /** + * autosaveEnable - begin a javascript interval to periodically save the database. + * + * @param {object} options - not currently used (remove or allow overrides?) + * @param {function=} callback - (Optional) user supplied async callback + */ + Loki.prototype.autosaveEnable = function (options, callback) { + this.autosave = true; + + var delay = 5000, + self = this; + + if (typeof (this.autosaveInterval) !== 'undefined' && this.autosaveInterval !== null) { + delay = this.autosaveInterval; + } + + this.autosaveHandle = setInterval(function autosaveHandleInterval() { + // use of dirty flag will need to be hierarchical since mods are done at collection level with no visibility of 'db' + // so next step will be to implement collection level dirty flags set on insert/update/remove + // along with loki level isdirty() function which iterates all collections to see if any are dirty + + if (self.autosaveDirty()) { + self.saveDatabase(callback); + } + }, delay); + }; + + /** + * autosaveDisable - stop the autosave interval timer. + * + */ + Loki.prototype.autosaveDisable = function () { + if (typeof (this.autosaveHandle) !== 'undefined' && this.autosaveHandle !== null) { + clearInterval(this.autosaveHandle); + this.autosaveHandle = null; + } + }; + + + /** + * Resultset class allowing chainable queries. Intended to be instanced internally. + * Collection.find(), Collection.where(), and Collection.chain() instantiate this. + * + * @example + * mycollection.chain() + * .find({ 'doors' : 4 }) + * .where(function(obj) { return obj.name === 'Toyota' }) + * .data(); + * + * @constructor Resultset + * @param {Collection} collection - The collection which this Resultset will query against. + */ + function Resultset(collection, options) { + options = options || {}; + + // retain reference to collection we are querying against + this.collection = collection; + this.filteredrows = []; + this.filterInitialized = false; + + return this; + } + + /** + * reset() - Reset the resultset to its initial state. + * + * @returns {Resultset} Reference to this resultset, for future chain operations. + */ + Resultset.prototype.reset = function () { + if (this.filteredrows.length > 0) { + this.filteredrows = []; + } + this.filterInitialized = false; + return this; + }; + + /** + * toJSON() - Override of toJSON to avoid circular references + * + */ + Resultset.prototype.toJSON = function () { + var copy = this.copy(); + copy.collection = null; + return copy; + }; + + /** + * Allows you to limit the number of documents passed to next chain operation. + * A resultset copy() is made to avoid altering original resultset. + * + * @param {int} qty - The number of documents to return. + * @returns {Resultset} Returns a copy of the resultset, limited by qty, for subsequent chain ops. + * @memberof Resultset + * // find the two oldest users + * var result = users.chain().simplesort("age", true).limit(2).data(); + */ + Resultset.prototype.limit = function (qty) { + // if this has no filters applied, we need to populate filteredrows first + if (!this.filterInitialized && this.filteredrows.length === 0) { + this.filteredrows = this.collection.prepareFullDocIndex(); + } + + var rscopy = new Resultset(this.collection); + rscopy.filteredrows = this.filteredrows.slice(0, qty); + rscopy.filterInitialized = true; + return rscopy; + }; + + /** + * Used for skipping 'pos' number of documents in the resultset. + * + * @param {int} pos - Number of documents to skip; all preceding documents are filtered out. + * @returns {Resultset} Returns a copy of the resultset, containing docs starting at 'pos' for subsequent chain ops. + * @memberof Resultset + * // find everyone but the two oldest users + * var result = users.chain().simplesort("age", true).offset(2).data(); + */ + Resultset.prototype.offset = function (pos) { + // if this has no filters applied, we need to populate filteredrows first + if (!this.filterInitialized && this.filteredrows.length === 0) { + this.filteredrows = this.collection.prepareFullDocIndex(); + } + + var rscopy = new Resultset(this.collection); + rscopy.filteredrows = this.filteredrows.slice(pos); + rscopy.filterInitialized = true; + return rscopy; + }; + + /** + * copy() - To support reuse of resultset in branched query situations. + * + * @returns {Resultset} Returns a copy of the resultset (set) but the underlying document references will be the same. + * @memberof Resultset + */ + Resultset.prototype.copy = function () { + var result = new Resultset(this.collection); + + if (this.filteredrows.length > 0) { + result.filteredrows = this.filteredrows.slice(); + } + result.filterInitialized = this.filterInitialized; + + return result; + }; + + /** + * Alias of copy() + * @memberof Resultset + */ + Resultset.prototype.branch = Resultset.prototype.copy; + + /** + * transform() - executes a named collection transform or raw array of transform steps against the resultset. + * + * @param transform {(string|array)} - name of collection transform or raw transform array + * @param parameters {object=} - (Optional) object property hash of parameters, if the transform requires them. + * @returns {Resultset} either (this) resultset or a clone of of this resultset (depending on steps) + * @memberof Resultset + * @example + * users.addTransform('CountryFilter', [ + * { + * type: 'find', + * value: { + * 'country': { $eq: '[%lktxp]Country' } + * } + * }, + * { + * type: 'simplesort', + * property: 'age', + * options: { desc: false} + * } + * ]); + * var results = users.chain().transform("CountryFilter", { Country: 'fr' }).data(); + */ + Resultset.prototype.transform = function (transform, parameters) { + var idx, + step, + rs = this; + + // if transform is name, then do lookup first + if (typeof transform === 'string') { + if (this.collection.transforms.hasOwnProperty(transform)) { + transform = this.collection.transforms[transform]; + } + } + + // either they passed in raw transform array or we looked it up, so process + if (typeof transform !== 'object' || !Array.isArray(transform)) { + throw new Error("Invalid transform"); + } + + if (typeof parameters !== 'undefined') { + transform = Utils.resolveTransformParams(transform, parameters); + } + + for (idx = 0; idx < transform.length; idx++) { + step = transform[idx]; + + switch (step.type) { + case "find": + rs.find(step.value); + break; + case "where": + rs.where(step.value); + break; + case "simplesort": + rs.simplesort(step.property, step.desc || step.options); + break; + case "compoundsort": + rs.compoundsort(step.value); + break; + case "sort": + rs.sort(step.value); + break; + case "limit": + rs = rs.limit(step.value); + break; // limit makes copy so update reference + case "offset": + rs = rs.offset(step.value); + break; // offset makes copy so update reference + case "map": + rs = rs.map(step.value, step.dataOptions); + break; + case "eqJoin": + rs = rs.eqJoin(step.joinData, step.leftJoinKey, step.rightJoinKey, step.mapFun, step.dataOptions); + break; + // following cases break chain by returning array data so make any of these last in transform steps + case "mapReduce": + rs = rs.mapReduce(step.mapFunction, step.reduceFunction); + break; + // following cases update documents in current filtered resultset (use carefully) + case "update": + rs.update(step.value); + break; + case "remove": + rs.remove(); + break; + default: + break; + } + } + + return rs; + }; + + /** + * User supplied compare function is provided two documents to compare. (chainable) + * @example + * rslt.sort(function(obj1, obj2) { + * if (obj1.name === obj2.name) return 0; + * if (obj1.name > obj2.name) return 1; + * if (obj1.name < obj2.name) return -1; + * }); + * + * @param {function} comparefun - A javascript compare function used for sorting. + * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @memberof Resultset + */ + Resultset.prototype.sort = function (comparefun) { + // if this has no filters applied, just we need to populate filteredrows first + if (!this.filterInitialized && this.filteredrows.length === 0) { + this.filteredrows = this.collection.prepareFullDocIndex(); + } + + var wrappedComparer = + (function (userComparer, data) { + return function (a, b) { + return userComparer(data[a], data[b]); + }; + })(comparefun, this.collection.data); + + this.filteredrows.sort(wrappedComparer); + + return this; + }; + + /** + * Simpler, loose evaluation for user to sort based on a property name. (chainable). + * Sorting based on the same lt/gt helper functions used for binary indices. + * + * @param {string} propname - name of property to sort by. + * @param {object|bool=} options - boolean to specify if isdescending, or options object + * @param {boolean} [options.desc=false] - whether to sort descending + * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection. + * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists). + * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort. + * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @memberof Resultset + * @example + * var results = users.chain().simplesort('age').data(); + */ + Resultset.prototype.simplesort = function (propname, options) { + var eff, + targetEff = 10, + dc = this.collection.data.length, + frl = this.filteredrows.length, + hasBinaryIndex = this.collection.binaryIndices.hasOwnProperty(propname); + + if (typeof (options) === 'undefined' || options === false) { + options = { desc: false }; + } + if (options === true) { + options = { desc: true }; + } + + // if nothing in filtered rows array... + if (frl === 0) { + // if the filter is initialized to be empty resultset, do nothing + if (this.filterInitialized) { + return this; + } + + // otherwise no filters applied implies all documents, so we need to populate filteredrows first + + // if we have a binary index, we can just use that instead of sorting (again) + if (this.collection.binaryIndices.hasOwnProperty(propname)) { + // make sure index is up-to-date + this.collection.ensureIndex(propname); + // copy index values into filteredrows + this.filteredrows = this.collection.binaryIndices[propname].values.slice(0); + + if (options.desc) { + this.filteredrows.reverse(); + } + + // we are done, return this (resultset) for further chain ops + return this; + } + // otherwise initialize array for sort below + else { + // build full document index (to be sorted subsequently) + this.filteredrows = this.collection.prepareFullDocIndex(); + } + } + // otherwise we had results to begin with, see if we qualify for index intercept optimization + else { + + // If already filtered, but we want to leverage binary index on sort. + // This will use custom array intection algorithm. + if (!options.disableIndexIntersect && hasBinaryIndex) { + + // calculate filter efficiency + eff = dc/frl; + + // when javascript sort fallback is enabled, you generally need more than ~17% of total docs in resultset + // before array intersect is determined to be the faster algorithm, otherwise leave at 10% for loki sort. + if (options.useJavascriptSorting) { + targetEff = 6; + } + + // anything more than ratio of 10:1 (total documents/current results) should use old sort code path + // So we will only use array intersection if you have more than 10% of total docs in your current resultset. + if (eff <= targetEff || options.forceIndexIntersect) { + var idx, fr=this.filteredrows; + var io = {}; + // set up hashobject for simple 'inclusion test' with existing (filtered) results + for(idx=0; idx obj2[propname]) return 1; + if (obj1[propname] < obj2[propname]) return -1; + }); + } + + // otherwise use loki sort which will return same results if column is indexed or not + var wrappedComparer = + (function (prop, desc, data) { + var val1, val2, arr; + return function (a, b) { + if (~prop.indexOf('.')) { + arr = prop.split('.'); + val1 = arr.reduce(function(obj, i) { return obj && obj[i] || undefined; }, data[a]); + val2 = arr.reduce(function(obj, i) { return obj && obj[i] || undefined; }, data[b]); + } else { + val1 = data[a][prop]; + val2 = data[b][prop]; + } + return sortHelper(val1, val2, desc); + }; + })(propname, options.desc, this.collection.data); + + this.filteredrows.sort(wrappedComparer); + + return this; + }; + + /** + * Allows sorting a resultset based on multiple columns. + * @example + * // to sort by age and then name (both ascending) + * rs.compoundsort(['age', 'name']); + * // to sort by age (ascending) and then by name (descending) + * rs.compoundsort(['age', ['name', true]); + * + * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order + * @returns {Resultset} Reference to this resultset, sorted, for future chain operations. + * @memberof Resultset + */ + Resultset.prototype.compoundsort = function (properties) { + if (properties.length === 0) { + throw new Error("Invalid call to compoundsort, need at least one property"); + } + + var prop; + if (properties.length === 1) { + prop = properties[0]; + if (Array.isArray(prop)) { + return this.simplesort(prop[0], prop[1]); + } + return this.simplesort(prop, false); + } + + // unify the structure of 'properties' to avoid checking it repeatedly while sorting + for (var i = 0, len = properties.length; i < len; i += 1) { + prop = properties[i]; + if (!Array.isArray(prop)) { + properties[i] = [prop, false]; + } + } + + // if this has no filters applied, just we need to populate filteredrows first + if (!this.filterInitialized && this.filteredrows.length === 0) { + this.filteredrows = this.collection.prepareFullDocIndex(); + } + + var wrappedComparer = + (function (props, data) { + return function (a, b) { + return compoundeval(props, data[a], data[b]); + }; + })(properties, this.collection.data); + + this.filteredrows.sort(wrappedComparer); + + return this; + }; + + /** + * findOr() - oversee the operation of OR'ed query expressions. + * OR'ed expression evaluation runs each expression individually against the full collection, + * and finally does a set OR on each expression's results. + * Each evaluation can utilize a binary index to prevent multiple linear array scans. + * + * @param {array} expressionArray - array of expressions + * @returns {Resultset} this resultset for further chain ops. + */ + Resultset.prototype.findOr = function (expressionArray) { + var fr = null, + fri = 0, + frlen = 0, + docset = [], + idxset = [], + idx = 0, + origCount = this.count(); + + // If filter is already initialized, then we query against only those items already in filter. + // This means no index utilization for fields, so hopefully its filtered to a smallish filteredrows. + for (var ei = 0, elen = expressionArray.length; ei < elen; ei++) { + // we need to branch existing query to run each filter separately and combine results + fr = this.branch().find(expressionArray[ei]).filteredrows; + frlen = fr.length; + // if the find operation did not reduce the initial set, then the initial set is the actual result + if (frlen === origCount) { + return this; + } + + // add any document 'hits' + for (fri = 0; fri < frlen; fri++) { + idx = fr[fri]; + if (idxset[idx] === undefined) { + idxset[idx] = true; + docset.push(idx); + } + } + } + + this.filteredrows = docset; + this.filterInitialized = true; + + return this; + }; + Resultset.prototype.$or = Resultset.prototype.findOr; + + /** + * findAnd() - oversee the operation of AND'ed query expressions. + * AND'ed expression evaluation runs each expression progressively against the full collection, + * internally utilizing existing chained resultset functionality. + * Only the first filter can utilize a binary index. + * + * @param {array} expressionArray - array of expressions + * @returns {Resultset} this resultset for further chain ops. + */ + Resultset.prototype.findAnd = function (expressionArray) { + // we have already implementing method chaining in this (our Resultset class) + // so lets just progressively apply user supplied and filters + for (var i = 0, len = expressionArray.length; i < len; i++) { + if (this.count() === 0) { + return this; + } + this.find(expressionArray[i]); + } + return this; + }; + Resultset.prototype.$and = Resultset.prototype.findAnd; + + /** + * Used for querying via a mongo-style query object. + * + * @param {object} query - A mongo-style query object used for filtering current results. + * @param {boolean=} firstOnly - (Optional) Used by collection.findOne() + * @returns {Resultset} this resultset for further chain ops. + * @memberof Resultset + * @example + * var over30 = users.chain().find({ age: { $gte: 30 } }).data(); + */ + Resultset.prototype.find = function (query, firstOnly) { + if (this.collection.data.length === 0) { + this.filteredrows = []; + this.filterInitialized = true; + return this; + } + + var queryObject = query || 'getAll', + p, + property, + queryObjectOp, + obj, + operator, + value, + key, + searchByIndex = false, + result = [], + filters = [], + index = null; + + // flag if this was invoked via findOne() + firstOnly = firstOnly || false; + + if (typeof queryObject === 'object') { + for (p in queryObject) { + obj = {}; + obj[p] = queryObject[p]; + filters.push(obj); + + if (hasOwnProperty.call(queryObject, p)) { + property = p; + queryObjectOp = queryObject[p]; + } + } + // if more than one expression in single query object, + // convert implicit $and to explicit $and + if (filters.length > 1) { + return this.find({ '$and': filters }, firstOnly); + } + } + + // apply no filters if they want all + if (!property || queryObject === 'getAll') { + if (firstOnly) { + this.filteredrows = (this.collection.data.length > 0)?[0]: []; + this.filterInitialized = true; + } + + return this; + } + + // injecting $and and $or expression tree evaluation here. + if (property === '$and' || property === '$or') { + this[property](queryObjectOp); + + // for chained find with firstonly, + if (firstOnly && this.filteredrows.length > 1) { + this.filteredrows = this.filteredrows.slice(0, 1); + } + + return this; + } + + // see if query object is in shorthand mode (assuming eq operator) + if (queryObjectOp === null || (typeof queryObjectOp !== 'object' || queryObjectOp instanceof Date)) { + operator = '$eq'; + value = queryObjectOp; + } else if (typeof queryObjectOp === 'object') { + for (key in queryObjectOp) { + if (hasOwnProperty.call(queryObjectOp, key)) { + operator = key; + value = queryObjectOp[key]; + break; + } + } + } else { + throw new Error('Do not know what you want to do.'); + } + + // for regex ops, precompile + if (operator === '$regex') { + if (Array.isArray(value)) { + value = new RegExp(value[0], value[1]); + } else if (!(value instanceof RegExp)) { + value = new RegExp(value); + } + } + + // if user is deep querying the object such as find('name.first': 'odin') + var usingDotNotation = (property.indexOf('.') !== -1); + + // if an index exists for the property being queried against, use it + // for now only enabling where it is the first filter applied and prop is indexed + var doIndexCheck = !usingDotNotation && !this.filterInitialized; + + if (doIndexCheck && this.collection.binaryIndices[property] && indexedOps[operator]) { + // this is where our lazy index rebuilding will take place + // basically we will leave all indexes dirty until we need them + // so here we will rebuild only the index tied to this property + // ensureIndex() will only rebuild if flagged as dirty since we are not passing force=true param + if (this.collection.adaptiveBinaryIndices !== true) { + this.collection.ensureIndex(property); + } + + searchByIndex = true; + index = this.collection.binaryIndices[property]; + } + + // the comparison function + var fun = LokiOps[operator]; + + // "shortcut" for collection data + var t = this.collection.data; + // filter data length + var i = 0, + len = 0; + + // Query executed differently depending on : + // - whether the property being queried has an index defined + // - if chained, we handle first pass differently for initial filteredrows[] population + // + // For performance reasons, each case has its own if block to minimize in-loop calculations + + var filter, rowIdx = 0; + + // If the filteredrows[] is already initialized, use it + if (this.filterInitialized) { + filter = this.filteredrows; + len = filter.length; + + // currently supporting dot notation for non-indexed conditions only + if (usingDotNotation) { + property = property.split('.'); + for(i=0; i= 30; }.data(); + */ + Resultset.prototype.where = function (fun) { + var viewFunction, + result = []; + + if ('function' === typeof fun) { + viewFunction = fun; + } else { + throw new TypeError('Argument is not a stored view or a function'); + } + try { + // If the filteredrows[] is already initialized, use it + if (this.filterInitialized) { + var j = this.filteredrows.length; + + while (j--) { + if (viewFunction(this.collection.data[this.filteredrows[j]]) === true) { + result.push(this.filteredrows[j]); + } + } + + this.filteredrows = result; + + return this; + } + // otherwise this is initial chained op, work against data, push into filteredrows[] + else { + var k = this.collection.data.length; + + while (k--) { + if (viewFunction(this.collection.data[k]) === true) { + result.push(k); + } + } + + this.filteredrows = result; + this.filterInitialized = true; + + return this; + } + } catch (err) { + throw err; + } + }; + + /** + * count() - returns the number of documents in the resultset. + * + * @returns {number} The number of documents in the resultset. + * @memberof Resultset + * @example + * var over30Count = users.chain().find({ age: { $gte: 30 } }).count(); + */ + Resultset.prototype.count = function () { + if (this.filterInitialized) { + return this.filteredrows.length; + } + return this.collection.count(); + }; + + /** + * Terminates the chain and returns array of filtered documents + * + * @param {object=} options - allows specifying 'forceClones' and 'forceCloneMethod' options. + * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when + * the collection is not configured for clone object. + * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param {bool} options.removeMeta - Will force clones and strip $loki and meta properties from documents + * + * @returns {array} Array of documents in the resultset + * @memberof Resultset + * @example + * var resutls = users.chain().find({ age: 34 }).data(); + */ + Resultset.prototype.data = function (options) { + var result = [], + data = this.collection.data, + obj, + len, + i, + method; + + options = options || {}; + + // if user opts to strip meta, then force clones and use 'shallow' if 'force' options are not present + if (options.removeMeta && !options.forceClones) { + options.forceClones = true; + options.forceCloneMethod = options.forceCloneMethod || 'shallow'; + } + + // if collection has delta changes active, then force clones and use 'parse-stringify' for effective change tracking of nested objects + if (!this.collection.disableDeltaChangesApi) { + options.forceClones = true; + options.forceCloneMethod = 'parse-stringify'; + } + + // if this has no filters applied, just return collection.data + if (!this.filterInitialized) { + if (this.filteredrows.length === 0) { + // determine whether we need to clone objects or not + if (this.collection.cloneObjects || options.forceClones) { + len = data.length; + method = options.forceCloneMethod || this.collection.cloneMethod; + + for (i = 0; i < len; i++) { + obj = clone(data[i], method); + if (options.removeMeta) { + delete obj.$loki; + delete obj.meta; + } + result.push(obj); + } + return result; + } + // otherwise we are not cloning so return sliced array with same object references + else { + return data.slice(); + } + } else { + // filteredrows must have been set manually, so use it + this.filterInitialized = true; + } + } + + var fr = this.filteredrows; + len = fr.length; + + if (this.collection.cloneObjects || options.forceClones) { + method = options.forceCloneMethod || this.collection.cloneMethod; + for (i = 0; i < len; i++) { + obj = clone(data[fr[i]], method); + if (options.removeMeta) { + delete obj.$loki; + delete obj.meta; + } + result.push(obj); + } + } else { + for (i = 0; i < len; i++) { + result.push(data[fr[i]]); + } + } + return result; + }; + + /** + * Used to run an update operation on all documents currently in the resultset. + * + * @param {function} updateFunction - User supplied updateFunction(obj) will be executed for each document object. + * @returns {Resultset} this resultset for further chain ops. + * @memberof Resultset + * @example + * users.chain().find({ country: 'de' }).update(function(user) { + * user.phoneFormat = "+49 AAAA BBBBBB"; + * }); + */ + Resultset.prototype.update = function (updateFunction) { + + if (typeof (updateFunction) !== "function") { + throw new TypeError('Argument is not a function'); + } + + // if this has no filters applied, we need to populate filteredrows first + if (!this.filterInitialized && this.filteredrows.length === 0) { + this.filteredrows = this.collection.prepareFullDocIndex(); + } + + var obj, len = this.filteredrows.length, + rcd = this.collection.data; + + // pass in each document object currently in resultset to user supplied updateFunction + for (var idx = 0; idx < len; idx++) { + // if we have cloning option specified or are doing differential delta changes, clone object first + if (this.collection.cloneObjects || !this.collection.disableDeltaChangesApi) { + obj = clone(rcd[this.filteredrows[idx]], this.collection.cloneMethod); + updateFunction(obj); + this.collection.update(obj); + } + else { + // no need to clone, so just perform update on collection data object instance + updateFunction(rcd[this.filteredrows[idx]]); + this.collection.update(rcd[this.filteredrows[idx]]); + } + } + + return this; + }; + + /** + * Removes all document objects which are currently in resultset from collection (as well as resultset) + * + * @returns {Resultset} this (empty) resultset for further chain ops. + * @memberof Resultset + * @example + * // remove users inactive since 1/1/2001 + * users.chain().find({ lastActive: { $lte: new Date("1/1/2001").getTime() } }).remove(); + */ + Resultset.prototype.remove = function () { + + // if this has no filters applied, we need to populate filteredrows first + if (!this.filterInitialized && this.filteredrows.length === 0) { + this.filteredrows = this.collection.prepareFullDocIndex(); + } + + this.collection.removeBatchByPositions(this.filteredrows); + + this.filteredrows = []; + + return this; + }; + + /** + * data transformation via user supplied functions + * + * @param {function} mapFunction - this function accepts a single document for you to transform and return + * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value + * @returns {value} The output of your reduceFunction + * @memberof Resultset + * @example + * var db = new loki("order.db"); + * var orders = db.addCollection("orders"); + * orders.insert([{ qty: 4, unitCost: 100.00 }, { qty: 10, unitCost: 999.99 }, { qty: 2, unitCost: 49.99 }]); + * + * function mapfun (obj) { return obj.qty*obj.unitCost }; + * function reducefun(array) { + * var grandTotal=0; + * array.forEach(function(orderTotal) { grandTotal += orderTotal; }); + * return grandTotal; + * } + * var grandOrderTotal = orders.chain().mapReduce(mapfun, reducefun); + * console.log(grandOrderTotal); + */ + Resultset.prototype.mapReduce = function (mapFunction, reduceFunction) { + try { + return reduceFunction(this.data().map(mapFunction)); + } catch (err) { + throw err; + } + }; + + /** + * eqJoin() - Left joining two sets of data. Join keys can be defined or calculated properties + * eqJoin expects the right join key values to be unique. Otherwise left data will be joined on the last joinData object with that key + * @param {Array|Resultset|Collection} joinData - Data array to join to. + * @param {(string|function)} leftJoinKey - Property name in this result set to join on or a function to produce a value to join on + * @param {(string|function)} rightJoinKey - Property name in the joinData to join on or a function to produce a value to join on + * @param {function=} mapFun - (Optional) A function that receives each matching pair and maps them into output objects - function(left,right){return joinedObject} + * @param {object=} dataOptions - options to data() before input to your map function + * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun + * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object + * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method. + * @returns {Resultset} A resultset with data in the format [{left: leftObj, right: rightObj}] + * @memberof Resultset + * @example + * var db = new loki('sandbox.db'); + * + * var products = db.addCollection('products'); + * var orders = db.addCollection('orders'); + * + * products.insert({ productId: "100234", name: "flywheel energy storage", unitCost: 19999.99 }); + * products.insert({ productId: "140491", name: "300F super capacitor", unitCost: 129.99 }); + * products.insert({ productId: "271941", name: "fuel cell", unitCost: 3999.99 }); + * products.insert({ productId: "174592", name: "390V 3AH lithium bank", unitCost: 4999.99 }); + * + * orders.insert({ orderDate : new Date("12/1/2017").getTime(), prodId: "174592", qty: 2, customerId: 2 }); + * orders.insert({ orderDate : new Date("4/15/2016").getTime(), prodId: "271941", qty: 1, customerId: 1 }); + * orders.insert({ orderDate : new Date("3/12/2017").getTime(), prodId: "140491", qty: 4, customerId: 4 }); + * orders.insert({ orderDate : new Date("7/31/2017").getTime(), prodId: "100234", qty: 7, customerId: 3 }); + * orders.insert({ orderDate : new Date("8/3/2016").getTime(), prodId: "174592", qty: 3, customerId: 5 }); + * + * var mapfun = function(left, right) { + * return { + * orderId: left.$loki, + * orderDate: new Date(left.orderDate) + '', + * customerId: left.customerId, + * qty: left.qty, + * productId: left.prodId, + * prodName: right.name, + * prodCost: right.unitCost, + * orderTotal: +((right.unitCost * left.qty).toFixed(2)) + * }; + * }; + * + * // join orders with relevant product info via eqJoin + * var orderSummary = orders.chain().eqJoin(products, "prodId", "productId", mapfun).data(); + * + * console.log(orderSummary); + */ + Resultset.prototype.eqJoin = function (joinData, leftJoinKey, rightJoinKey, mapFun, dataOptions) { + + var leftData = [], + leftDataLength, + rightData = [], + rightDataLength, + key, + result = [], + leftKeyisFunction = typeof leftJoinKey === 'function', + rightKeyisFunction = typeof rightJoinKey === 'function', + joinMap = {}; + + //get the left data + leftData = this.data(dataOptions); + leftDataLength = leftData.length; + + //get the right data + if (joinData instanceof Collection) { + rightData = joinData.chain().data(dataOptions); + } else if (joinData instanceof Resultset) { + rightData = joinData.data(dataOptions); + } else if (Array.isArray(joinData)) { + rightData = joinData; + } else { + throw new TypeError('joinData needs to be an array or result set'); + } + rightDataLength = rightData.length; + + //construct a lookup table + + for (var i = 0; i < rightDataLength; i++) { + key = rightKeyisFunction ? rightJoinKey(rightData[i]) : rightData[i][rightJoinKey]; + joinMap[key] = rightData[i]; + } + + if (!mapFun) { + mapFun = function (left, right) { + return { + left: left, + right: right + }; + }; + } + + //Run map function over each object in the resultset + for (var j = 0; j < leftDataLength; j++) { + key = leftKeyisFunction ? leftJoinKey(leftData[j]) : leftData[j][leftJoinKey]; + result.push(mapFun(leftData[j], joinMap[key] || {})); + } + + //return return a new resultset with no filters + this.collection = new Collection('joinData'); + this.collection.insert(result); + this.filteredrows = []; + this.filterInitialized = false; + + return this; + }; + + /** + * Applies a map function into a new collection for further chaining. + * @param {function} mapFun - javascript map function + * @param {object=} dataOptions - options to data() before input to your map function + * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun + * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object + * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method. + * @memberof Resultset + * @example + * var orders.chain().find({ productId: 32 }).map(function(obj) { + * return { + * orderId: $loki, + * productId: productId, + * quantity: qty + * }; + * }); + */ + Resultset.prototype.map = function (mapFun, dataOptions) { + var data = this.data(dataOptions).map(mapFun); + //return return a new resultset with no filters + this.collection = new Collection('mappedData'); + this.collection.insert(data); + this.filteredrows = []; + this.filterInitialized = false; + + return this; + }; + + /** + * DynamicView class is a versatile 'live' view class which can have filters and sorts applied. + * Collection.addDynamicView(name) instantiates this DynamicView object and notifies it + * whenever documents are add/updated/removed so it can remain up-to-date. (chainable) + * + * @example + * var mydv = mycollection.addDynamicView('test'); // default is non-persistent + * mydv.applyFind({ 'doors' : 4 }); + * mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; }); + * var results = mydv.data(); + * + * @constructor DynamicView + * @implements LokiEventEmitter + * @param {Collection} collection - A reference to the collection to work against + * @param {string} name - The name of this dynamic view + * @param {object=} options - (Optional) Pass in object with 'persistent' and/or 'sortPriority' options. + * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' + * @param {string} [options.sortPriority='passive'] - 'passive' (sorts performed on call to data) or 'active' (after updates) + * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here) + * @see {@link Collection#addDynamicView} to construct instances of DynamicView + */ + function DynamicView(collection, name, options) { + this.collection = collection; + this.name = name; + this.rebuildPending = false; + this.options = options || {}; + + if (!this.options.hasOwnProperty('persistent')) { + this.options.persistent = false; + } + + // 'persistentSortPriority': + // 'passive' will defer the sort phase until they call data(). (most efficient overall) + // 'active' will sort async whenever next idle. (prioritizes read speeds) + if (!this.options.hasOwnProperty('sortPriority')) { + this.options.sortPriority = 'passive'; + } + + if (!this.options.hasOwnProperty('minRebuildInterval')) { + this.options.minRebuildInterval = 1; + } + + this.resultset = new Resultset(collection); + this.resultdata = []; + this.resultsdirty = false; + + this.cachedresultset = null; + + // keep ordered filter pipeline + this.filterPipeline = []; + + // sorting member variables + // we only support one active search, applied using applySort() or applySimpleSort() + this.sortFunction = null; + this.sortCriteria = null; + this.sortCriteriaSimple = null; + this.sortDirty = false; + + // for now just have 1 event for when we finally rebuilt lazy view + // once we refactor transactions, i will tie in certain transactional events + + this.events = { + 'rebuild': [] + }; + } + + DynamicView.prototype = new LokiEventEmitter(); + + + /** + * rematerialize() - internally used immediately after deserialization (loading) + * This will clear out and reapply filterPipeline ops, recreating the view. + * Since where filters do not persist correctly, this method allows + * restoring the view to state where user can re-apply those where filters. + * + * @param {Object=} options - (Optional) allows specification of 'removeWhereFilters' option + * @returns {DynamicView} This dynamic view for further chained ops. + * @memberof DynamicView + * @fires DynamicView.rebuild + */ + DynamicView.prototype.rematerialize = function (options) { + var fpl, + fpi, + idx; + + options = options || {}; + + this.resultdata = []; + this.resultsdirty = true; + this.resultset = new Resultset(this.collection); + + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.sortDirty = true; + } + + if (options.hasOwnProperty('removeWhereFilters')) { + // for each view see if it had any where filters applied... since they don't + // serialize those functions lets remove those invalid filters + fpl = this.filterPipeline.length; + fpi = fpl; + while (fpi--) { + if (this.filterPipeline[fpi].type === 'where') { + if (fpi !== this.filterPipeline.length - 1) { + this.filterPipeline[fpi] = this.filterPipeline[this.filterPipeline.length - 1]; + } + + this.filterPipeline.length--; + } + } + } + + // back up old filter pipeline, clear filter pipeline, and reapply pipeline ops + var ofp = this.filterPipeline; + this.filterPipeline = []; + + // now re-apply 'find' filterPipeline ops + fpl = ofp.length; + for (idx = 0; idx < fpl; idx++) { + this.applyFind(ofp[idx].val); + } + + // during creation of unit tests, i will remove this forced refresh and leave lazy + this.data(); + + // emit rebuild event in case user wants to be notified + this.emit('rebuild', this); + + return this; + }; + + /** + * branchResultset() - Makes a copy of the internal resultset for branched queries. + * Unlike this dynamic view, the branched resultset will not be 'live' updated, + * so your branched query should be immediately resolved and not held for future evaluation. + * + * @param {(string|array=)} transform - Optional name of collection transform, or an array of transform steps + * @param {object=} parameters - optional parameters (if optional transform requires them) + * @returns {Resultset} A copy of the internal resultset for branched queries. + * @memberof DynamicView + * @example + * var db = new loki('test'); + * var coll = db.addCollection('mydocs'); + * var dv = coll.addDynamicView('myview'); + * var tx = [ + * { + * type: 'offset', + * value: '[%lktxp]pageStart' + * }, + * { + * type: 'limit', + * value: '[%lktxp]pageSize' + * } + * ]; + * coll.addTransform('viewPaging', tx); + * + * // add some records + * + * var results = dv.branchResultset('viewPaging', { pageStart: 10, pageSize: 10 }).data(); + */ + DynamicView.prototype.branchResultset = function (transform, parameters) { + var rs = this.resultset.branch(); + + if (typeof transform === 'undefined') { + return rs; + } + + return rs.transform(transform, parameters); + }; + + /** + * toJSON() - Override of toJSON to avoid circular references + * + */ + DynamicView.prototype.toJSON = function () { + var copy = new DynamicView(this.collection, this.name, this.options); + + copy.resultset = this.resultset; + copy.resultdata = []; // let's not save data (copy) to minimize size + copy.resultsdirty = true; + copy.filterPipeline = this.filterPipeline; + copy.sortFunction = this.sortFunction; + copy.sortCriteria = this.sortCriteria; + copy.sortCriteriaSimple = this.sortCriteriaSimple || null; + copy.sortDirty = this.sortDirty; + + // avoid circular reference, reapply in db.loadJSON() + copy.collection = null; + + return copy; + }; + + /** + * removeFilters() - Used to clear pipeline and reset dynamic view to initial state. + * Existing options should be retained. + * @param {object=} options - configure removeFilter behavior + * @param {boolean=} options.queueSortPhase - (default: false) if true we will async rebuild view (maybe set default to true in future?) + * @memberof DynamicView + */ + DynamicView.prototype.removeFilters = function (options) { + options = options || {}; + + this.rebuildPending = false; + this.resultset.reset(); + this.resultdata = []; + this.resultsdirty = true; + + this.cachedresultset = null; + + // keep ordered filter pipeline + this.filterPipeline = []; + + // sorting member variables + // we only support one active search, applied using applySort() or applySimpleSort() + this.sortFunction = null; + this.sortCriteria = null; + this.sortCriteriaSimple = null; + this.sortDirty = false; + + if (options.queueSortPhase === true) { + this.queueSortPhase(); + } + }; + + /** + * applySort() - Used to apply a sort to the dynamic view + * @example + * dv.applySort(function(obj1, obj2) { + * if (obj1.name === obj2.name) return 0; + * if (obj1.name > obj2.name) return 1; + * if (obj1.name < obj2.name) return -1; + * }); + * + * @param {function} comparefun - a javascript compare function used for sorting + * @returns {DynamicView} this DynamicView object, for further chain ops. + * @memberof DynamicView + */ + DynamicView.prototype.applySort = function (comparefun) { + this.sortFunction = comparefun; + this.sortCriteria = null; + this.sortCriteriaSimple = null; + + this.queueSortPhase(); + + return this; + }; + + /** + * applySimpleSort() - Used to specify a property used for view translation. + * @example + * dv.applySimpleSort("name"); + * + * @param {string} propname - Name of property by which to sort. + * @param {object|boolean=} options - boolean for sort descending or options object + * @param {boolean} [options.desc=false] - whether we should sort descending. + * @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection. + * @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists). + * @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort. + * @returns {DynamicView} this DynamicView object, for further chain ops. + * @memberof DynamicView + */ + DynamicView.prototype.applySimpleSort = function (propname, options) { + this.sortCriteriaSimple = { propname: propname, options: options || false }; + this.sortCriteria = null; + this.sortFunction = null; + + this.queueSortPhase(); + + return this; + }; + + /** + * applySortCriteria() - Allows sorting a resultset based on multiple columns. + * @example + * // to sort by age and then name (both ascending) + * dv.applySortCriteria(['age', 'name']); + * // to sort by age (ascending) and then by name (descending) + * dv.applySortCriteria(['age', ['name', true]); + * // to sort by age (descending) and then by name (descending) + * dv.applySortCriteria(['age', true], ['name', true]); + * + * @param {array} properties - array of property names or subarray of [propertyname, isdesc] used evaluate sort order + * @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations. + * @memberof DynamicView + */ + DynamicView.prototype.applySortCriteria = function (criteria) { + this.sortCriteria = criteria; + this.sortCriteriaSimple = null; + this.sortFunction = null; + + this.queueSortPhase(); + + return this; + }; + + /** + * startTransaction() - marks the beginning of a transaction. + * + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + DynamicView.prototype.startTransaction = function () { + this.cachedresultset = this.resultset.copy(); + + return this; + }; + + /** + * commit() - commits a transaction. + * + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + DynamicView.prototype.commit = function () { + this.cachedresultset = null; + + return this; + }; + + /** + * rollback() - rolls back a transaction. + * + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + DynamicView.prototype.rollback = function () { + this.resultset = this.cachedresultset; + + if (this.options.persistent) { + // for now just rebuild the persistent dynamic view data in this worst case scenario + // (a persistent view utilizing transactions which get rolled back), we already know the filter so not too bad. + this.resultdata = this.resultset.data(); + + this.emit('rebuild', this); + } + + return this; + }; + + + /** + * Implementation detail. + * _indexOfFilterWithId() - Find the index of a filter in the pipeline, by that filter's ID. + * + * @param {(string|number)} uid - The unique ID of the filter. + * @returns {number}: index of the referenced filter in the pipeline; -1 if not found. + */ + DynamicView.prototype._indexOfFilterWithId = function (uid) { + if (typeof uid === 'string' || typeof uid === 'number') { + for (var idx = 0, len = this.filterPipeline.length; idx < len; idx += 1) { + if (uid === this.filterPipeline[idx].uid) { + return idx; + } + } + } + return -1; + }; + + /** + * Implementation detail. + * _addFilter() - Add the filter object to the end of view's filter pipeline and apply the filter to the resultset. + * + * @param {object} filter - The filter object. Refer to applyFilter() for extra details. + */ + DynamicView.prototype._addFilter = function (filter) { + this.filterPipeline.push(filter); + this.resultset[filter.type](filter.val); + }; + + /** + * reapplyFilters() - Reapply all the filters in the current pipeline. + * + * @returns {DynamicView} this DynamicView object, for further chain ops. + */ + DynamicView.prototype.reapplyFilters = function () { + this.resultset.reset(); + + this.cachedresultset = null; + if (this.options.persistent) { + this.resultdata = []; + this.resultsdirty = true; + } + + var filters = this.filterPipeline; + this.filterPipeline = []; + + for (var idx = 0, len = filters.length; idx < len; idx += 1) { + this._addFilter(filters[idx]); + } + + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + + return this; + }; + + /** + * applyFilter() - Adds or updates a filter in the DynamicView filter pipeline + * + * @param {object} filter - A filter object to add to the pipeline. + * The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id } + * @returns {DynamicView} this DynamicView object, for further chain ops. + * @memberof DynamicView + */ + DynamicView.prototype.applyFilter = function (filter) { + var idx = this._indexOfFilterWithId(filter.uid); + if (idx >= 0) { + this.filterPipeline[idx] = filter; + return this.reapplyFilters(); + } + + this.cachedresultset = null; + if (this.options.persistent) { + this.resultdata = []; + this.resultsdirty = true; + } + + this._addFilter(filter); + + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + + return this; + }; + + /** + * applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline + * + * @param {object} query - A mongo-style query object to apply to pipeline + * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future. + * @returns {DynamicView} this DynamicView object, for further chain ops. + * @memberof DynamicView + */ + DynamicView.prototype.applyFind = function (query, uid) { + this.applyFilter({ + type: 'find', + val: query, + uid: uid + }); + return this; + }; + + /** + * applyWhere() - Adds or updates a javascript filter function in the DynamicView filter pipeline + * + * @param {function} fun - A javascript filter function to apply to pipeline + * @param {(string|number)=} uid - Optional: The unique ID of this filter, to reference it in the future. + * @returns {DynamicView} this DynamicView object, for further chain ops. + * @memberof DynamicView + */ + DynamicView.prototype.applyWhere = function (fun, uid) { + this.applyFilter({ + type: 'where', + val: fun, + uid: uid + }); + return this; + }; + + /** + * removeFilter() - Remove the specified filter from the DynamicView filter pipeline + * + * @param {(string|number)} uid - The unique ID of the filter to be removed. + * @returns {DynamicView} this DynamicView object, for further chain ops. + * @memberof DynamicView + */ + DynamicView.prototype.removeFilter = function (uid) { + var idx = this._indexOfFilterWithId(uid); + if (idx < 0) { + throw new Error("Dynamic view does not contain a filter with ID: " + uid); + } + + this.filterPipeline.splice(idx, 1); + this.reapplyFilters(); + return this; + }; + + /** + * count() - returns the number of documents representing the current DynamicView contents. + * + * @returns {number} The number of documents representing the current DynamicView contents. + * @memberof DynamicView + */ + DynamicView.prototype.count = function () { + // in order to be accurate we will pay the minimum cost (and not alter dv state management) + // recurring resultset data resolutions should know internally its already up to date. + // for persistent data this will not update resultdata nor fire rebuild event. + if (this.resultsdirty) { + this.resultdata = this.resultset.data(); + } + + return this.resultset.count(); + }; + + /** + * data() - resolves and pending filtering and sorting, then returns document array as result. + * + * @param {object=} options - optional parameters to pass to resultset.data() if non-persistent + * @param {boolean} options.forceClones - Allows forcing the return of cloned objects even when + * the collection is not configured for clone object. + * @param {string} options.forceCloneMethod - Allows overriding the default or collection specified cloning method. + * Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param {bool} options.removeMeta - Will force clones and strip $loki and meta properties from documents + * @returns {array} An array of documents representing the current DynamicView contents. + * @memberof DynamicView + */ + DynamicView.prototype.data = function (options) { + // using final sort phase as 'catch all' for a few use cases which require full rebuild + if (this.sortDirty || this.resultsdirty) { + this.performSortPhase({ + suppressRebuildEvent: true + }); + } + return (this.options.persistent) ? (this.resultdata) : (this.resultset.data(options)); + }; + + /** + * queueRebuildEvent() - When the view is not sorted we may still wish to be notified of rebuild events. + * This event will throttle and queue a single rebuild event when batches of updates affect the view. + */ + DynamicView.prototype.queueRebuildEvent = function () { + if (this.rebuildPending) { + return; + } + this.rebuildPending = true; + + var self = this; + setTimeout(function () { + if (self.rebuildPending) { + self.rebuildPending = false; + self.emit('rebuild', self); + } + }, this.options.minRebuildInterval); + }; + + /** + * queueSortPhase : If the view is sorted we will throttle sorting to either : + * (1) passive - when the user calls data(), or + * (2) active - once they stop updating and yield js thread control + */ + DynamicView.prototype.queueSortPhase = function () { + // already queued? exit without queuing again + if (this.sortDirty) { + return; + } + this.sortDirty = true; + + var self = this; + if (this.options.sortPriority === "active") { + // active sorting... once they are done and yield js thread, run async performSortPhase() + setTimeout(function () { + self.performSortPhase(); + }, this.options.minRebuildInterval); + } else { + // must be passive sorting... since not calling performSortPhase (until data call), lets use queueRebuildEvent to + // potentially notify user that data has changed. + this.queueRebuildEvent(); + } + }; + + /** + * performSortPhase() - invoked synchronously or asynchronously to perform final sort phase (if needed) + * + */ + DynamicView.prototype.performSortPhase = function (options) { + // async call to this may have been pre-empted by synchronous call to data before async could fire + if (!this.sortDirty && !this.resultsdirty) { + return; + } + + options = options || {}; + + if (this.sortDirty) { + if (this.sortFunction) { + this.resultset.sort(this.sortFunction); + } else if (this.sortCriteria) { + this.resultset.compoundsort(this.sortCriteria); + } else if (this.sortCriteriaSimple) { + this.resultset.simplesort(this.sortCriteriaSimple.propname, this.sortCriteriaSimple.options); + } + + this.sortDirty = false; + } + + if (this.options.persistent) { + // persistent view, rebuild local resultdata array + this.resultdata = this.resultset.data(); + this.resultsdirty = false; + } + + if (!options.suppressRebuildEvent) { + this.emit('rebuild', this); + } + }; + + /** + * evaluateDocument() - internal method for (re)evaluating document inclusion. + * Called by : collection.insert() and collection.update(). + * + * @param {int} objIndex - index of document to (re)run through filter pipeline. + * @param {bool} isNew - true if the document was just added to the collection. + */ + DynamicView.prototype.evaluateDocument = function (objIndex, isNew) { + // if no filter applied yet, the result 'set' should remain 'everything' + if (!this.resultset.filterInitialized) { + if (this.options.persistent) { + this.resultdata = this.resultset.data(); + } + // need to re-sort to sort new document + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + return; + } + + var ofr = this.resultset.filteredrows; + var oldPos = (isNew) ? (-1) : (ofr.indexOf(+objIndex)); + var oldlen = ofr.length; + + // creating a 1-element resultset to run filter chain ops on to see if that doc passes filters; + // mostly efficient algorithm, slight stack overhead price (this function is called on inserts and updates) + var evalResultset = new Resultset(this.collection); + evalResultset.filteredrows = [objIndex]; + evalResultset.filterInitialized = true; + var filter; + for (var idx = 0, len = this.filterPipeline.length; idx < len; idx++) { + filter = this.filterPipeline[idx]; + evalResultset[filter.type](filter.val); + } + + // not a true position, but -1 if not pass our filter(s), 0 if passed filter(s) + var newPos = (evalResultset.filteredrows.length === 0) ? -1 : 0; + + // wasn't in old, shouldn't be now... do nothing + if (oldPos === -1 && newPos === -1) return; + + // wasn't in resultset, should be now... add + if (oldPos === -1 && newPos !== -1) { + ofr.push(objIndex); + + if (this.options.persistent) { + this.resultdata.push(this.collection.data[objIndex]); + } + + // need to re-sort to sort new document + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + + return; + } + + // was in resultset, shouldn't be now... delete + if (oldPos !== -1 && newPos === -1) { + if (oldPos < oldlen - 1) { + ofr.splice(oldPos, 1); + + if (this.options.persistent) { + this.resultdata.splice(oldPos, 1); + } + } else { + ofr.length = oldlen - 1; + + if (this.options.persistent) { + this.resultdata.length = oldlen - 1; + } + } + + // in case changes to data altered a sort column + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + + return; + } + + // was in resultset, should still be now... (update persistent only?) + if (oldPos !== -1 && newPos !== -1) { + if (this.options.persistent) { + // in case document changed, replace persistent view data with the latest collection.data document + this.resultdata[oldPos] = this.collection.data[objIndex]; + } + + // in case changes to data altered a sort column + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + + return; + } + }; + + /** + * removeDocument() - internal function called on collection.delete() + * @param {number|number[]} objIndex - index of document to (re)run through filter pipeline. + */ + DynamicView.prototype.removeDocument = function (objIndex) { + var idx, rmidx, rmlen, rxo = {}, fxo = {}; + var adjels = []; + var drs = this.resultset; + var fr = this.resultset.filteredrows; + var frlen = fr.length; + + // if no filter applied yet, the result 'set' should remain 'everything' + if (!this.resultset.filterInitialized) { + if (this.options.persistent) { + this.resultdata = this.resultset.data(); + } + // in case changes to data altered a sort column + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + return; + } + + // if passed single index, wrap in array + if (!Array.isArray(objIndex)) { + objIndex = [objIndex]; + } + + rmlen = objIndex.length; + // create intersection object of data indices to remove + for(rmidx=0;rmidx 0) { + // remove them from filtered rows + this.resultset.filteredrows = this.resultset.filteredrows.filter(function(di, idx) { return !fxo[idx]; }); + // if persistent... + if (this.options.persistent) { + // remove from resultdata + this.resultdata = this.resultdata.filter(function(obj, idx) { return !fxo[idx]; }); + } + + // and queue sorts + if (this.sortFunction || this.sortCriteria || this.sortCriteriaSimple) { + this.queueSortPhase(); + } else { + this.queueRebuildEvent(); + } + } + + // to remove holes, we need to 'shift down' indices, this filter function finds number of positions to shift + var filt = function(idx) { return function(di) { return di < drs.filteredrows[idx]; }; }; + + frlen = drs.filteredrows.length; + for (idx = 0; idx < frlen; idx++) { + // grab subset of removed elements where data index is less than current filtered row data index; + // use this to determine how many positions iterated remaining data index needs to be 'shifted down' + adjels = objIndex.filter(filt(idx)); + drs.filteredrows[idx] -= adjels.length; + } + }; + + /** + * mapReduce() - data transformation via user supplied functions + * + * @param {function} mapFunction - this function accepts a single document for you to transform and return + * @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value + * @returns The output of your reduceFunction + * @memberof DynamicView + */ + DynamicView.prototype.mapReduce = function (mapFunction, reduceFunction) { + try { + return reduceFunction(this.data().map(mapFunction)); + } catch (err) { + throw err; + } + }; + + + /** + * Collection class that handles documents of same type + * @constructor Collection + * @implements LokiEventEmitter + * @param {string} name - collection name + * @param {(array|object)=} options - (optional) array of property names to be indicized OR a configuration object + * @param {array=} [options.unique=[]] - array of property names to define unique constraints for + * @param {array=} [options.exact=[]] - array of property names to define exact constraints for + * @param {array=} [options.indices=[]] - array property names to define binary indexes for + * @param {boolean} [options.adaptiveBinaryIndices=true] - collection indices will be actively rebuilt rather than lazily + * @param {boolean} [options.asyncListeners=false] - whether listeners are invoked asynchronously + * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents + * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes API + * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning) + * @param {boolean} [options.autoupdate=false] - use Object.observe to update objects automatically + * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user + * @param {boolean} [options.serializableIndices=true[]] - converts date values on binary indexed properties to epoch time + * @param {string} [options.cloneMethod='parse-stringify'] - 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign' + * @param {int=} options.ttl - age of document (in ms.) before document is considered aged/stale. + * @param {int=} options.ttlInterval - time interval for clearing out 'aged' documents; not set by default. + * @see {@link Loki#addCollection} for normal creation of collections + */ + function Collection(name, options) { + // the name of the collection + + this.name = name; + // the data held by the collection + this.data = []; + this.idIndex = []; // index of id + this.binaryIndices = {}; // user defined indexes + this.constraints = { + unique: {}, + exact: {} + }; + + // unique contraints contain duplicate object references, so they are not persisted. + // we will keep track of properties which have unique contraint applied here, and regenerate on load + this.uniqueNames = []; + + // transforms will be used to store frequently used query chains as a series of steps + // which itself can be stored along with the database. + this.transforms = {}; + + // the object type of the collection + this.objType = name; + + // in autosave scenarios we will use collection level dirty flags to determine whether save is needed. + // currently, if any collection is dirty we will autosave the whole database if autosave is configured. + // defaulting to true since this is called from addCollection and adding a collection should trigger save + this.dirty = true; + + // private holders for cached data + this.cachedIndex = null; + this.cachedBinaryIndex = null; + this.cachedData = null; + var self = this; + + /* OPTIONS */ + options = options || {}; + + // exact match and unique constraints + if (options.hasOwnProperty('unique')) { + if (!Array.isArray(options.unique)) { + options.unique = [options.unique]; + } + options.unique.forEach(function (prop) { + self.uniqueNames.push(prop); // used to regenerate on subsequent database loads + self.constraints.unique[prop] = new UniqueIndex(prop); + }); + } + + if (options.hasOwnProperty('exact')) { + options.exact.forEach(function (prop) { + self.constraints.exact[prop] = new ExactIndex(prop); + }); + } + + // if set to true we will optimally keep indices 'fresh' during insert/update/remove ops (never dirty/never needs rebuild) + // if you frequently intersperse insert/update/remove ops between find ops this will likely be significantly faster option. + this.adaptiveBinaryIndices = options.hasOwnProperty('adaptiveBinaryIndices') ? options.adaptiveBinaryIndices : true; + + // is collection transactional + this.transactional = options.hasOwnProperty('transactional') ? options.transactional : false; + + // options to clone objects when inserting them + this.cloneObjects = options.hasOwnProperty('clone') ? options.clone : false; + + // default clone method (if enabled) is parse-stringify + this.cloneMethod = options.hasOwnProperty('cloneMethod') ? options.cloneMethod : "parse-stringify"; + + // option to make event listeners async, default is sync + this.asyncListeners = options.hasOwnProperty('asyncListeners') ? options.asyncListeners : false; + + // if set to true we will not maintain a meta property for a document + this.disableMeta = options.hasOwnProperty('disableMeta') ? options.disableMeta : false; + + // disable track changes + this.disableChangesApi = options.hasOwnProperty('disableChangesApi') ? options.disableChangesApi : true; + + // disable delta update object style on changes + this.disableDeltaChangesApi = options.hasOwnProperty('disableDeltaChangesApi') ? options.disableDeltaChangesApi : true; + if (this.disableChangesApi) { this.disableDeltaChangesApi = true; } + + // option to observe objects and update them automatically, ignored if Object.observe is not supported + this.autoupdate = options.hasOwnProperty('autoupdate') ? options.autoupdate : false; + + // by default, if you insert a document into a collection with binary indices, if those indexed properties contain + // a DateTime we will convert to epoch time format so that (across serializations) its value position will be the + // same 'after' serialization as it was 'before'. + this.serializableIndices = options.hasOwnProperty('serializableIndices') ? options.serializableIndices : true; + + //option to activate a cleaner daemon - clears "aged" documents at set intervals. + this.ttl = { + age: null, + ttlInterval: null, + daemon: null + }; + this.setTTL(options.ttl || -1, options.ttlInterval); + + // currentMaxId - change manually at your own peril! + this.maxId = 0; + + this.DynamicViews = []; + + // events + this.events = { + 'insert': [], + 'update': [], + 'pre-insert': [], + 'pre-update': [], + 'close': [], + 'flushbuffer': [], + 'error': [], + 'delete': [], + 'warning': [] + }; + + // changes are tracked by collection and aggregated by the db + this.changes = []; + + // initialize the id index + this.ensureId(); + var indices = []; + // initialize optional user-supplied indices array ['age', 'lname', 'zip'] + if (options && options.indices) { + if (Object.prototype.toString.call(options.indices) === '[object Array]') { + indices = options.indices; + } else if (typeof options.indices === 'string') { + indices = [options.indices]; + } else { + throw new TypeError('Indices needs to be a string or an array of strings'); + } + } + + for (var idx = 0; idx < indices.length; idx++) { + this.ensureIndex(indices[idx]); + } + + function observerCallback(changes) { + + var changedObjects = typeof Set === 'function' ? new Set() : []; + + if (!changedObjects.add) + changedObjects.add = function (object) { + if (this.indexOf(object) === -1) + this.push(object); + return this; + }; + + changes.forEach(function (change) { + changedObjects.add(change.object); + }); + + changedObjects.forEach(function (object) { + if (!hasOwnProperty.call(object, '$loki')) + return self.removeAutoUpdateObserver(object); + try { + self.update(object); + } catch (err) {} + }); + } + + this.observerCallback = observerCallback; + + //Compare changed object (which is a forced clone) with existing object and return the delta + function getChangeDelta(obj, old) { + if (old) { + return getObjectDelta(old, obj); + } + else { + return JSON.parse(JSON.stringify(obj)); + } + } + + this.getChangeDelta = getChangeDelta; + + function getObjectDelta(oldObject, newObject) { + var propertyNames = newObject !== null && typeof newObject === 'object' ? Object.keys(newObject) : null; + if (propertyNames && propertyNames.length && ['string', 'boolean', 'number'].indexOf(typeof(newObject)) < 0) { + var delta = {}; + for (var i = 0; i < propertyNames.length; i++) { + var propertyName = propertyNames[i]; + if (newObject.hasOwnProperty(propertyName)) { + if (!oldObject.hasOwnProperty(propertyName) || self.uniqueNames.indexOf(propertyName) >= 0 || propertyName == '$loki' || propertyName == 'meta') { + delta[propertyName] = newObject[propertyName]; + } + else { + var propertyDelta = getObjectDelta(oldObject[propertyName], newObject[propertyName]); + if (typeof propertyDelta !== "undefined" && propertyDelta != {}) { + delta[propertyName] = propertyDelta; + } + } + } + } + return Object.keys(delta).length === 0 ? undefined : delta; + } + else { + return oldObject === newObject ? undefined : newObject; + } + } + + this.getObjectDelta = getObjectDelta; + + // clear all the changes + function flushChanges() { + self.changes = []; + } + + this.getChanges = function () { + return self.changes; + }; + + this.flushChanges = flushChanges; + + this.setChangesApi = function (enabled) { + self.disableChangesApi = !enabled; + if (!enabled) { self.disableDeltaChangesApi = false; } + }; + + this.on('delete', function deleteCallback(obj) { + if (!self.disableChangesApi) { + self.createChange(self.name, 'R', obj); + } + }); + + this.on('warning', function (warning) { + self.console.warn(warning); + }); + // for de-serialization purposes + flushChanges(); + } + + Collection.prototype = new LokiEventEmitter(); + + /* + * For ChangeAPI default to clone entire object, for delta changes create object with only differences (+ $loki and meta) + */ + Collection.prototype.createChange = function(name, op, obj, old) { + this.changes.push({ + name: name, + operation: op, + obj: op == 'U' && !this.disableDeltaChangesApi ? this.getChangeDelta(obj, old) : JSON.parse(JSON.stringify(obj)) + }); + }; + + Collection.prototype.insertMeta = function(obj) { + var len, idx; + + if (this.disableMeta || !obj) { + return; + } + + // if batch insert + if (Array.isArray(obj)) { + len = obj.length; + + for(idx=0; idx 0) { + * results.forEach(function(name) { + * console.log('problem encountered with index : ' + name); + * }); + * } + */ + Collection.prototype.checkAllIndexes = function (options) { + var key, bIndices = this.binaryIndices; + var results = [], result; + + for (key in bIndices) { + if (hasOwnProperty.call(bIndices, key)) { + result = this.checkIndex(key, options); + if (!result) { + results.push(key); + } + } + } + + return results; + }; + + /** + * Perform checks to determine validity/consistency of a binary index + * @param {string} property - name of the binary-indexed property to check + * @param {object=} options - optional configuration object + * @param {boolean} [options.randomSampling=false] - whether (faster) random sampling should be used + * @param {number} [options.randomSamplingFactor=0.10] - percentage of total rows to randomly sample + * @param {boolean} [options.repair=false] - whether to fix problems if they are encountered + * @returns {boolean} whether the index was found to be valid (before optional correcting). + * @memberof Collection + * @example + * // full test + * var valid = coll.checkIndex('name'); + * // full test with repair (if issues found) + * valid = coll.checkIndex('name', { repair: true }); + * // random sampling (default is 10% of total document count) + * valid = coll.checkIndex('name', { randomSampling: true }); + * // random sampling (sample 20% of total document count) + * valid = coll.checkIndex('name', { randomSampling: true, randomSamplingFactor: 0.20 }); + * // random sampling (implied boolean) + * valid = coll.checkIndex('name', { randomSamplingFactor: 0.20 }); + * // random sampling with repair (if issues found) + * valid = coll.checkIndex('name', { repair: true, randomSampling: true }); + */ + Collection.prototype.checkIndex = function (property, options) { + options = options || {}; + // if 'randomSamplingFactor' specified but not 'randomSampling', assume true + if (options.randomSamplingFactor && options.randomSampling !== false) { + options.randomSampling = true; + } + options.randomSamplingFactor = options.randomSamplingFactor || 0.1; + if (options.randomSamplingFactor < 0 || options.randomSamplingFactor > 1) { + options.randomSamplingFactor = 0.1; + } + + var valid=true, idx, iter, pos, len, biv; + + // make sure we are passed a valid binary index name + if (!this.binaryIndices.hasOwnProperty(property)) { + throw new Error("called checkIndex on property without an index: " + property); + } + + // if lazy indexing, rebuild only if flagged as dirty + if (!this.adaptiveBinaryIndices) { + this.ensureIndex(property); + } + + biv = this.binaryIndices[property].values; + len = biv.length; + + // if the index has an incorrect number of values + if (len !== this.data.length) { + if (options.repair) { + this.ensureIndex(property, true); + } + return false; + } + + if (len === 0) { + return true; + } + + if (len === 1) { + valid = (biv[0] === 0); + } + else { + if (options.randomSampling) { + // validate first and last + if (!LokiOps.$lte(this.data[biv[0]][property], this.data[biv[1]][property])) { + valid=false; + } + if (!LokiOps.$lte(this.data[biv[len-2]][property], this.data[biv[len-1]][property])) { + valid=false; + } + + // if first and last positions are sorted correctly with their nearest neighbor, + // continue onto random sampling phase... + if (valid) { + // # random samplings = total count * sampling factor + iter = Math.floor((len-1) * options.randomSamplingFactor); + + // for each random sampling, validate that the binary index is sequenced properly + // with next higher value. + for(idx=0; idx 0; + + if (adaptiveBatchOverride) { + this.adaptiveBinaryIndices = false; + } + + try { + for (k=0; k < len; k += 1) { + this.update(doc[k]); + } + } + finally { + if (adaptiveBatchOverride) { + this.ensureAllIndexes(); + this.adaptiveBinaryIndices = true; + } + } + + return; + } + + // verify object is a properly formed document + if (!hasOwnProperty.call(doc, '$loki')) { + throw new Error('Trying to update unsynced document. Please save the document first by using insert() or addMany()'); + } + try { + this.startTransaction(); + var arr = this.get(doc.$loki, true), + oldInternal, // ref to existing obj + newInternal, // ref to new internal obj + position, + self = this; + + if (!arr) { + throw new Error('Trying to update a document not in collection.'); + } + + oldInternal = arr[0]; // -internal- obj ref + position = arr[1]; // position in data array + + // if configured to clone, do so now... otherwise just use same obj reference + newInternal = this.cloneObjects || !this.disableDeltaChangesApi ? clone(doc, this.cloneMethod) : doc; + + this.emit('pre-update', doc); + + Object.keys(this.constraints.unique).forEach(function (key) { + self.constraints.unique[key].update(oldInternal, newInternal); + }); + + // operate the update + this.data[position] = newInternal; + + if (newInternal !== doc) { + this.addAutoUpdateObserver(doc); + } + + // now that we can efficiently determine the data[] position of newly added document, + // submit it for all registered DynamicViews to evaluate for inclusion/exclusion + for (var idx = 0; idx < this.DynamicViews.length; idx++) { + this.DynamicViews[idx].evaluateDocument(position, false); + } + + var key; + if (this.adaptiveBinaryIndices) { + // for each binary index defined in collection, immediately update rather than flag for lazy rebuild + var bIndices = this.binaryIndices; + for (key in bIndices) { + this.adaptiveBinaryIndexUpdate(position, key); + } + } + else { + this.flagBinaryIndexesDirty(); + } + + this.idIndex[position] = newInternal.$loki; + //this.flagBinaryIndexesDirty(); + + this.commit(); + this.dirty = true; // for autosave scenarios + + // update meta and store changes if ChangesAPI is enabled + if (this.disableChangesApi) { + this.updateMeta(newInternal, null); + } + else { + this.updateMetaWithChange(newInternal, oldInternal); + } + + var returnObj; + + // if cloning is enabled, emit 'update' event and return with clone of new object + if (this.cloneObjects) { + returnObj = clone(newInternal, this.cloneMethod); + } + else { + returnObj = newInternal; + } + + this.emit('update', returnObj, oldInternal); + return returnObj; + } catch (err) { + this.rollback(); + this.console.error(err.message); + this.emit('error', err); + throw (err); // re-throw error so user does not think it succeeded + } + }; + + /** + * Add object to collection + */ + Collection.prototype.add = function (obj) { + // if parameter isn't object exit with throw + if ('object' !== typeof obj) { + throw new TypeError('Object being added needs to be an object'); + } + // if object you are adding already has id column it is either already in the collection + // or the object is carrying its own 'id' property. If it also has a meta property, + // then this is already in collection so throw error, otherwise rename to originalId and continue adding. + if (typeof (obj.$loki) !== 'undefined') { + throw new Error('Document is already in collection, please use update()'); + } + + /* + * try adding object to collection + */ + try { + this.startTransaction(); + this.maxId++; + + if (isNaN(this.maxId)) { + this.maxId = (this.data[this.data.length - 1].$loki + 1); + } + + obj.$loki = this.maxId; + + if (!this.disableMeta) { + obj.meta.version = 0; + } + + var key, constrUnique = this.constraints.unique; + for (key in constrUnique) { + if (hasOwnProperty.call(constrUnique, key)) { + constrUnique[key].set(obj); + } + } + + // add new obj id to idIndex + this.idIndex.push(obj.$loki); + + // add the object + this.data.push(obj); + + var addedPos = this.data.length - 1; + + // now that we can efficiently determine the data[] position of newly added document, + // submit it for all registered DynamicViews to evaluate for inclusion/exclusion + var dvlen = this.DynamicViews.length; + for (var i = 0; i < dvlen; i++) { + this.DynamicViews[i].evaluateDocument(addedPos, true); + } + + if (this.adaptiveBinaryIndices) { + // for each binary index defined in collection, immediately update rather than flag for lazy rebuild + var bIndices = this.binaryIndices; + for (key in bIndices) { + this.adaptiveBinaryIndexInsert(addedPos, key); + } + } + else { + this.flagBinaryIndexesDirty(); + } + + this.commit(); + this.dirty = true; // for autosave scenarios + + return (this.cloneObjects) ? (clone(obj, this.cloneMethod)) : (obj); + } catch (err) { + this.rollback(); + this.console.error(err.message); + this.emit('error', err); + throw (err); // re-throw error so user does not think it succeeded + } + }; + + /** + * Applies a filter function and passes all results to an update function. + * + * @param {function} filterFunction - filter function whose results will execute update + * @param {function} updateFunction - update function to run against filtered documents + * @memberof Collection + */ + Collection.prototype.updateWhere = function(filterFunction, updateFunction) { + var results = this.where(filterFunction), + i = 0, + obj; + try { + for (i; i < results.length; i++) { + obj = updateFunction(results[i]); + this.update(obj); + } + + } catch (err) { + this.rollback(); + this.console.error(err.message); + } + }; + + /** + * Remove all documents matching supplied filter function. + * For 'mongo-like' querying you should migrate to [findAndRemove()]{@link Collection#findAndRemove}. + * @param {function|object} query - query object to filter on + * @memberof Collection + */ + Collection.prototype.removeWhere = function (query) { + var list; + if (typeof query === 'function') { + list = this.data.filter(query); + this.remove(list); + } else { + this.chain().find(query).remove(); + } + }; + + Collection.prototype.removeDataOnly = function () { + this.remove(this.data.slice()); + }; + + /** + * Internal method to remove a batch of documents from the collection. + * @param {number[]} positions - data/idIndex positions to remove + */ + Collection.prototype.removeBatchByPositions = function(positions) { + var len = positions.length; + var xo = {}; + var dlen, didx, idx; + var bic=Object.keys(this.binaryIndices).length; + var uic=Object.keys(this.constraints.unique).length; + var adaptiveOverride = this.adaptiveBinaryIndices && Object.keys(this.binaryIndices).length > 0; + var doc, self=this; + + try { + this.startTransaction(); + + // create hashobject for positional removal inclusion tests... + // all keys defined in this hashobject represent $loki ids of the documents to remove. + for(idx=0; idx < len; idx++) { + xo[this.idIndex[positions[idx]]] = true; + } + + // if we will need to notify dynamic views and/or binary indices to update themselves... + dlen = this.DynamicViews.length; + if ((dlen > 0) || (bic > 0) || (uic > 0)) { + if (dlen > 0) { + // notify dynamic views to remove relevant documents at data positions + for (didx = 0; didx < dlen; didx++) { + // notify dv of remove (passing batch/array of positions) + this.DynamicViews[didx].removeDocument(positions); + } + } + + // notify binary indices to update + if (this.adaptiveBinaryIndices && !adaptiveOverride) { + // for each binary index defined in collection, immediately update rather than flag for lazy rebuild + var key, bIndices = this.binaryIndices; + + for (key in bIndices) { + this.adaptiveBinaryIndexRemove(positions, key); + } + } + else { + this.flagBinaryIndexesDirty(); + } + + if (uic) { + Object.keys(this.constraints.unique).forEach(function (key) { + for(idx=0; idx < len; idx++) { + doc = self.data[positions[idx]]; + if (doc[key] !== null && doc[key] !== undefined) { + self.constraints.unique[key].remove(doc[key]); + } + } + }); + } + } + + // emit 'delete' events only of listeners are attached. + // since data not removed yet, in future we can emit single delete event with array... + // for now that might be breaking change to put in potential 1.6 or LokiDB (lokijs2) version + if (!this.disableChangesApi || this.events.delete.length > 1) { + for(idx=0; idx < len; idx++) { + this.emit('delete', this.data[positions[idx]]); + } + } + + // remove from data[] : + // filter collection data for items not in inclusion hashobject + this.data = this.data.filter(function(obj) { + return !xo[obj.$loki]; + }); + + // remove from idIndex[] : + // filter idIndex for items not in inclusion hashobject + this.idIndex = this.idIndex.filter(function(id) { + return !xo[id]; + }); + + if (this.adaptiveBinaryIndices && adaptiveOverride) { + this.adaptiveBinaryIndices = false; + this.ensureAllIndexes(true); + this.adaptiveBinaryIndices = true; + } + + this.commit(); + + // flag collection as dirty for autosave + this.dirty = true; + } + catch (err) { + this.rollback(); + if (adaptiveOverride) { + this.adaptiveBinaryIndices = true; + } + this.console.error(err.message); + this.emit('error', err); + return null; + } + }; + + /** + * Internal method called by remove() + * @param {object[]|number[]} batch - array of documents or $loki ids to remove + */ + Collection.prototype.removeBatch = function(batch) { + var len = batch.length, + dlen=this.data.length, + idx; + var xlt = {}; + var posx = []; + + // create lookup hashobject to translate $loki id to position + for (idx=0; idx < dlen; idx++) { + xlt[this.data[idx].$loki] = idx; + } + + // iterate the batch + for (idx=0; idx < len; idx++) { + if (typeof(batch[idx]) === 'object') { + posx.push(xlt[batch[idx].$loki]); + } + else { + posx.push(xlt[batch[idx]]); + } + } + + this.removeBatchByPositions(posx); + }; + + /** + * Remove a document from the collection + * @param {object} doc - document to remove from collection + * @memberof Collection + */ + Collection.prototype.remove = function (doc) { + if (typeof doc === 'number') { + doc = this.get(doc); + } + + if ('object' !== typeof doc) { + throw new Error('Parameter is not an object'); + } + if (Array.isArray(doc)) { + this.removeBatch(doc); + return; + } + + if (!hasOwnProperty.call(doc, '$loki')) { + throw new Error('Object is not a document stored in the collection'); + } + + try { + this.startTransaction(); + var arr = this.get(doc.$loki, true), + // obj = arr[0], + position = arr[1]; + var self = this; + Object.keys(this.constraints.unique).forEach(function (key) { + if (doc[key] !== null && typeof doc[key] !== 'undefined') { + self.constraints.unique[key].remove(doc[key]); + } + }); + // now that we can efficiently determine the data[] position of newly added document, + // submit it for all registered DynamicViews to remove + for (var idx = 0; idx < this.DynamicViews.length; idx++) { + this.DynamicViews[idx].removeDocument(position); + } + + if (this.adaptiveBinaryIndices) { + // for each binary index defined in collection, immediately update rather than flag for lazy rebuild + var key, bIndices = this.binaryIndices; + for (key in bIndices) { + this.adaptiveBinaryIndexRemove(position, key); + } + } + else { + this.flagBinaryIndexesDirty(); + } + + this.data.splice(position, 1); + this.removeAutoUpdateObserver(doc); + + // remove id from idIndex + this.idIndex.splice(position, 1); + + this.commit(); + this.dirty = true; // for autosave scenarios + this.emit('delete', arr[0]); + delete doc.$loki; + delete doc.meta; + return doc; + + } catch (err) { + this.rollback(); + this.console.error(err.message); + this.emit('error', err); + return null; + } + }; + + /*---------------------+ + | Finding methods | + +----------------------*/ + + /** + * Get by Id - faster than other methods because of the searching algorithm + * @param {int} id - $loki id of document you want to retrieve + * @param {boolean} returnPosition - if 'true' we will return [object, position] + * @returns {(object|array|null)} Object reference if document was found, null if not, + * or an array if 'returnPosition' was passed. + * @memberof Collection + */ + Collection.prototype.get = function (id, returnPosition) { + var retpos = returnPosition || false, + data = this.idIndex, + max = data.length - 1, + min = 0, + mid = (min + max) >> 1; + + id = typeof id === 'number' ? id : parseInt(id, 10); + + if (isNaN(id)) { + throw new TypeError('Passed id is not an integer'); + } + + while (data[min] < data[max]) { + mid = (min + max) >> 1; + + if (data[mid] < id) { + min = mid + 1; + } else { + max = mid; + } + } + + if (max === min && data[min] === id) { + if (retpos) { + return [this.data[min], min]; + } + return this.data[min]; + } + return null; + + }; + + /** + * Perform binary range lookup for the data[dataPosition][binaryIndexName] property value + * Since multiple documents may contain the same value (which the index is sorted on), + * we hone in on range and then linear scan range to find exact index array position. + * @param {int} dataPosition : coll.data array index/position + * @param {string} binaryIndexName : index to search for dataPosition in + */ + Collection.prototype.getBinaryIndexPosition = function(dataPosition, binaryIndexName) { + var val = this.data[dataPosition][binaryIndexName]; + var index = this.binaryIndices[binaryIndexName].values; + + // i think calculateRange can probably be moved to collection + // as it doesn't seem to need resultset. need to verify + var range = this.calculateRange("$eq", binaryIndexName, val); + + if (range[0] === 0 && range[1] === -1) { + // uhoh didn't find range + return null; + } + + var min = range[0]; + var max = range[1]; + + // narrow down the sub-segment of index values + // where the indexed property value exactly matches our + // value and then linear scan to find exact -index- position + for(var idx = min; idx <= max; idx++) { + if (index[idx] === dataPosition) return idx; + } + + // uhoh + return null; + }; + + /** + * Adaptively insert a selected item to the index. + * @param {int} dataPosition : coll.data array index/position + * @param {string} binaryIndexName : index to search for dataPosition in + */ + Collection.prototype.adaptiveBinaryIndexInsert = function(dataPosition, binaryIndexName) { + var index = this.binaryIndices[binaryIndexName].values; + var val = this.data[dataPosition][binaryIndexName]; + + // If you are inserting a javascript Date value into a binary index, convert to epoch time + if (this.serializableIndices === true && val instanceof Date) { + this.data[dataPosition][binaryIndexName] = val.getTime(); + val = this.data[dataPosition][binaryIndexName]; + } + + var idxPos = (index.length === 0)?0:this.calculateRangeStart(binaryIndexName, val, true); + + // insert new data index into our binary index at the proper sorted location for relevant property calculated by idxPos. + // doing this after adjusting dataPositions so no clash with previous item at that position. + this.binaryIndices[binaryIndexName].values.splice(idxPos, 0, dataPosition); + }; + + /** + * Adaptively update a selected item within an index. + * @param {int} dataPosition : coll.data array index/position + * @param {string} binaryIndexName : index to search for dataPosition in + */ + Collection.prototype.adaptiveBinaryIndexUpdate = function(dataPosition, binaryIndexName) { + // linear scan needed to find old position within index unless we optimize for clone scenarios later + // within (my) node 5.6.0, the following for() loop with strict compare is -much- faster than indexOf() + var idxPos, + index = this.binaryIndices[binaryIndexName].values, + len=index.length; + + for(idxPos=0; idxPos < len; idxPos++) { + if (index[idxPos] === dataPosition) break; + } + + //var idxPos = this.binaryIndices[binaryIndexName].values.indexOf(dataPosition); + this.binaryIndices[binaryIndexName].values.splice(idxPos, 1); + + //this.adaptiveBinaryIndexRemove(dataPosition, binaryIndexName, true); + this.adaptiveBinaryIndexInsert(dataPosition, binaryIndexName); + }; + + /** + * Adaptively remove a selected item from the index. + * @param {number|number[]} dataPosition : coll.data array index/position + * @param {string} binaryIndexName : index to search for dataPosition in + */ + Collection.prototype.adaptiveBinaryIndexRemove = function(dataPosition, binaryIndexName, removedFromIndexOnly) { + var bi = this.binaryIndices[binaryIndexName]; + var len, idx, rmidx, rmlen, rxo = {}; + var curr, shift, idxPos; + + if (Array.isArray(dataPosition)) { + // when called from chained remove, and only one document in array, + // it will be faster to use old algorithm + rmlen = dataPosition.length; + if (rmlen === 1) { + dataPosition = dataPosition[0]; + } + // we were passed an array (batch) of documents so use this 'batch optimized' algorithm + else { + for(rmidx=0;rmidx sortedPositions[rmidx]; rmidx++) { + shift++; + } + bi.values[idx]-=shift; + } + + // batch processed, bail out + return; + } + + // not a batch so continue... + } + + idxPos = this.getBinaryIndexPosition(dataPosition, binaryIndexName); + + if (idxPos === null) { + // throw new Error('unable to determine binary index position'); + return null; + } + + // remove document from index (with splice) + bi.values.splice(idxPos, 1); + + // if we passed this optional flag parameter, we are calling from adaptiveBinaryIndexUpdate, + // in which case data positions stay the same. + if (removedFromIndexOnly === true) { + return; + } + + // since index stores data array positions, if we remove a document + // we need to adjust array positions -1 for all document positions greater than removed position + len = bi.values.length; + for (idx = 0; idx < len; idx++) { + if (bi.values[idx] > dataPosition) { + bi.values[idx]--; + } + } + }; + + /** + * Internal method used for index maintenance and indexed searching. + * Calculates the beginning of an index range for a given value. + * For index maintainance (adaptive:true), we will return a valid index position to insert to. + * For querying (adaptive:false/undefined), we will : + * return lower bound/index of range of that value (if found) + * return next lower index position if not found (hole) + * If index is empty it is assumed to be handled at higher level, so + * this method assumes there is at least 1 document in index. + * + * @param {string} prop - name of property which has binary index + * @param {any} val - value to find within index + * @param {bool?} adaptive - if true, we will return insert position + */ + Collection.prototype.calculateRangeStart = function (prop, val, adaptive) { + var rcd = this.data; + var index = this.binaryIndices[prop].values; + var min = 0; + var max = index.length - 1; + var mid = 0; + + if (index.length === 0) { + return -1; + } + + var minVal = rcd[index[min]][prop]; + var maxVal = rcd[index[max]][prop]; + + // hone in on start position of value + while (min < max) { + mid = (min + max) >> 1; + + if (Comparators.lt(rcd[index[mid]][prop], val, false)) { + min = mid + 1; + } else { + max = mid; + } + } + + var lbound = min; + + // found it... return it + if (Comparators.aeq(val, rcd[index[lbound]][prop])) { + return lbound; + } + + // if not in index and our value is less than the found one + if (Comparators.lt(val, rcd[index[lbound]][prop], false)) { + return adaptive?lbound:lbound-1; + } + + // not in index and our value is greater than the found one + return adaptive?lbound+1:lbound; + }; + + /** + * Internal method used for indexed $between. Given a prop (index name), and a value + * (which may or may not yet exist) this will find the final position of that upper range value. + */ + Collection.prototype.calculateRangeEnd = function (prop, val) { + var rcd = this.data; + var index = this.binaryIndices[prop].values; + var min = 0; + var max = index.length - 1; + var mid = 0; + + if (index.length === 0) { + return -1; + } + + var minVal = rcd[index[min]][prop]; + var maxVal = rcd[index[max]][prop]; + + // hone in on start position of value + while (min < max) { + mid = (min + max) >> 1; + + if (Comparators.lt(val, rcd[index[mid]][prop], false)) { + max = mid; + } else { + min = mid + 1; + } + } + + var ubound = max; + + // only eq if last element in array is our val + if (Comparators.aeq(val, rcd[index[ubound]][prop])) { + return ubound; + } + + // if not in index and our value is less than the found one + if (Comparators.gt(val, rcd[index[ubound]][prop], false)) { + return ubound+1; + } + + // either hole or first nonmatch + if (Comparators.aeq(val, rcd[index[ubound-1]][prop])) { + return ubound-1; + } + + // hole, so ubound if nearest gt than the val we were looking for + return ubound; + }; + + /** + * calculateRange() - Binary Search utility method to find range/segment of values matching criteria. + * this is used for collection.find() and first find filter of resultset/dynview + * slightly different than get() binary search in that get() hones in on 1 value, + * but we have to hone in on many (range) + * @param {string} op - operation, such as $eq + * @param {string} prop - name of property to calculate range for + * @param {object} val - value to use for range calculation. + * @returns {array} [start, end] index array positions + */ + Collection.prototype.calculateRange = function (op, prop, val) { + var rcd = this.data; + var index = this.binaryIndices[prop].values; + var min = 0; + var max = index.length - 1; + var mid = 0; + var lbound, lval; + var ubound, uval; + + // when no documents are in collection, return empty range condition + if (rcd.length === 0) { + return [0, -1]; + } + + var minVal = rcd[index[min]][prop]; + var maxVal = rcd[index[max]][prop]; + + // if value falls outside of our range return [0, -1] to designate no results + switch (op) { + case '$eq': + case '$aeq': + if (Comparators.lt(val, minVal, false) || Comparators.gt(val, maxVal, false)) { + return [0, -1]; + } + break; + case '$dteq': + if (Comparators.lt(val, minVal, false) || Comparators.gt(val, maxVal, false)) { + return [0, -1]; + } + break; + case '$gt': + // none are within range + if (Comparators.gt(val, maxVal, true)) { + return [0, -1]; + } + // all are within range + if (Comparators.gt(minVal, val, false)) { + return [min, max]; + } + break; + case '$gte': + // none are within range + if (Comparators.gt(val, maxVal, false)) { + return [0, -1]; + } + // all are within range + if (Comparators.gt(minVal, val, true)) { + return [min, max]; + } + break; + case '$lt': + // none are within range + if (Comparators.lt(val, minVal, true)) { + return [0, -1]; + } + // all are within range + if (Comparators.lt(maxVal, val, false)) { + return [min, max]; + } + break; + case '$lte': + // none are within range + if (Comparators.lt(val, minVal, false)) { + return [0, -1]; + } + // all are within range + if (Comparators.lt(maxVal, val, true)) { + return [min, max]; + } + break; + case '$between': + // none are within range (low range is greater) + if (Comparators.gt(val[0], maxVal, false)) { + return [0, -1]; + } + // none are within range (high range lower) + if (Comparators.lt(val[1], minVal, false)) { + return [0, -1]; + } + + lbound = this.calculateRangeStart(prop, val[0]); + ubound = this.calculateRangeEnd(prop, val[1]); + + if (lbound < 0) lbound++; + if (ubound > max) ubound--; + + if (!Comparators.gt(rcd[index[lbound]][prop], val[0], true)) lbound++; + if (!Comparators.lt(rcd[index[ubound]][prop], val[1], true)) ubound--; + + if (ubound < lbound) return [0, -1]; + + return ([lbound, ubound]); + case '$in': + var idxset = [], + segResult = []; + // query each value '$eq' operator and merge the seqment results. + for (var j = 0, len = val.length; j < len; j++) { + var seg = this.calculateRange('$eq', prop, val[j]); + + for (var i = seg[0]; i <= seg[1]; i++) { + if (idxset[i] === undefined) { + idxset[i] = true; + segResult.push(i); + } + } + } + return segResult; + } + + // determine lbound where needed + switch (op) { + case '$eq': + case '$aeq': + case '$dteq': + case '$gte': + case '$lt': + lbound = this.calculateRangeStart(prop, val); + lval = rcd[index[lbound]][prop]; + break; + default: break; + } + + // determine ubound where needed + switch (op) { + case '$eq': + case '$aeq': + case '$dteq': + case '$lte': + case '$gt': + ubound = this.calculateRangeEnd(prop, val); + uval = rcd[index[ubound]][prop]; + break; + default: break; + } + + + switch (op) { + case '$eq': + case '$aeq': + case '$dteq': + // if hole (not found) + if (!Comparators.aeq(lval, val)) { + return [0, -1]; + } + + return [lbound, ubound]; + + case '$gt': + // if hole (not found) ub position is already greater + if (!Comparators.aeq(rcd[index[ubound]][prop], val)) { + return [ubound, max]; + } + // otherwise (found) so ubound is still equal, get next + return [ubound+1, max]; + + case '$gte': + // if hole (not found) lb position marks left outside of range + if (!Comparators.aeq(rcd[index[lbound]][prop], val)) { + return [lbound+1, max]; + } + // otherwise (found) so lb is first position where its equal + return [lbound, max]; + + case '$lt': + // if hole (not found) position already is less than + if (!Comparators.aeq(rcd[index[lbound]][prop], val)) { + return [min, lbound]; + } + // otherwise (found) so lb marks left inside of eq range, get previous + return [min, lbound-1]; + + case '$lte': + // if hole (not found) ub position marks right outside so get previous + if (!Comparators.aeq(rcd[index[ubound]][prop], val)) { + return [min, ubound-1]; + } + // otherwise (found) so ub is last position where its still equal + return [min, ubound]; + + default: + return [0, rcd.length - 1]; + } + }; + + /** + * Retrieve doc by Unique index + * @param {string} field - name of uniquely indexed property to use when doing lookup + * @param {value} value - unique value to search for + * @returns {object} document matching the value passed + * @memberof Collection + */ + Collection.prototype.by = function (field, value) { + var self; + if (value === undefined) { + self = this; + return function (value) { + return self.by(field, value); + }; + } + + var result = this.constraints.unique[field].get(value); + if (!this.cloneObjects) { + return result; + } else { + return clone(result, this.cloneMethod); + } + }; + + /** + * Find one object by index property, by property equal to value + * @param {object} query - query object used to perform search with + * @returns {(object|null)} First matching document, or null if none + * @memberof Collection + */ + Collection.prototype.findOne = function (query) { + query = query || {}; + + // Instantiate Resultset and exec find op passing firstOnly = true param + var result = this.chain().find(query,true).data(); + + if (Array.isArray(result) && result.length === 0) { + return null; + } else { + if (!this.cloneObjects) { + return result[0]; + } else { + return clone(result[0], this.cloneMethod); + } + } + }; + + /** + * Chain method, used for beginning a series of chained find() and/or view() operations + * on a collection. + * + * @param {string|array=} transform - named transform or array of transform steps + * @param {object=} parameters - Object containing properties representing parameters to substitute + * @returns {Resultset} (this) resultset, or data array if any map or join functions where called + * @memberof Collection + */ + Collection.prototype.chain = function (transform, parameters) { + var rs = new Resultset(this); + + if (typeof transform === 'undefined') { + return rs; + } + + return rs.transform(transform, parameters); + }; + + /** + * Find method, api is similar to mongodb. + * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}. + * @example {@tutorial Query Examples} + * @param {object} query - 'mongo-like' query object + * @returns {array} Array of matching documents + * @memberof Collection + */ + Collection.prototype.find = function (query) { + return this.chain().find(query).data(); + }; + + /** + * Find object by unindexed field by property equal to value, + * simply iterates and returns the first element matching the query + */ + Collection.prototype.findOneUnindexed = function (prop, value) { + var i = this.data.length, + doc; + while (i--) { + if (this.data[i][prop] === value) { + doc = this.data[i]; + return doc; + } + } + return null; + }; + + /** + * Transaction methods + */ + + /** start the transation */ + Collection.prototype.startTransaction = function () { + if (this.transactional) { + this.cachedData = clone(this.data, this.cloneMethod); + this.cachedIndex = this.idIndex; + this.cachedBinaryIndex = this.binaryIndices; + + // propagate startTransaction to dynamic views + for (var idx = 0; idx < this.DynamicViews.length; idx++) { + this.DynamicViews[idx].startTransaction(); + } + } + }; + + /** commit the transation */ + Collection.prototype.commit = function () { + if (this.transactional) { + this.cachedData = null; + this.cachedIndex = null; + this.cachedBinaryIndex = null; + + // propagate commit to dynamic views + for (var idx = 0; idx < this.DynamicViews.length; idx++) { + this.DynamicViews[idx].commit(); + } + } + }; + + /** roll back the transation */ + Collection.prototype.rollback = function () { + if (this.transactional) { + if (this.cachedData !== null && this.cachedIndex !== null) { + this.data = this.cachedData; + this.idIndex = this.cachedIndex; + this.binaryIndices = this.cachedBinaryIndex; + } + + // propagate rollback to dynamic views + for (var idx = 0; idx < this.DynamicViews.length; idx++) { + this.DynamicViews[idx].rollback(); + } + } + }; + + // async executor. This is only to enable callbacks at the end of the execution. + Collection.prototype.async = function (fun, callback) { + setTimeout(function () { + if (typeof fun === 'function') { + fun(); + callback(); + } else { + throw new TypeError('Argument passed for async execution is not a function'); + } + }, 0); + }; + + /** + * Query the collection by supplying a javascript filter function. + * @example + * var results = coll.where(function(obj) { + * return obj.legs === 8; + * }); + * + * @param {function} fun - filter function to run against all collection docs + * @returns {array} all documents which pass your filter function + * @memberof Collection + */ + Collection.prototype.where = function (fun) { + return this.chain().where(fun).data(); + }; + + /** + * Map Reduce operation + * + * @param {function} mapFunction - function to use as map function + * @param {function} reduceFunction - function to use as reduce function + * @returns {data} The result of your mapReduce operation + * @memberof Collection + */ + Collection.prototype.mapReduce = function (mapFunction, reduceFunction) { + try { + return reduceFunction(this.data.map(mapFunction)); + } catch (err) { + throw err; + } + }; + + /** + * Join two collections on specified properties + * + * @param {array|Resultset|Collection} joinData - array of documents to 'join' to this collection + * @param {string} leftJoinProp - property name in collection + * @param {string} rightJoinProp - property name in joinData + * @param {function=} mapFun - (Optional) map function to use + * @param {object=} dataOptions - options to data() before input to your map function + * @param {bool} dataOptions.removeMeta - allows removing meta before calling mapFun + * @param {boolean} dataOptions.forceClones - forcing the return of cloned objects to your map object + * @param {string} dataOptions.forceCloneMethod - Allows overriding the default or collection specified cloning method. + * @returns {Resultset} Result of the mapping operation + * @memberof Collection + */ + Collection.prototype.eqJoin = function (joinData, leftJoinProp, rightJoinProp, mapFun, dataOptions) { + // logic in Resultset class + return new Resultset(this).eqJoin(joinData, leftJoinProp, rightJoinProp, mapFun, dataOptions); + }; + + /* ------ STAGING API -------- */ + /** + * stages: a map of uniquely identified 'stages', which hold copies of objects to be + * manipulated without affecting the data in the original collection + */ + Collection.prototype.stages = {}; + + /** + * (Staging API) create a stage and/or retrieve it + * @memberof Collection + */ + Collection.prototype.getStage = function (name) { + if (!this.stages[name]) { + this.stages[name] = {}; + } + return this.stages[name]; + }; + /** + * a collection of objects recording the changes applied through a commmitStage + */ + Collection.prototype.commitLog = []; + + /** + * (Staging API) create a copy of an object and insert it into a stage + * @memberof Collection + */ + Collection.prototype.stage = function (stageName, obj) { + var copy = JSON.parse(JSON.stringify(obj)); + this.getStage(stageName)[obj.$loki] = copy; + return copy; + }; + + /** + * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt + * then create a message to be inserted in the commitlog + * @param {string} stageName - name of stage + * @param {string} message + * @memberof Collection + */ + Collection.prototype.commitStage = function (stageName, message) { + var stage = this.getStage(stageName), + prop, + timestamp = new Date().getTime(); + + for (prop in stage) { + + this.update(stage[prop]); + this.commitLog.push({ + timestamp: timestamp, + message: message, + data: JSON.parse(JSON.stringify(stage[prop])) + }); + } + this.stages[stageName] = {}; + }; + + Collection.prototype.no_op = function () { + return; + }; + + /** + * @memberof Collection + */ + Collection.prototype.extract = function (field) { + var i = 0, + len = this.data.length, + isDotNotation = isDeepProperty(field), + result = []; + for (i; i < len; i += 1) { + result.push(deepProperty(this.data[i], field, isDotNotation)); + } + return result; + }; + + /** + * @memberof Collection + */ + Collection.prototype.max = function (field) { + return Math.max.apply(null, this.extract(field)); + }; + + /** + * @memberof Collection + */ + Collection.prototype.min = function (field) { + return Math.min.apply(null, this.extract(field)); + }; + + /** + * @memberof Collection + */ + Collection.prototype.maxRecord = function (field) { + var i = 0, + len = this.data.length, + deep = isDeepProperty(field), + result = { + index: 0, + value: undefined + }, + max; + + for (i; i < len; i += 1) { + if (max !== undefined) { + if (max < deepProperty(this.data[i], field, deep)) { + max = deepProperty(this.data[i], field, deep); + result.index = this.data[i].$loki; + } + } else { + max = deepProperty(this.data[i], field, deep); + result.index = this.data[i].$loki; + } + } + result.value = max; + return result; + }; + + /** + * @memberof Collection + */ + Collection.prototype.minRecord = function (field) { + var i = 0, + len = this.data.length, + deep = isDeepProperty(field), + result = { + index: 0, + value: undefined + }, + min; + + for (i; i < len; i += 1) { + if (min !== undefined) { + if (min > deepProperty(this.data[i], field, deep)) { + min = deepProperty(this.data[i], field, deep); + result.index = this.data[i].$loki; + } + } else { + min = deepProperty(this.data[i], field, deep); + result.index = this.data[i].$loki; + } + } + result.value = min; + return result; + }; + + /** + * @memberof Collection + */ + Collection.prototype.extractNumerical = function (field) { + return this.extract(field).map(parseBase10).filter(Number).filter(function (n) { + return !(isNaN(n)); + }); + }; + + /** + * Calculates the average numerical value of a property + * + * @param {string} field - name of property in docs to average + * @returns {number} average of property in all docs in the collection + * @memberof Collection + */ + Collection.prototype.avg = function (field) { + return average(this.extractNumerical(field)); + }; + + /** + * Calculate standard deviation of a field + * @memberof Collection + * @param {string} field + */ + Collection.prototype.stdDev = function (field) { + return standardDeviation(this.extractNumerical(field)); + }; + + /** + * @memberof Collection + * @param {string} field + */ + Collection.prototype.mode = function (field) { + var dict = {}, + data = this.extract(field); + data.forEach(function (obj) { + if (dict[obj]) { + dict[obj] += 1; + } else { + dict[obj] = 1; + } + }); + var max, + prop, mode; + for (prop in dict) { + if (max) { + if (max < dict[prop]) { + mode = prop; + } + } else { + mode = prop; + max = dict[prop]; + } + } + return mode; + }; + + /** + * @memberof Collection + * @param {string} field - property name + */ + Collection.prototype.median = function (field) { + var values = this.extractNumerical(field); + values.sort(sub); + + var half = Math.floor(values.length / 2); + + if (values.length % 2) { + return values[half]; + } else { + return (values[half - 1] + values[half]) / 2.0; + } + }; + + /** + * General utils, including statistical functions + */ + function isDeepProperty(field) { + return field.indexOf('.') !== -1; + } + + function parseBase10(num) { + return parseFloat(num, 10); + } + + function isNotUndefined(obj) { + return obj !== undefined; + } + + function add(a, b) { + return a + b; + } + + function sub(a, b) { + return a - b; + } + + function median(values) { + values.sort(sub); + var half = Math.floor(values.length / 2); + return (values.length % 2) ? values[half] : ((values[half - 1] + values[half]) / 2.0); + } + + function average(array) { + return (array.reduce(add, 0)) / array.length; + } + + function standardDeviation(values) { + var avg = average(values); + var squareDiffs = values.map(function (value) { + var diff = value - avg; + var sqrDiff = diff * diff; + return sqrDiff; + }); + + var avgSquareDiff = average(squareDiffs); + + var stdDev = Math.sqrt(avgSquareDiff); + return stdDev; + } + + function deepProperty(obj, property, isDeep) { + if (isDeep === false) { + // pass without processing + return obj[property]; + } + var pieces = property.split('.'), + root = obj; + while (pieces.length > 0) { + root = root[pieces.shift()]; + } + return root; + } + + function binarySearch(array, item, fun) { + var lo = 0, + hi = array.length, + compared, + mid; + while (lo < hi) { + mid = (lo + hi) >> 1; + compared = fun.apply(null, [item, array[mid]]); + if (compared === 0) { + return { + found: true, + index: mid + }; + } else if (compared < 0) { + hi = mid; + } else { + lo = mid + 1; + } + } + return { + found: false, + index: hi + }; + } + + function BSonSort(fun) { + return function (array, item) { + return binarySearch(array, item, fun); + }; + } + + function KeyValueStore() {} + + KeyValueStore.prototype = { + keys: [], + values: [], + sort: function (a, b) { + return (a < b) ? -1 : ((a > b) ? 1 : 0); + }, + setSort: function (fun) { + this.bs = new BSonSort(fun); + }, + bs: function () { + return new BSonSort(this.sort); + }, + set: function (key, value) { + var pos = this.bs(this.keys, key); + if (pos.found) { + this.values[pos.index] = value; + } else { + this.keys.splice(pos.index, 0, key); + this.values.splice(pos.index, 0, value); + } + }, + get: function (key) { + return this.values[binarySearch(this.keys, key, this.sort).index]; + } + }; + + function UniqueIndex(uniqueField) { + this.field = uniqueField; + this.keyMap = {}; + this.lokiMap = {}; + } + UniqueIndex.prototype.keyMap = {}; + UniqueIndex.prototype.lokiMap = {}; + UniqueIndex.prototype.set = function (obj) { + var fieldValue = obj[this.field]; + if (fieldValue !== null && typeof (fieldValue) !== 'undefined') { + if (this.keyMap[fieldValue]) { + throw new Error('Duplicate key for property ' + this.field + ': ' + fieldValue); + } else { + this.keyMap[fieldValue] = obj; + this.lokiMap[obj.$loki] = fieldValue; + } + } + }; + UniqueIndex.prototype.get = function (key) { + return this.keyMap[key]; + }; + + UniqueIndex.prototype.byId = function (id) { + return this.keyMap[this.lokiMap[id]]; + }; + /** + * Updates a document's unique index given an updated object. + * @param {Object} obj Original document object + * @param {Object} doc New document object (likely the same as obj) + */ + UniqueIndex.prototype.update = function (obj, doc) { + if (this.lokiMap[obj.$loki] !== doc[this.field]) { + var old = this.lokiMap[obj.$loki]; + this.set(doc); + // make the old key fail bool test, while avoiding the use of delete (mem-leak prone) + this.keyMap[old] = undefined; + } else { + this.keyMap[obj[this.field]] = doc; + } + }; + UniqueIndex.prototype.remove = function (key) { + var obj = this.keyMap[key]; + if (obj !== null && typeof obj !== 'undefined') { + this.keyMap[key] = undefined; + this.lokiMap[obj.$loki] = undefined; + } else { + throw new Error('Key is not in unique index: ' + this.field); + } + }; + UniqueIndex.prototype.clear = function () { + this.keyMap = {}; + this.lokiMap = {}; + }; + + function ExactIndex(exactField) { + this.index = {}; + this.field = exactField; + } + + // add the value you want returned to the key in the index + ExactIndex.prototype = { + set: function add(key, val) { + if (this.index[key]) { + this.index[key].push(val); + } else { + this.index[key] = [val]; + } + }, + + // remove the value from the index, if the value was the last one, remove the key + remove: function remove(key, val) { + var idxSet = this.index[key]; + for (var i in idxSet) { + if (idxSet[i] == val) { + idxSet.splice(i, 1); + } + } + if (idxSet.length < 1) { + this.index[key] = undefined; + } + }, + + // get the values related to the key, could be more than one + get: function get(key) { + return this.index[key]; + }, + + // clear will zap the index + clear: function clear(key) { + this.index = {}; + } + }; + + function SortedIndex(sortedField) { + this.field = sortedField; + } + + SortedIndex.prototype = { + keys: [], + values: [], + // set the default sort + sort: function (a, b) { + return (a < b) ? -1 : ((a > b) ? 1 : 0); + }, + bs: function () { + return new BSonSort(this.sort); + }, + // and allow override of the default sort + setSort: function (fun) { + this.bs = new BSonSort(fun); + }, + // add the value you want returned to the key in the index + set: function (key, value) { + var pos = binarySearch(this.keys, key, this.sort); + if (pos.found) { + this.values[pos.index].push(value); + } else { + this.keys.splice(pos.index, 0, key); + this.values.splice(pos.index, 0, [value]); + } + }, + // get all values which have a key == the given key + get: function (key) { + var bsr = binarySearch(this.keys, key, this.sort); + if (bsr.found) { + return this.values[bsr.index]; + } else { + return []; + } + }, + // get all values which have a key < the given key + getLt: function (key) { + var bsr = binarySearch(this.keys, key, this.sort); + var pos = bsr.index; + if (bsr.found) pos--; + return this.getAll(key, 0, pos); + }, + // get all values which have a key > the given key + getGt: function (key) { + var bsr = binarySearch(this.keys, key, this.sort); + var pos = bsr.index; + if (bsr.found) pos++; + return this.getAll(key, pos, this.keys.length); + }, + + // get all vals from start to end + getAll: function (key, start, end) { + var results = []; + for (var i = start; i < end; i++) { + results = results.concat(this.values[i]); + } + return results; + }, + // just in case someone wants to do something smart with ranges + getPos: function (key) { + return binarySearch(this.keys, key, this.sort); + }, + // remove the value from the index, if the value was the last one, remove the key + remove: function (key, value) { + var pos = binarySearch(this.keys, key, this.sort).index; + var idxSet = this.values[pos]; + for (var i in idxSet) { + if (idxSet[i] == value) idxSet.splice(i, 1); + } + if (idxSet.length < 1) { + this.keys.splice(pos, 1); + this.values.splice(pos, 1); + } + }, + // clear will zap the index + clear: function () { + this.keys = []; + this.values = []; + } + }; + + + Loki.LokiOps = LokiOps; + Loki.Collection = Collection; + Loki.KeyValueStore = KeyValueStore; + Loki.LokiMemoryAdapter = LokiMemoryAdapter; + Loki.LokiPartitioningAdapter = LokiPartitioningAdapter; + Loki.LokiLocalStorageAdapter = LokiLocalStorageAdapter; + Loki.LokiFsAdapter = LokiFsAdapter; + Loki.persistenceAdapters = { + fs: LokiFsAdapter, + localStorage: LokiLocalStorageAdapter + }; + Loki.aeq = aeqHelper; + Loki.lt = ltHelper; + Loki.gt = gtHelper; + Loki.Comparators = Comparators; + return Loki; + }()); + +})); diff --git a/node_modules/media-typer/HISTORY.md b/node_modules/media-typer/HISTORY.md new file mode 100644 index 00000000..62c20031 --- /dev/null +++ b/node_modules/media-typer/HISTORY.md @@ -0,0 +1,22 @@ +0.3.0 / 2014-09-07 +================== + + * Support Node.js 0.6 + * Throw error when parameter format invalid on parse + +0.2.0 / 2014-06-18 +================== + + * Add `typer.format()` to format media types + +0.1.0 / 2014-06-17 +================== + + * Accept `req` as argument to `parse` + * Accept `res` as argument to `parse` + * Parse media type with extra LWS between type and first parameter + +0.0.0 / 2014-06-13 +================== + + * Initial implementation diff --git a/node_modules/media-typer/LICENSE b/node_modules/media-typer/LICENSE new file mode 100644 index 00000000..b7dce6cf --- /dev/null +++ b/node_modules/media-typer/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014 Douglas Christopher Wilson + +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/media-typer/README.md b/node_modules/media-typer/README.md new file mode 100644 index 00000000..d8df6234 --- /dev/null +++ b/node_modules/media-typer/README.md @@ -0,0 +1,81 @@ +# media-typer + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Simple RFC 6838 media type parser + +## Installation + +```sh +$ npm install media-typer +``` + +## API + +```js +var typer = require('media-typer') +``` + +### typer.parse(string) + +```js +var obj = typer.parse('image/svg+xml; charset=utf-8') +``` + +Parse a media type string. This will return an object with the following +properties (examples are shown for the string `'image/svg+xml; charset=utf-8'`): + + - `type`: The type of the media type (always lower case). Example: `'image'` + + - `subtype`: The subtype of the media type (always lower case). Example: `'svg'` + + - `suffix`: The suffix of the media type (always lower case). Example: `'xml'` + + - `parameters`: An object of the parameters in the media type (name of parameter always lower case). Example: `{charset: 'utf-8'}` + +### typer.parse(req) + +```js +var obj = typer.parse(req) +``` + +Parse the `content-type` header from the given `req`. Short-cut for +`typer.parse(req.headers['content-type'])`. + +### typer.parse(res) + +```js +var obj = typer.parse(res) +``` + +Parse the `content-type` header set on the given `res`. Short-cut for +`typer.parse(res.getHeader('content-type'))`. + +### typer.format(obj) + +```js +var obj = typer.format({type: 'image', subtype: 'svg', suffix: 'xml'}) +``` + +Format an object into a media type string. This will return a string of the +mime type for the given object. For the properties of the object, see the +documentation for `typer.parse(string)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/media-typer.svg?style=flat +[npm-url]: https://npmjs.org/package/media-typer +[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/media-typer.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/media-typer +[coveralls-image]: https://img.shields.io/coveralls/jshttp/media-typer.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/media-typer +[downloads-image]: https://img.shields.io/npm/dm/media-typer.svg?style=flat +[downloads-url]: https://npmjs.org/package/media-typer diff --git a/node_modules/media-typer/index.js b/node_modules/media-typer/index.js new file mode 100644 index 00000000..07f7295e --- /dev/null +++ b/node_modules/media-typer/index.js @@ -0,0 +1,270 @@ +/*! + * media-typer + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7 + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * SHT = + * CTL = + * OCTET = + */ +var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g; +var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/ +var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/ + +/** + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + */ +var qescRegExp = /\\([\u0000-\u007f])/g; + +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + */ +var quoteRegExp = /([\\"])/g; + +/** + * RegExp to match type in RFC 6838 + * + * type-name = restricted-name + * subtype-name = restricted-name + * restricted-name = restricted-name-first *126restricted-name-chars + * restricted-name-first = ALPHA / DIGIT + * restricted-name-chars = ALPHA / DIGIT / "!" / "#" / + * "$" / "&" / "-" / "^" / "_" + * restricted-name-chars =/ "." ; Characters before first dot always + * ; specify a facet name + * restricted-name-chars =/ "+" ; Characters after last plus always + * ; specify a structured syntax suffix + * ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + * DIGIT = %x30-39 ; 0-9 + */ +var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/ +var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/ +var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/; + +/** + * Module exports. + */ + +exports.format = format +exports.parse = parse + +/** + * Format object to media type. + * + * @param {object} obj + * @return {string} + * @api public + */ + +function format(obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } + + var parameters = obj.parameters + var subtype = obj.subtype + var suffix = obj.suffix + var type = obj.type + + if (!type || !typeNameRegExp.test(type)) { + throw new TypeError('invalid type') + } + + if (!subtype || !subtypeNameRegExp.test(subtype)) { + throw new TypeError('invalid subtype') + } + + // format as type/subtype + var string = type + '/' + subtype + + // append +suffix + if (suffix) { + if (!typeNameRegExp.test(suffix)) { + throw new TypeError('invalid suffix') + } + + string += '+' + suffix + } + + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() + + for (var i = 0; i < params.length; i++) { + param = params[i] + + if (!tokenRegExp.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) + } + } + + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @api public + */ + +function parse(string) { + if (!string) { + throw new TypeError('argument string is required') + } + + // support req/res-like objects as argument + if (typeof string === 'object') { + string = getcontenttype(string) + } + + if (typeof string !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = string.indexOf(';') + var type = index !== -1 + ? string.substr(0, index) + : string + + var key + var match + var obj = splitType(type) + var params = {} + var value + + paramRegExp.lastIndex = index + + while (match = paramRegExp.exec(string)) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(qescRegExp, '$1') + } + + params[key] = value + } + + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } + + obj.parameters = params + + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @api private + */ + +function getcontenttype(obj) { + if (typeof obj.getHeader === 'function') { + // res-like + return obj.getHeader('content-type') + } + + if (typeof obj.headers === 'object') { + // req-like + return obj.headers && obj.headers['content-type'] + } +} + +/** + * Quote a string if necessary. + * + * @param {string} val + * @return {string} + * @api private + */ + +function qstring(val) { + var str = String(val) + + // no need to quote tokens + if (tokenRegExp.test(str)) { + return str + } + + if (str.length > 0 && !textRegExp.test(str)) { + throw new TypeError('invalid parameter value') + } + + return '"' + str.replace(quoteRegExp, '\\$1') + '"' +} + +/** + * Simply "type/subtype+siffx" into parts. + * + * @param {string} string + * @return {Object} + * @api private + */ + +function splitType(string) { + var match = typeRegExp.exec(string.toLowerCase()) + + if (!match) { + throw new TypeError('invalid media type') + } + + var type = match[1] + var subtype = match[2] + var suffix + + // suffix after last + + var index = subtype.lastIndexOf('+') + if (index !== -1) { + suffix = subtype.substr(index + 1) + subtype = subtype.substr(0, index) + } + + var obj = { + type: type, + subtype: subtype, + suffix: suffix + } + + return obj +} diff --git a/node_modules/media-typer/package.json b/node_modules/media-typer/package.json new file mode 100644 index 00000000..38d78797 --- /dev/null +++ b/node_modules/media-typer/package.json @@ -0,0 +1,64 @@ +{ + "_args": [ + [ + "media-typer@0.3.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "media-typer@0.3.0", + "_id": "media-typer@0.3.0", + "_inBundle": false, + "_integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=", + "_location": "/media-typer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "media-typer@0.3.0", + "name": "media-typer", + "escapedName": "media-typer", + "rawSpec": "0.3.0", + "saveSpec": null, + "fetchSpec": "0.3.0" + }, + "_requiredBy": [ + "/type-is" + ], + "_resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "_spec": "0.3.0", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/jshttp/media-typer/issues" + }, + "description": "Simple RFC 6838 media type parser and formatter", + "devDependencies": { + "istanbul": "0.3.2", + "mocha": "~1.21.4", + "should": "~4.0.4" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/media-typer#readme", + "license": "MIT", + "name": "media-typer", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/media-typer.git" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "0.3.0" +} diff --git a/node_modules/merge-descriptors/HISTORY.md b/node_modules/merge-descriptors/HISTORY.md new file mode 100644 index 00000000..486771f0 --- /dev/null +++ b/node_modules/merge-descriptors/HISTORY.md @@ -0,0 +1,21 @@ +1.0.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.0.0 / 2015-03-01 +================== + + * Add option to only add new descriptors + * Add simple argument validation + * Add jsdoc to source file + +0.0.2 / 2013-12-14 +================== + + * Move repository to `component` organization + +0.0.1 / 2013-10-29 +================== + + * Initial release diff --git a/node_modules/merge-descriptors/LICENSE b/node_modules/merge-descriptors/LICENSE new file mode 100644 index 00000000..274bfd82 --- /dev/null +++ b/node_modules/merge-descriptors/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/merge-descriptors/README.md b/node_modules/merge-descriptors/README.md new file mode 100644 index 00000000..d593c0eb --- /dev/null +++ b/node_modules/merge-descriptors/README.md @@ -0,0 +1,48 @@ +# Merge Descriptors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Merge objects using descriptors. + +```js +var thing = { + get name() { + return 'jon' + } +} + +var animal = { + +} + +merge(animal, thing) + +animal.name === 'jon' +``` + +## API + +### merge(destination, source) + +Redefines `destination`'s descriptors with `source`'s. + +### merge(destination, source, false) + +Defines `source`'s descriptors on `destination` if `destination` does not have +a descriptor by the same name. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/merge-descriptors.svg +[npm-url]: https://npmjs.org/package/merge-descriptors +[travis-image]: https://img.shields.io/travis/component/merge-descriptors/master.svg +[travis-url]: https://travis-ci.org/component/merge-descriptors +[coveralls-image]: https://img.shields.io/coveralls/component/merge-descriptors/master.svg +[coveralls-url]: https://coveralls.io/r/component/merge-descriptors?branch=master +[downloads-image]: https://img.shields.io/npm/dm/merge-descriptors.svg +[downloads-url]: https://npmjs.org/package/merge-descriptors diff --git a/node_modules/merge-descriptors/index.js b/node_modules/merge-descriptors/index.js new file mode 100644 index 00000000..573b132e --- /dev/null +++ b/node_modules/merge-descriptors/index.js @@ -0,0 +1,60 @@ +/*! + * merge-descriptors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = merge + +/** + * Module variables. + * @private + */ + +var hasOwnProperty = Object.prototype.hasOwnProperty + +/** + * Merge the property descriptors of `src` into `dest` + * + * @param {object} dest Object to add descriptors to + * @param {object} src Object to clone descriptors from + * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties + * @returns {object} Reference to dest + * @public + */ + +function merge(dest, src, redefine) { + if (!dest) { + throw new TypeError('argument dest is required') + } + + if (!src) { + throw new TypeError('argument src is required') + } + + if (redefine === undefined) { + // Default to true + redefine = true + } + + Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) { + if (!redefine && hasOwnProperty.call(dest, name)) { + // Skip desriptor + return + } + + // Copy descriptor + var descriptor = Object.getOwnPropertyDescriptor(src, name) + Object.defineProperty(dest, name, descriptor) + }) + + return dest +} diff --git a/node_modules/merge-descriptors/package.json b/node_modules/merge-descriptors/package.json new file mode 100644 index 00000000..e028f767 --- /dev/null +++ b/node_modules/merge-descriptors/package.json @@ -0,0 +1,72 @@ +{ + "_args": [ + [ + "merge-descriptors@1.0.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "merge-descriptors@1.0.1", + "_id": "merge-descriptors@1.0.1", + "_inBundle": false, + "_integrity": "sha1-sAqqVW3YtEVoFQ7J0blT8/kMu2E=", + "_location": "/merge-descriptors", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "merge-descriptors@1.0.1", + "name": "merge-descriptors", + "escapedName": "merge-descriptors", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "_spec": "1.0.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/component/merge-descriptors/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Mike Grabowski", + "email": "grabbou@gmail.com" + } + ], + "description": "Merge objects using descriptors", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "homepage": "https://github.com/component/merge-descriptors#readme", + "license": "MIT", + "name": "merge-descriptors", + "repository": { + "type": "git", + "url": "git+https://github.com/component/merge-descriptors.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + }, + "version": "1.0.1" +} diff --git a/node_modules/methods/HISTORY.md b/node_modules/methods/HISTORY.md new file mode 100644 index 00000000..c0ecf072 --- /dev/null +++ b/node_modules/methods/HISTORY.md @@ -0,0 +1,29 @@ +1.1.2 / 2016-01-17 +================== + + * perf: enable strict mode + +1.1.1 / 2014-12-30 +================== + + * Improve `browserify` support + +1.1.0 / 2014-07-05 +================== + + * Add `CONNECT` method + +1.0.1 / 2014-06-02 +================== + + * Fix module to work with harmony transform + +1.0.0 / 2014-05-08 +================== + + * Add `PURGE` method + +0.1.0 / 2013-10-28 +================== + + * Add `http.METHODS` support diff --git a/node_modules/methods/LICENSE b/node_modules/methods/LICENSE new file mode 100644 index 00000000..220dc1a2 --- /dev/null +++ b/node_modules/methods/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2013-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson + +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/methods/README.md b/node_modules/methods/README.md new file mode 100644 index 00000000..672a32bf --- /dev/null +++ b/node_modules/methods/README.md @@ -0,0 +1,51 @@ +# Methods + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP verbs that Node.js core's HTTP parser supports. + +This module provides an export that is just like `http.METHODS` from Node.js core, +with the following differences: + + * All method names are lower-cased. + * Contains a fallback list of methods for Node.js versions that do not have a + `http.METHODS` export (0.10 and lower). + * Provides the fallback list when using tools like `browserify` without pulling + in the `http` shim module. + +## Install + +```bash +$ npm install methods +``` + +## API + +```js +var methods = require('methods') +``` + +### methods + +This is an array of lower-cased method names that Node.js supports. If Node.js +provides the `http.METHODS` export, then this is the same array lower-cased, +otherwise it is a snapshot of the verbs from Node.js 0.10. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/methods.svg?style=flat +[npm-url]: https://npmjs.org/package/methods +[node-version-image]: https://img.shields.io/node/v/methods.svg?style=flat +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/methods.svg?style=flat +[travis-url]: https://travis-ci.org/jshttp/methods +[coveralls-image]: https://img.shields.io/coveralls/jshttp/methods.svg?style=flat +[coveralls-url]: https://coveralls.io/r/jshttp/methods?branch=master +[downloads-image]: https://img.shields.io/npm/dm/methods.svg?style=flat +[downloads-url]: https://npmjs.org/package/methods diff --git a/node_modules/methods/index.js b/node_modules/methods/index.js new file mode 100644 index 00000000..667a50bd --- /dev/null +++ b/node_modules/methods/index.js @@ -0,0 +1,69 @@ +/*! + * methods + * Copyright(c) 2013-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module dependencies. + * @private + */ + +var http = require('http'); + +/** + * Module exports. + * @public + */ + +module.exports = getCurrentNodeMethods() || getBasicNodeMethods(); + +/** + * Get the current Node.js methods. + * @private + */ + +function getCurrentNodeMethods() { + return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) { + return method.toLowerCase(); + }); +} + +/** + * Get the "basic" Node.js methods, a snapshot from Node.js 0.10. + * @private + */ + +function getBasicNodeMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect' + ]; +} diff --git a/node_modules/methods/package.json b/node_modules/methods/package.json new file mode 100644 index 00000000..fc8d4d10 --- /dev/null +++ b/node_modules/methods/package.json @@ -0,0 +1,82 @@ +{ + "_args": [ + [ + "methods@1.1.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "methods@1.1.2", + "_id": "methods@1.1.2", + "_inBundle": false, + "_integrity": "sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=", + "_location": "/methods", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "methods@1.1.2", + "name": "methods", + "escapedName": "methods", + "rawSpec": "1.1.2", + "saveSpec": null, + "fetchSpec": "1.1.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "_spec": "1.1.2", + "_where": "C:\\GitHub\\cis411_lab0", + "browser": { + "http": false + }, + "bugs": { + "url": "https://github.com/jshttp/methods/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + } + ], + "description": "HTTP methods that node supports", + "devDependencies": { + "istanbul": "0.4.1", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE" + ], + "homepage": "https://github.com/jshttp/methods#readme", + "keywords": [ + "http", + "methods" + ], + "license": "MIT", + "name": "methods", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/methods.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.1.2" +} diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 00000000..1cc7a514 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,391 @@ +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 00000000..a7ae8ee9 --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.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/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 00000000..fed4eeba --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,94 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a database of all mime types. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [RawGit](https://rawgit.com/). It is recommended to replace +`master` with [a release tag](https://github.com/jshttp/mime-db/tags) as the +JSON format may change in the future. + +``` +https://cdn.rawgit.com/jshttp/mime-db/master/db.json +``` + +## Usage + +```js +var db = require('mime-db'); + +// grab data on .js files +var data = db['application/javascript']; +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom.json` or +`src/custom-suffix.json`. + +The `src/custom.json` file is a JSON object with the MIME type as the keys +and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +## Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg +[npm-url]: https://npmjs.org/package/mime-db +[travis-image]: https://img.shields.io/travis/jshttp/mime-db/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-db +[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-db/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://img.shields.io/node/v/mime-db.svg +[node-url]: https://nodejs.org/en/download/ diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 00000000..fbffff24 --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,7671 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/cbor": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["ecma","es"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true + }, + "application/fhir+json": { + "source": "iana", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana" + }, + "application/n-triples": { + "source": "iana" + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana" + }, + "application/news-groupinfo": { + "source": "iana" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana" + }, + "application/nss": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana" + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana" + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana" + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["keynote"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana" + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana" + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "apache", + "extensions": ["der","crt","pem"] + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana" + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana" + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana" + }, + "image/avcs": { + "source": "iana" + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana" + }, + "image/heic-sequence": { + "source": "iana" + }, + "image/heif": { + "source": "iana" + }, + "image/heif-sequence": { + "source": "iana" + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/stl": { + "source": "iana" + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana" + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana" + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana" + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana" + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana", + "compressible": false + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shex": { + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana" + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vp8": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 00000000..551031f6 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,11 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 00000000..5b9a8155 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,103 @@ +{ + "_args": [ + [ + "mime-db@1.36.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "mime-db@1.36.0", + "_id": "mime-db@1.36.0", + "_inBundle": false, + "_integrity": "sha512-L+xvyD9MkoYMXb1jAmzI/lWYAxAMCPvIBSWur0PZ5nOf5euahRLVqH//FKW9mWp2lkqUgYiXPgkzfMUFi4zVDw==", + "_location": "/mime-db", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mime-db@1.36.0", + "name": "mime-db", + "escapedName": "mime-db", + "rawSpec": "1.36.0", + "saveSpec": null, + "fetchSpec": "1.36.0" + }, + "_requiredBy": [ + "/mime-types" + ], + "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.36.0.tgz", + "_spec": "1.36.0", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/mime-db/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + } + ], + "description": "Media Type Database", + "devDependencies": { + "bluebird": "3.5.1", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "2.5.0", + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.13.0", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.8.0", + "eslint-plugin-standard": "3.1.0", + "gnode": "0.1.2", + "mocha": "1.21.5", + "nyc": "11.8.0", + "raw-body": "2.3.3", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "homepage": "https://github.com/jshttp/mime-db#readme", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "license": "MIT", + "name": "mime-db", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-db.git" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "test-travis": "nyc --reporter=text npm test", + "update": "npm run fetch && npm run build" + }, + "version": "1.36.0" +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 00000000..c3af78d2 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,278 @@ +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Add additional compressible + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 00000000..06166077 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 00000000..b58cae6d --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,108 @@ +# mime-types + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/mime-types.svg +[npm-url]: https://npmjs.org/package/mime-types +[node-version-image]: https://img.shields.io/node/v/mime-types.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/mime-types/master.svg +[travis-url]: https://travis-ci.org/jshttp/mime-types +[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types +[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg +[downloads-url]: https://npmjs.org/package/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 00000000..b9f34d59 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 00000000..79c4ab3d --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,90 @@ +{ + "_args": [ + [ + "mime-types@2.1.20", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "mime-types@2.1.20", + "_id": "mime-types@2.1.20", + "_inBundle": false, + "_integrity": "sha512-HrkrPaP9vGuWbLK1B1FfgAkbqNjIuy4eHlIYnFi7kamZyLLrGlo2mpcx0bBmNpKqBtYtAfGbodDddIgddSJC2A==", + "_location": "/mime-types", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mime-types@2.1.20", + "name": "mime-types", + "escapedName": "mime-types", + "rawSpec": "2.1.20", + "saveSpec": null, + "fetchSpec": "2.1.20" + }, + "_requiredBy": [ + "/accepts", + "/type-is" + ], + "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.20.tgz", + "_spec": "2.1.20", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/mime-types/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jeremiah Senkpiel", + "email": "fishrock123@rocketmail.com", + "url": "https://searchbeam.jit.su" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "dependencies": { + "mime-db": "~1.36.0" + }, + "description": "The ultimate javascript content-type utility.", + "devDependencies": { + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.13.0", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.8.0", + "eslint-plugin-standard": "3.1.0", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "homepage": "https://github.com/jshttp/mime-types#readme", + "keywords": [ + "mime", + "types" + ], + "license": "MIT", + "name": "mime-types", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/mime-types.git" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/test.js", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot test/test.js" + }, + "version": "2.1.20" +} diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE new file mode 100644 index 00000000..d3f46f7e --- /dev/null +++ b/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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/mime/README.md b/node_modules/mime/README.md new file mode 100644 index 00000000..506fbe55 --- /dev/null +++ b/node_modules/mime/README.md @@ -0,0 +1,90 @@ +# mime + +Comprehensive MIME type mapping API based on mime-db module. + +## Install + +Install with [npm](http://github.com/isaacs/npm): + + npm install mime + +## Contributing / Testing + + npm run test + +## Command Line + + mime [path_string] + +E.g. + + > mime scripts/jquery.js + application/javascript + +## API - Queries + +### mime.lookup(path) +Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. + +```js +var mime = require('mime'); + +mime.lookup('/path/to/file.txt'); // => 'text/plain' +mime.lookup('file.txt'); // => 'text/plain' +mime.lookup('.TXT'); // => 'text/plain' +mime.lookup('htm'); // => 'text/html' +``` + +### mime.default_type +Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) + +### mime.extension(type) +Get the default extension for `type` + +```js +mime.extension('text/html'); // => 'html' +mime.extension('application/octet-stream'); // => 'bin' +``` + +### mime.charsets.lookup() + +Map mime-type to charset + +```js +mime.charsets.lookup('text/plain'); // => 'UTF-8' +``` + +(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) + +## API - Defining Custom Types + +Custom type mappings can be added on a per-project basis via the following APIs. + +### mime.define() + +Add custom mime/extension mappings + +```js +mime.define({ + 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], + 'application/x-my-type': ['x-mt', 'x-mtt'], + // etc ... +}); + +mime.lookup('x-sft'); // => 'text/x-some-format' +``` + +The first entry in the extensions array is returned by `mime.extension()`. E.g. + +```js +mime.extension('text/x-some-format'); // => 'x-sf' +``` + +### mime.load(filepath) + +Load mappings from an Apache ".types" format file + +```js +mime.load('./my_project.types'); +``` +The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/mime/build/build.js b/node_modules/mime/build/build.js new file mode 100644 index 00000000..ed5313e3 --- /dev/null +++ b/node_modules/mime/build/build.js @@ -0,0 +1,11 @@ +var db = require('mime-db'); + +var mapByType = {}; +Object.keys(db).forEach(function(key) { + var extensions = db[key].extensions; + if (extensions) { + mapByType[key] = extensions; + } +}); + +console.log(JSON.stringify(mapByType)); diff --git a/node_modules/mime/build/test.js b/node_modules/mime/build/test.js new file mode 100644 index 00000000..010c42b9 --- /dev/null +++ b/node_modules/mime/build/test.js @@ -0,0 +1,60 @@ +/** + * Usage: node test.js + */ + +var mime = require('../mime'); +var assert = require('assert'); +var path = require('path'); + +// +// Test mime lookups +// + +assert.equal('text/plain', mime.lookup('text.txt')); // normal file +assert.equal('text/plain', mime.lookup('TEXT.TXT')); // uppercase +assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file +assert.equal('text/plain', mime.lookup('.text.txt')); // hidden file +assert.equal('text/plain', mime.lookup('.txt')); // nameless +assert.equal('text/plain', mime.lookup('txt')); // extension-only +assert.equal('text/plain', mime.lookup('/txt')); // extension-less () +assert.equal('text/plain', mime.lookup('\\txt')); // Windows, extension-less +assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized +assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default + +// +// Test extensions +// + +assert.equal('txt', mime.extension(mime.types.text)); +assert.equal('html', mime.extension(mime.types.htm)); +assert.equal('bin', mime.extension('application/octet-stream')); +assert.equal('bin', mime.extension('application/octet-stream ')); +assert.equal('html', mime.extension(' text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html; charset=UTF-8 ')); +assert.equal('html', mime.extension('text/html; charset=UTF-8')); +assert.equal('html', mime.extension('text/html ; charset=UTF-8')); +assert.equal('html', mime.extension('text/html;charset=UTF-8')); +assert.equal('html', mime.extension('text/Html;charset=UTF-8')); +assert.equal(undefined, mime.extension('unrecognized')); + +// +// Test node.types lookups +// + +assert.equal('application/font-woff', mime.lookup('file.woff')); +assert.equal('application/octet-stream', mime.lookup('file.buffer')); +// TODO: Uncomment once #157 is resolved +// assert.equal('audio/mp4', mime.lookup('file.m4a')); +assert.equal('font/otf', mime.lookup('file.otf')); + +// +// Test charsets +// + +assert.equal('UTF-8', mime.charsets.lookup('text/plain')); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.js)); +assert.equal('UTF-8', mime.charsets.lookup(mime.types.json)); +assert.equal(undefined, mime.charsets.lookup(mime.types.bin)); +assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); + +console.log('\nAll tests passed'); diff --git a/node_modules/mime/cli.js b/node_modules/mime/cli.js new file mode 100644 index 00000000..20b1ffeb --- /dev/null +++ b/node_modules/mime/cli.js @@ -0,0 +1,8 @@ +#!/usr/bin/env node + +var mime = require('./mime.js'); +var file = process.argv[2]; +var type = mime.lookup(file); + +process.stdout.write(type + '\n'); + diff --git a/node_modules/mime/mime.js b/node_modules/mime/mime.js new file mode 100644 index 00000000..d7efbde7 --- /dev/null +++ b/node_modules/mime/mime.js @@ -0,0 +1,108 @@ +var path = require('path'); +var fs = require('fs'); + +function Mime() { + // Map of extension -> mime type + this.types = Object.create(null); + + // Map of mime type -> extension + this.extensions = Object.create(null); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * @param map (Object) type definitions + */ +Mime.prototype.define = function (map) { + for (var type in map) { + var exts = map[type]; + for (var i = 0; i < exts.length; i++) { + if (process.env.DEBUG_MIME && this.types[exts[i]]) { + console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + + this.types[exts[i]] + ' to ' + type); + } + + this.types[exts[i]] = type; + } + + // Default extension is the first one we encounter + if (!this.extensions[type]) { + this.extensions[type] = exts[0]; + } + } +}; + +/** + * Load an Apache2-style ".types" file + * + * This may be called multiple times (it's expected). Where files declare + * overlapping types/extensions, the last file wins. + * + * @param file (String) path of file to load. + */ +Mime.prototype.load = function(file) { + this._loading = file; + // Read file and split into lines + var map = {}, + content = fs.readFileSync(file, 'ascii'), + lines = content.split(/[\r\n]+/); + + lines.forEach(function(line) { + // Clean up whitespace/comments, and split into fields + var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); + map[fields.shift()] = fields; + }); + + this.define(map); + + this._loading = null; +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.lookup = function(path, fallback) { + var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase(); + + return this.types[ext] || fallback || this.default_type; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.extension = function(mimeType) { + var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); + return this.extensions[type]; +}; + +// Default instance +var mime = new Mime(); + +// Define built-in types +mime.define(require('./types.json')); + +// Default type +mime.default_type = mime.lookup('bin'); + +// +// Additional API specific to the default instance +// + +mime.Mime = Mime; + +/** + * Lookup a charset based on mime type. + */ +mime.charsets = { + lookup: function(mimeType, fallback) { + // Assume text types are utf8 + return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback; + } +}; + +module.exports = mime; diff --git a/node_modules/mime/package.json b/node_modules/mime/package.json new file mode 100644 index 00000000..80f7b69b --- /dev/null +++ b/node_modules/mime/package.json @@ -0,0 +1,70 @@ +{ + "_args": [ + [ + "mime@1.4.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "mime@1.4.1", + "_id": "mime@1.4.1", + "_inBundle": false, + "_integrity": "sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ==", + "_location": "/mime", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "mime@1.4.1", + "name": "mime", + "escapedName": "mime", + "rawSpec": "1.4.1", + "saveSpec": null, + "fetchSpec": "1.4.1" + }, + "_requiredBy": [ + "/send" + ], + "_resolved": "https://registry.npmjs.org/mime/-/mime-1.4.1.tgz", + "_spec": "1.4.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Robert Kieffer", + "email": "robert@broofa.com", + "url": "http://github.com/broofa" + }, + "bin": { + "mime": "cli.js" + }, + "bugs": { + "url": "https://github.com/broofa/node-mime/issues" + }, + "contributors": [ + { + "name": "Benjamin Thomas", + "email": "benjamin@benjaminthomas.org", + "url": "http://github.com/bentomas" + } + ], + "dependencies": {}, + "description": "A comprehensive library for mime-type mapping", + "devDependencies": { + "mime-db": "1.30.0" + }, + "homepage": "https://github.com/broofa/node-mime#readme", + "keywords": [ + "util", + "mime" + ], + "license": "MIT", + "main": "mime.js", + "name": "mime", + "repository": { + "url": "git+https://github.com/broofa/node-mime.git", + "type": "git" + }, + "scripts": { + "prepublish": "node build/build.js > types.json", + "test": "node build/test.js" + }, + "version": "1.4.1" +} diff --git a/node_modules/mime/types.json b/node_modules/mime/types.json new file mode 100644 index 00000000..5369cd1c --- /dev/null +++ b/node_modules/mime/types.json @@ -0,0 +1 @@ +{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomsvc+xml":["atomsvc"],"application/bdoc":["bdoc"],"application/ccxml+xml":["ccxml"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["ecma"],"application/emma+xml":["emma"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/font-tdpfr":["pfr"],"application/font-woff":["woff"],"application/font-woff2":["woff2"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/prs.cww":["cww"],"application/pskc+xml":["pskcxml"],"application/rdf+xml":["rdf"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/voicexml+xml":["vxml"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-otf":["otf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-ttf":["ttf","ttc"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["iso"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["exe"],"application/x-msdownload":["exe","dll","com","bat","msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["wmf","wmz","emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["prc","pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"application/xaml+xml":["xaml"],"application/xcap-diff+xml":["xdf"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["3gpp"],"audio/adpcm":["adp"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mp3":["mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/wav":["wav"],"audio/wave":["wav"],"audio/webm":["weba"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["ra"],"audio/x-wav":["wav"],"audio/xm":["xm"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"font/otf":["otf"],"image/apng":["apng"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/g3fax":["g3"],"image/gif":["gif"],"image/ief":["ief"],"image/jpeg":["jpeg","jpg","jpe"],"image/ktx":["ktx"],"image/png":["png"],"image/prs.btif":["btif"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/tiff":["tiff","tif"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/webp":["webp"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["bmp"],"image/x-pcx":["pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/rfc822":["eml","mime"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.vtu":["vtu"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["x3db","x3dbz"],"model/x3d+vrml":["x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/hjson":["hjson"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/prs.lines.tag":["dsc"],"text/richtext":["rtx"],"text/rtf":["rtf"],"text/sgml":["sgml","sgm"],"text/slim":["slim","slm"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/vtt":["vtt"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"text/xml":["xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/jpeg":["jpgv"],"video/jpm":["jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/webm":["webm"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 00000000..6a522b16 --- /dev/null +++ b/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/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 00000000..69b61253 --- /dev/null +++ b/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/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 00000000..5d98ac8a --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,73 @@ +{ + "_args": [ + [ + "ms@2.0.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "ms@2.0.0", + "_id": "ms@2.0.0", + "_inBundle": false, + "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "_location": "/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@2.0.0", + "name": "ms", + "escapedName": "ms", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/debug", + "/send" + ], + "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "_spec": "2.0.0", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/zeit/ms/issues" + }, + "description": "Tiny milisecond conversion utility", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/zeit/ms#readme", + "license": "MIT", + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git+https://github.com/zeit/ms.git" + }, + "scripts": { + "lint": "eslint lib/* bin/*", + "precommit": "lint-staged", + "test": "mocha tests.js" + }, + "version": "2.0.0" +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 00000000..84a9974c --- /dev/null +++ b/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/negotiator/HISTORY.md b/node_modules/negotiator/HISTORY.md new file mode 100644 index 00000000..10b69179 --- /dev/null +++ b/node_modules/negotiator/HISTORY.md @@ -0,0 +1,98 @@ +0.6.1 / 2016-05-02 +================== + + * perf: improve `Accept` parsing speed + * perf: improve `Accept-Charset` parsing speed + * perf: improve `Accept-Encoding` parsing speed + * perf: improve `Accept-Language` parsing speed + +0.6.0 / 2015-09-29 +================== + + * Fix including type extensions in parameters in `Accept` parsing + * Fix parsing `Accept` parameters with quoted equals + * Fix parsing `Accept` parameters with quoted semicolons + * Lazy-load modules from main entry point + * perf: delay type concatenation until needed + * perf: enable strict mode + * perf: hoist regular expressions + * perf: remove closures getting spec properties + * perf: remove a closure from media type parsing + * perf: remove property delete from media type parsing + +0.5.3 / 2015-05-10 +================== + + * Fix media type parameter matching to be case-insensitive + +0.5.2 / 2015-05-06 +================== + + * Fix comparing media types with quoted values + * Fix splitting media types with quoted commas + +0.5.1 / 2015-02-14 +================== + + * Fix preference sorting to be stable for long acceptable lists + +0.5.0 / 2014-12-18 +================== + + * Fix list return order when large accepted list + * Fix missing identity encoding when q=0 exists + * Remove dynamic building of Negotiator class + +0.4.9 / 2014-10-14 +================== + + * Fix error when media type has invalid parameter + +0.4.8 / 2014-09-28 +================== + + * Fix all negotiations to be case-insensitive + * Stable sort preferences of same quality according to client order + * Support Node.js 0.6 + +0.4.7 / 2014-06-24 +================== + + * Handle invalid provided languages + * Handle invalid provided media types + +0.4.6 / 2014-06-11 +================== + + * Order by specificity when quality is the same + +0.4.5 / 2014-05-29 +================== + + * Fix regression in empty header handling + +0.4.4 / 2014-05-29 +================== + + * Fix behaviors when headers are not present + +0.4.3 / 2014-04-16 +================== + + * Handle slashes on media params correctly + +0.4.2 / 2014-02-28 +================== + + * Fix media type sorting + * Handle media types params strictly + +0.4.1 / 2014-01-16 +================== + + * Use most specific matches + +0.4.0 / 2014-01-09 +================== + + * Remove preferred prefix from methods diff --git a/node_modules/negotiator/LICENSE b/node_modules/negotiator/LICENSE new file mode 100644 index 00000000..ea6b9e2e --- /dev/null +++ b/node_modules/negotiator/LICENSE @@ -0,0 +1,24 @@ +(The MIT License) + +Copyright (c) 2012-2014 Federico Romero +Copyright (c) 2012-2014 Isaac Z. Schlueter +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/negotiator/README.md b/node_modules/negotiator/README.md new file mode 100644 index 00000000..04a67ff7 --- /dev/null +++ b/node_modules/negotiator/README.md @@ -0,0 +1,203 @@ +# negotiator + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +An HTTP content negotiator for Node.js + +## Installation + +```sh +$ npm install negotiator +``` + +## API + +```js +var Negotiator = require('negotiator') +``` + +### Accept Negotiation + +```js +availableMediaTypes = ['text/html', 'text/plain', 'application/json'] + +// The negotiator constructor receives a request object +negotiator = new Negotiator(request) + +// Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' + +negotiator.mediaTypes() +// -> ['text/html', 'image/jpeg', 'application/*'] + +negotiator.mediaTypes(availableMediaTypes) +// -> ['text/html', 'application/json'] + +negotiator.mediaType(availableMediaTypes) +// -> 'text/html' +``` + +You can check a working example at `examples/accept.js`. + +#### Methods + +##### mediaType() + +Returns the most preferred media type from the client. + +##### mediaType(availableMediaType) + +Returns the most preferred media type from a list of available media types. + +##### mediaTypes() + +Returns an array of preferred media types ordered by the client preference. + +##### mediaTypes(availableMediaTypes) + +Returns an array of preferred media types ordered by priority from a list of +available media types. + +### Accept-Language Negotiation + +```js +negotiator = new Negotiator(request) + +availableLanguages = ['en', 'es', 'fr'] + +// Let's say Accept-Language header is 'en;q=0.8, es, pt' + +negotiator.languages() +// -> ['es', 'pt', 'en'] + +negotiator.languages(availableLanguages) +// -> ['es', 'en'] + +language = negotiator.language(availableLanguages) +// -> 'es' +``` + +You can check a working example at `examples/language.js`. + +#### Methods + +##### language() + +Returns the most preferred language from the client. + +##### language(availableLanguages) + +Returns the most preferred language from a list of available languages. + +##### languages() + +Returns an array of preferred languages ordered by the client preference. + +##### languages(availableLanguages) + +Returns an array of preferred languages ordered by priority from a list of +available languages. + +### Accept-Charset Negotiation + +```js +availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' + +negotiator.charsets() +// -> ['utf-8', 'iso-8859-1', 'utf-7'] + +negotiator.charsets(availableCharsets) +// -> ['utf-8', 'iso-8859-1'] + +negotiator.charset(availableCharsets) +// -> 'utf-8' +``` + +You can check a working example at `examples/charset.js`. + +#### Methods + +##### charset() + +Returns the most preferred charset from the client. + +##### charset(availableCharsets) + +Returns the most preferred charset from a list of available charsets. + +##### charsets() + +Returns an array of preferred charsets ordered by the client preference. + +##### charsets(availableCharsets) + +Returns an array of preferred charsets ordered by priority from a list of +available charsets. + +### Accept-Encoding Negotiation + +```js +availableEncodings = ['identity', 'gzip'] + +negotiator = new Negotiator(request) + +// Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' + +negotiator.encodings() +// -> ['gzip', 'identity', 'compress'] + +negotiator.encodings(availableEncodings) +// -> ['gzip', 'identity'] + +negotiator.encoding(availableEncodings) +// -> 'gzip' +``` + +You can check a working example at `examples/encoding.js`. + +#### Methods + +##### encoding() + +Returns the most preferred encoding from the client. + +##### encoding(availableEncodings) + +Returns the most preferred encoding from a list of available encodings. + +##### encodings() + +Returns an array of preferred encodings ordered by the client preference. + +##### encodings(availableEncodings) + +Returns an array of preferred encodings ordered by priority from a list of +available encodings. + +## See Also + +The [accepts](https://npmjs.org/package/accepts#readme) module builds on +this module and provides an alternative interface, mime type validation, +and more. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/negotiator.svg +[npm-url]: https://npmjs.org/package/negotiator +[node-version-image]: https://img.shields.io/node/v/negotiator.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/negotiator/master.svg +[travis-url]: https://travis-ci.org/jshttp/negotiator +[coveralls-image]: https://img.shields.io/coveralls/jshttp/negotiator/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/negotiator?branch=master +[downloads-image]: https://img.shields.io/npm/dm/negotiator.svg +[downloads-url]: https://npmjs.org/package/negotiator diff --git a/node_modules/negotiator/index.js b/node_modules/negotiator/index.js new file mode 100644 index 00000000..8d4f6a22 --- /dev/null +++ b/node_modules/negotiator/index.js @@ -0,0 +1,124 @@ +/*! + * negotiator + * Copyright(c) 2012 Federico Romero + * Copyright(c) 2012-2014 Isaac Z. Schlueter + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Cached loaded submodules. + * @private + */ + +var modules = Object.create(null); + +/** + * Module exports. + * @public + */ + +module.exports = Negotiator; +module.exports.Negotiator = Negotiator; + +/** + * Create a Negotiator instance from a request. + * @param {object} request + * @public + */ + +function Negotiator(request) { + if (!(this instanceof Negotiator)) { + return new Negotiator(request); + } + + this.request = request; +} + +Negotiator.prototype.charset = function charset(available) { + var set = this.charsets(available); + return set && set[0]; +}; + +Negotiator.prototype.charsets = function charsets(available) { + var preferredCharsets = loadModule('charset').preferredCharsets; + return preferredCharsets(this.request.headers['accept-charset'], available); +}; + +Negotiator.prototype.encoding = function encoding(available) { + var set = this.encodings(available); + return set && set[0]; +}; + +Negotiator.prototype.encodings = function encodings(available) { + var preferredEncodings = loadModule('encoding').preferredEncodings; + return preferredEncodings(this.request.headers['accept-encoding'], available); +}; + +Negotiator.prototype.language = function language(available) { + var set = this.languages(available); + return set && set[0]; +}; + +Negotiator.prototype.languages = function languages(available) { + var preferredLanguages = loadModule('language').preferredLanguages; + return preferredLanguages(this.request.headers['accept-language'], available); +}; + +Negotiator.prototype.mediaType = function mediaType(available) { + var set = this.mediaTypes(available); + return set && set[0]; +}; + +Negotiator.prototype.mediaTypes = function mediaTypes(available) { + var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes; + return preferredMediaTypes(this.request.headers.accept, available); +}; + +// Backwards compatibility +Negotiator.prototype.preferredCharset = Negotiator.prototype.charset; +Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets; +Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding; +Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings; +Negotiator.prototype.preferredLanguage = Negotiator.prototype.language; +Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages; +Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType; +Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes; + +/** + * Load the given module. + * @private + */ + +function loadModule(moduleName) { + var module = modules[moduleName]; + + if (module !== undefined) { + return module; + } + + // This uses a switch for static require analysis + switch (moduleName) { + case 'charset': + module = require('./lib/charset'); + break; + case 'encoding': + module = require('./lib/encoding'); + break; + case 'language': + module = require('./lib/language'); + break; + case 'mediaType': + module = require('./lib/mediaType'); + break; + default: + throw new Error('Cannot find module \'' + moduleName + '\''); + } + + // Store to prevent invoking require() + modules[moduleName] = module; + + return module; +} diff --git a/node_modules/negotiator/lib/charset.js b/node_modules/negotiator/lib/charset.js new file mode 100644 index 00000000..ac4217b4 --- /dev/null +++ b/node_modules/negotiator/lib/charset.js @@ -0,0 +1,169 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredCharsets; +module.exports.preferredCharsets = preferredCharsets; + +/** + * Module variables. + * @private + */ + +var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Charset header. + * @private + */ + +function parseAcceptCharset(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var charset = parseCharset(accepts[i].trim(), i); + + if (charset) { + accepts[j++] = charset; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a charset from the Accept-Charset header. + * @private + */ + +function parseCharset(str, i) { + var match = simpleCharsetRegExp.exec(str); + if (!match) return null; + + var charset = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + charset: charset, + q: q, + i: i + }; +} + +/** + * Get the priority of a charset. + * @private + */ + +function getCharsetPriority(charset, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(charset, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the charset. + * @private + */ + +function specify(charset, spec, index) { + var s = 0; + if(spec.charset.toLowerCase() === charset.toLowerCase()){ + s |= 1; + } else if (spec.charset !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +} + +/** + * Get the preferred charsets from an Accept-Charset header. + * @public + */ + +function preferredCharsets(accept, provided) { + // RFC 2616 sec 14.2: no header = * + var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all charsets + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullCharset); + } + + var priorities = provided.map(function getPriority(type, index) { + return getCharsetPriority(type, accepts, index); + }); + + // sorted list of accepted charsets + return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full charset string. + * @private + */ + +function getFullCharset(spec) { + return spec.charset; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/encoding.js b/node_modules/negotiator/lib/encoding.js new file mode 100644 index 00000000..70ac3de6 --- /dev/null +++ b/node_modules/negotiator/lib/encoding.js @@ -0,0 +1,184 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredEncodings; +module.exports.preferredEncodings = preferredEncodings; + +/** + * Module variables. + * @private + */ + +var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Encoding header. + * @private + */ + +function parseAcceptEncoding(accept) { + var accepts = accept.split(','); + var hasIdentity = false; + var minQuality = 1; + + for (var i = 0, j = 0; i < accepts.length; i++) { + var encoding = parseEncoding(accepts[i].trim(), i); + + if (encoding) { + accepts[j++] = encoding; + hasIdentity = hasIdentity || specify('identity', encoding); + minQuality = Math.min(minQuality, encoding.q || 1); + } + } + + if (!hasIdentity) { + /* + * If identity doesn't explicitly appear in the accept-encoding header, + * it's added to the list of acceptable encoding with the lowest q + */ + accepts[j++] = { + encoding: 'identity', + q: minQuality, + i: i + }; + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse an encoding from the Accept-Encoding header. + * @private + */ + +function parseEncoding(str, i) { + var match = simpleEncodingRegExp.exec(str); + if (!match) return null; + + var encoding = match[1]; + var q = 1; + if (match[2]) { + var params = match[2].split(';'); + for (var i = 0; i < params.length; i ++) { + var p = params[i].trim().split('='); + if (p[0] === 'q') { + q = parseFloat(p[1]); + break; + } + } + } + + return { + encoding: encoding, + q: q, + i: i + }; +} + +/** + * Get the priority of an encoding. + * @private + */ + +function getEncodingPriority(encoding, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(encoding, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the encoding. + * @private + */ + +function specify(encoding, spec, index) { + var s = 0; + if(spec.encoding.toLowerCase() === encoding.toLowerCase()){ + s |= 1; + } else if (spec.encoding !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred encodings from an Accept-Encoding header. + * @public + */ + +function preferredEncodings(accept, provided) { + var accepts = parseAcceptEncoding(accept || ''); + + if (!provided) { + // sorted list of all encodings + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullEncoding); + } + + var priorities = provided.map(function getPriority(type, index) { + return getEncodingPriority(type, accepts, index); + }); + + // sorted list of accepted encodings + return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full encoding string. + * @private + */ + +function getFullEncoding(spec) { + return spec.encoding; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/language.js b/node_modules/negotiator/lib/language.js new file mode 100644 index 00000000..1bd2d0e1 --- /dev/null +++ b/node_modules/negotiator/lib/language.js @@ -0,0 +1,179 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredLanguages; +module.exports.preferredLanguages = preferredLanguages; + +/** + * Module variables. + * @private + */ + +var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/; + +/** + * Parse the Accept-Language header. + * @private + */ + +function parseAcceptLanguage(accept) { + var accepts = accept.split(','); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var langauge = parseLanguage(accepts[i].trim(), i); + + if (langauge) { + accepts[j++] = langauge; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a language from the Accept-Language header. + * @private + */ + +function parseLanguage(str, i) { + var match = simpleLanguageRegExp.exec(str); + if (!match) return null; + + var prefix = match[1], + suffix = match[2], + full = prefix; + + if (suffix) full += "-" + suffix; + + var q = 1; + if (match[3]) { + var params = match[3].split(';') + for (var i = 0; i < params.length; i ++) { + var p = params[i].split('='); + if (p[0] === 'q') q = parseFloat(p[1]); + } + } + + return { + prefix: prefix, + suffix: suffix, + q: q, + i: i, + full: full + }; +} + +/** + * Get the priority of a language. + * @private + */ + +function getLanguagePriority(language, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(language, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the language. + * @private + */ + +function specify(language, spec, index) { + var p = parseLanguage(language) + if (!p) return null; + var s = 0; + if(spec.full.toLowerCase() === p.full.toLowerCase()){ + s |= 4; + } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) { + s |= 2; + } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) { + s |= 1; + } else if (spec.full !== '*' ) { + return null + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s + } +}; + +/** + * Get the preferred languages from an Accept-Language header. + * @public + */ + +function preferredLanguages(accept, provided) { + // RFC 2616 sec 14.4: no header = * + var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || ''); + + if (!provided) { + // sorted list of all languages + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullLanguage); + } + + var priorities = provided.map(function getPriority(type, index) { + return getLanguagePriority(type, accepts, index); + }); + + // sorted list of accepted languages + return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full language string. + * @private + */ + +function getFullLanguage(spec) { + return spec.full; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} diff --git a/node_modules/negotiator/lib/mediaType.js b/node_modules/negotiator/lib/mediaType.js new file mode 100644 index 00000000..67309dd7 --- /dev/null +++ b/node_modules/negotiator/lib/mediaType.js @@ -0,0 +1,294 @@ +/** + * negotiator + * Copyright(c) 2012 Isaac Z. Schlueter + * Copyright(c) 2014 Federico Romero + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict'; + +/** + * Module exports. + * @public + */ + +module.exports = preferredMediaTypes; +module.exports.preferredMediaTypes = preferredMediaTypes; + +/** + * Module variables. + * @private + */ + +var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/; + +/** + * Parse the Accept header. + * @private + */ + +function parseAccept(accept) { + var accepts = splitMediaTypes(accept); + + for (var i = 0, j = 0; i < accepts.length; i++) { + var mediaType = parseMediaType(accepts[i].trim(), i); + + if (mediaType) { + accepts[j++] = mediaType; + } + } + + // trim accepts + accepts.length = j; + + return accepts; +} + +/** + * Parse a media type from the Accept header. + * @private + */ + +function parseMediaType(str, i) { + var match = simpleMediaTypeRegExp.exec(str); + if (!match) return null; + + var params = Object.create(null); + var q = 1; + var subtype = match[2]; + var type = match[1]; + + if (match[3]) { + var kvps = splitParameters(match[3]).map(splitKeyValuePair); + + for (var j = 0; j < kvps.length; j++) { + var pair = kvps[j]; + var key = pair[0].toLowerCase(); + var val = pair[1]; + + // get the value, unwrapping quotes + var value = val && val[0] === '"' && val[val.length - 1] === '"' + ? val.substr(1, val.length - 2) + : val; + + if (key === 'q') { + q = parseFloat(value); + break; + } + + // store parameter + params[key] = value; + } + } + + return { + type: type, + subtype: subtype, + params: params, + q: q, + i: i + }; +} + +/** + * Get the priority of a media type. + * @private + */ + +function getMediaTypePriority(type, accepted, index) { + var priority = {o: -1, q: 0, s: 0}; + + for (var i = 0; i < accepted.length; i++) { + var spec = specify(type, accepted[i], index); + + if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) { + priority = spec; + } + } + + return priority; +} + +/** + * Get the specificity of the media type. + * @private + */ + +function specify(type, spec, index) { + var p = parseMediaType(type); + var s = 0; + + if (!p) { + return null; + } + + if(spec.type.toLowerCase() == p.type.toLowerCase()) { + s |= 4 + } else if(spec.type != '*') { + return null; + } + + if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) { + s |= 2 + } else if(spec.subtype != '*') { + return null; + } + + var keys = Object.keys(spec.params); + if (keys.length > 0) { + if (keys.every(function (k) { + return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase(); + })) { + s |= 1 + } else { + return null + } + } + + return { + i: index, + o: spec.i, + q: spec.q, + s: s, + } +} + +/** + * Get the preferred media types from an Accept header. + * @public + */ + +function preferredMediaTypes(accept, provided) { + // RFC 2616 sec 14.2: no header = */* + var accepts = parseAccept(accept === undefined ? '*/*' : accept || ''); + + if (!provided) { + // sorted list of all types + return accepts + .filter(isQuality) + .sort(compareSpecs) + .map(getFullType); + } + + var priorities = provided.map(function getPriority(type, index) { + return getMediaTypePriority(type, accepts, index); + }); + + // sorted list of accepted types + return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) { + return provided[priorities.indexOf(priority)]; + }); +} + +/** + * Compare two specs. + * @private + */ + +function compareSpecs(a, b) { + return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0; +} + +/** + * Get full type string. + * @private + */ + +function getFullType(spec) { + return spec.type + '/' + spec.subtype; +} + +/** + * Check if a spec has any quality. + * @private + */ + +function isQuality(spec) { + return spec.q > 0; +} + +/** + * Count the number of quotes in a string. + * @private + */ + +function quoteCount(string) { + var count = 0; + var index = 0; + + while ((index = string.indexOf('"', index)) !== -1) { + count++; + index++; + } + + return count; +} + +/** + * Split a key value pair. + * @private + */ + +function splitKeyValuePair(str) { + var index = str.indexOf('='); + var key; + var val; + + if (index === -1) { + key = str; + } else { + key = str.substr(0, index); + val = str.substr(index + 1); + } + + return [key, val]; +} + +/** + * Split an Accept header into media types. + * @private + */ + +function splitMediaTypes(accept) { + var accepts = accept.split(','); + + for (var i = 1, j = 0; i < accepts.length; i++) { + if (quoteCount(accepts[j]) % 2 == 0) { + accepts[++j] = accepts[i]; + } else { + accepts[j] += ',' + accepts[i]; + } + } + + // trim accepts + accepts.length = j + 1; + + return accepts; +} + +/** + * Split a string of parameters. + * @private + */ + +function splitParameters(str) { + var parameters = str.split(';'); + + for (var i = 1, j = 0; i < parameters.length; i++) { + if (quoteCount(parameters[j]) % 2 == 0) { + parameters[++j] = parameters[i]; + } else { + parameters[j] += ';' + parameters[i]; + } + } + + // trim parameters + parameters.length = j + 1; + + for (var i = 0; i < parameters.length; i++) { + parameters[i] = parameters[i].trim(); + } + + return parameters; +} diff --git a/node_modules/negotiator/package.json b/node_modules/negotiator/package.json new file mode 100644 index 00000000..c70a0441 --- /dev/null +++ b/node_modules/negotiator/package.json @@ -0,0 +1,84 @@ +{ + "_args": [ + [ + "negotiator@0.6.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "negotiator@0.6.1", + "_id": "negotiator@0.6.1", + "_inBundle": false, + "_integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk=", + "_location": "/negotiator", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "negotiator@0.6.1", + "name": "negotiator", + "escapedName": "negotiator", + "rawSpec": "0.6.1", + "saveSpec": null, + "fetchSpec": "0.6.1" + }, + "_requiredBy": [ + "/accepts" + ], + "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz", + "_spec": "0.6.1", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/negotiator/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Federico Romero", + "email": "federico.romero@outboxlabs.com" + }, + { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + } + ], + "description": "HTTP content negotiation", + "devDependencies": { + "istanbul": "0.4.3", + "mocha": "~1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "lib/", + "HISTORY.md", + "LICENSE", + "index.js", + "README.md" + ], + "homepage": "https://github.com/jshttp/negotiator#readme", + "keywords": [ + "http", + "content negotiation", + "accept", + "accept-language", + "accept-encoding", + "accept-charset" + ], + "license": "MIT", + "name": "negotiator", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/negotiator.git" + }, + "scripts": { + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "0.6.1" +} diff --git a/node_modules/on-finished/HISTORY.md b/node_modules/on-finished/HISTORY.md new file mode 100644 index 00000000..98ff0e99 --- /dev/null +++ b/node_modules/on-finished/HISTORY.md @@ -0,0 +1,88 @@ +2.3.0 / 2015-05-26 +================== + + * Add defined behavior for HTTP `CONNECT` requests + * Add defined behavior for HTTP `Upgrade` requests + * deps: ee-first@1.1.1 + +2.2.1 / 2015-04-22 +================== + + * Fix `isFinished(req)` when data buffered + +2.2.0 / 2014-12-22 +================== + + * Add message object to callback arguments + +2.1.1 / 2014-10-22 +================== + + * Fix handling of pipelined requests + +2.1.0 / 2014-08-16 +================== + + * Check if `socket` is detached + * Return `undefined` for `isFinished` if state unknown + +2.0.0 / 2014-08-16 +================== + + * Add `isFinished` function + * Move to `jshttp` organization + * Remove support for plain socket argument + * Rename to `on-finished` + * Support both `req` and `res` as arguments + * deps: ee-first@1.0.5 + +1.2.2 / 2014-06-10 +================== + + * Reduce listeners added to emitters + - avoids "event emitter leak" warnings when used multiple times on same request + +1.2.1 / 2014-06-08 +================== + + * Fix returned value when already finished + +1.2.0 / 2014-06-05 +================== + + * Call callback when called on already-finished socket + +1.1.4 / 2014-05-27 +================== + + * Support node.js 0.8 + +1.1.3 / 2014-04-30 +================== + + * Make sure errors passed as instanceof `Error` + +1.1.2 / 2014-04-18 +================== + + * Default the `socket` to passed-in object + +1.1.1 / 2014-01-16 +================== + + * Rename module to `finished` + +1.1.0 / 2013-12-25 +================== + + * Call callback when called on already-errored socket + +1.0.1 / 2013-12-20 +================== + + * Actually pass the error to the callback + +1.0.0 / 2013-12-20 +================== + + * Initial release diff --git a/node_modules/on-finished/LICENSE b/node_modules/on-finished/LICENSE new file mode 100644 index 00000000..5931fd23 --- /dev/null +++ b/node_modules/on-finished/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2013 Jonathan Ong +Copyright (c) 2014 Douglas Christopher Wilson + +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/on-finished/README.md b/node_modules/on-finished/README.md new file mode 100644 index 00000000..a0e11574 --- /dev/null +++ b/node_modules/on-finished/README.md @@ -0,0 +1,154 @@ +# on-finished + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Execute a callback when a HTTP request closes, finishes, or errors. + +## Install + +```sh +$ npm install on-finished +``` + +## API + +```js +var onFinished = require('on-finished') +``` + +### onFinished(res, listener) + +Attach a listener to listen for the response to finish. The listener will +be invoked only once when the response finished. If the response finished +to an error, the first argument will contain the error. If the response +has already finished, the listener will be invoked. + +Listening to the end of a response would be used to close things associated +with the response, like open files. + +Listener is invoked as `listener(err, res)`. + +```js +onFinished(res, function (err, res) { + // clean up open fds, etc. + // err contains the error is request error'd +}) +``` + +### onFinished(req, listener) + +Attach a listener to listen for the request to finish. The listener will +be invoked only once when the request finished. If the request finished +to an error, the first argument will contain the error. If the request +has already finished, the listener will be invoked. + +Listening to the end of a request would be used to know when to continue +after reading the data. + +Listener is invoked as `listener(err, req)`. + +```js +var data = '' + +req.setEncoding('utf8') +res.on('data', function (str) { + data += str +}) + +onFinished(req, function (err, req) { + // data is read unless there is err +}) +``` + +### onFinished.isFinished(res) + +Determine if `res` is already finished. This would be useful to check and +not even start certain operations if the response has already finished. + +### onFinished.isFinished(req) + +Determine if `req` is already finished. This would be useful to check and +not even start certain operations if the request has already finished. + +## Special Node.js requests + +### HTTP CONNECT method + +The meaning of the `CONNECT` method from RFC 7231, section 4.3.6: + +> The CONNECT method requests that the recipient establish a tunnel to +> the destination origin server identified by the request-target and, +> if successful, thereafter restrict its behavior to blind forwarding +> of packets, in both directions, until the tunnel is closed. Tunnels +> are commonly used to create an end-to-end virtual connection, through +> one or more proxies, which can then be secured using TLS (Transport +> Layer Security, [RFC5246]). + +In Node.js, these request objects come from the `'connect'` event on +the HTTP server. + +When this module is used on a HTTP `CONNECT` request, the request is +considered "finished" immediately, **due to limitations in the Node.js +interface**. This means if the `CONNECT` request contains a request entity, +the request will be considered "finished" even before it has been read. + +There is no such thing as a response object to a `CONNECT` request in +Node.js, so there is no support for for one. + +### HTTP Upgrade request + +The meaning of the `Upgrade` header from RFC 7230, section 6.1: + +> The "Upgrade" header field is intended to provide a simple mechanism +> for transitioning from HTTP/1.1 to some other protocol on the same +> connection. + +In Node.js, these request objects come from the `'upgrade'` event on +the HTTP server. + +When this module is used on a HTTP request with an `Upgrade` header, the +request is considered "finished" immediately, **due to limitations in the +Node.js interface**. This means if the `Upgrade` request contains a request +entity, the request will be considered "finished" even before it has been +read. + +There is no such thing as a response object to a `Upgrade` request in +Node.js, so there is no support for for one. + +## Example + +The following code ensures that file descriptors are always closed +once the response finishes. + +```js +var destroy = require('destroy') +var http = require('http') +var onFinished = require('on-finished') + +http.createServer(function onRequest(req, res) { + var stream = fs.createReadStream('package.json') + stream.pipe(res) + onFinished(res, function (err) { + destroy(stream) + }) +}) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/on-finished.svg +[npm-url]: https://npmjs.org/package/on-finished +[node-version-image]: https://img.shields.io/node/v/on-finished.svg +[node-version-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/jshttp/on-finished/master.svg +[travis-url]: https://travis-ci.org/jshttp/on-finished +[coveralls-image]: https://img.shields.io/coveralls/jshttp/on-finished/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/on-finished?branch=master +[downloads-image]: https://img.shields.io/npm/dm/on-finished.svg +[downloads-url]: https://npmjs.org/package/on-finished diff --git a/node_modules/on-finished/index.js b/node_modules/on-finished/index.js new file mode 100644 index 00000000..9abd98f9 --- /dev/null +++ b/node_modules/on-finished/index.js @@ -0,0 +1,196 @@ +/*! + * on-finished + * Copyright(c) 2013 Jonathan Ong + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = onFinished +module.exports.isFinished = isFinished + +/** + * Module dependencies. + * @private + */ + +var first = require('ee-first') + +/** + * Variables. + * @private + */ + +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) } + +/** + * Invoke callback when the response has finished, useful for + * cleaning up resources afterwards. + * + * @param {object} msg + * @param {function} listener + * @return {object} + * @public + */ + +function onFinished(msg, listener) { + if (isFinished(msg) !== false) { + defer(listener, null, msg) + return msg + } + + // attach the listener to the message + attachListener(msg, listener) + + return msg +} + +/** + * Determine if message is already finished. + * + * @param {object} msg + * @return {boolean} + * @public + */ + +function isFinished(msg) { + var socket = msg.socket + + if (typeof msg.finished === 'boolean') { + // OutgoingMessage + return Boolean(msg.finished || (socket && !socket.writable)) + } + + if (typeof msg.complete === 'boolean') { + // IncomingMessage + return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable)) + } + + // don't know + return undefined +} + +/** + * Attach a finished listener to the message. + * + * @param {object} msg + * @param {function} callback + * @private + */ + +function attachFinishedListener(msg, callback) { + var eeMsg + var eeSocket + var finished = false + + function onFinish(error) { + eeMsg.cancel() + eeSocket.cancel() + + finished = true + callback(error) + } + + // finished on first message event + eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish) + + function onSocket(socket) { + // remove listener + msg.removeListener('socket', onSocket) + + if (finished) return + if (eeMsg !== eeSocket) return + + // finished on first socket event + eeSocket = first([[socket, 'error', 'close']], onFinish) + } + + if (msg.socket) { + // socket already assigned + onSocket(msg.socket) + return + } + + // wait for socket to be assigned + msg.on('socket', onSocket) + + if (msg.socket === undefined) { + // node.js 0.8 patch + patchAssignSocket(msg, onSocket) + } +} + +/** + * Attach the listener to the message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function attachListener(msg, listener) { + var attached = msg.__onFinished + + // create a private single listener with queue + if (!attached || !attached.queue) { + attached = msg.__onFinished = createListener(msg) + attachFinishedListener(msg, attached) + } + + attached.queue.push(listener) +} + +/** + * Create listener on message. + * + * @param {object} msg + * @return {function} + * @private + */ + +function createListener(msg) { + function listener(err) { + if (msg.__onFinished === listener) msg.__onFinished = null + if (!listener.queue) return + + var queue = listener.queue + listener.queue = null + + for (var i = 0; i < queue.length; i++) { + queue[i](err, msg) + } + } + + listener.queue = [] + + return listener +} + +/** + * Patch ServerResponse.prototype.assignSocket for node.js 0.8. + * + * @param {ServerResponse} res + * @param {function} callback + * @private + */ + +function patchAssignSocket(res, callback) { + var assignSocket = res.assignSocket + + if (typeof assignSocket !== 'function') return + + // res.on('socket', callback) is broken in 0.8 + res.assignSocket = function _assignSocket(socket) { + assignSocket.call(this, socket) + callback(socket) + } +} diff --git a/node_modules/on-finished/package.json b/node_modules/on-finished/package.json new file mode 100644 index 00000000..b2756678 --- /dev/null +++ b/node_modules/on-finished/package.json @@ -0,0 +1,76 @@ +{ + "_args": [ + [ + "on-finished@2.3.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "on-finished@2.3.0", + "_id": "on-finished@2.3.0", + "_inBundle": false, + "_integrity": "sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=", + "_location": "/on-finished", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "on-finished@2.3.0", + "name": "on-finished", + "escapedName": "on-finished", + "rawSpec": "2.3.0", + "saveSpec": null, + "fetchSpec": "2.3.0" + }, + "_requiredBy": [ + "/body-parser", + "/express", + "/finalhandler", + "/send" + ], + "_resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz", + "_spec": "2.3.0", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/on-finished/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "dependencies": { + "ee-first": "1.1.1" + }, + "description": "Execute a callback when a request closes, finishes, or errors", + "devDependencies": { + "istanbul": "0.3.9", + "mocha": "2.2.5" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "homepage": "https://github.com/jshttp/on-finished#readme", + "license": "MIT", + "name": "on-finished", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/on-finished.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "2.3.0" +} diff --git a/node_modules/parseurl/HISTORY.md b/node_modules/parseurl/HISTORY.md new file mode 100644 index 00000000..4803393a --- /dev/null +++ b/node_modules/parseurl/HISTORY.md @@ -0,0 +1,53 @@ +1.3.2 / 2017-09-09 +================== + + * perf: reduce overhead for full URLs + * perf: unroll the "fast-path" `RegExp` + +1.3.1 / 2016-01-17 +================== + + * perf: enable strict mode + +1.3.0 / 2014-08-09 +================== + + * Add `parseurl.original` for parsing `req.originalUrl` with fallback + * Return `undefined` if `req.url` is `undefined` + +1.2.0 / 2014-07-21 +================== + + * Cache URLs based on original value + * Remove no-longer-needed URL mis-parse work-around + * Simplify the "fast-path" `RegExp` + +1.1.3 / 2014-07-08 +================== + + * Fix typo + +1.1.2 / 2014-07-08 +================== + + * Seriously fix Node.js 0.8 compatibility + +1.1.1 / 2014-07-08 +================== + + * Fix Node.js 0.8 compatibility + +1.1.0 / 2014-07-08 +================== + + * Incorporate URL href-only parse fast-path + +1.0.1 / 2014-03-08 +================== + + * Add missing `require` + +1.0.0 / 2014-03-08 +================== + + * Genesis from `connect` diff --git a/node_modules/parseurl/LICENSE b/node_modules/parseurl/LICENSE new file mode 100644 index 00000000..27653d3d --- /dev/null +++ b/node_modules/parseurl/LICENSE @@ -0,0 +1,24 @@ + +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/parseurl/README.md b/node_modules/parseurl/README.md new file mode 100644 index 00000000..a5ccc51b --- /dev/null +++ b/node_modules/parseurl/README.md @@ -0,0 +1,124 @@ +# parseurl + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Parse a URL with memoization. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install parseurl +``` + +## API + +```js +var parseurl = require('parseurl') +``` + +### parseurl(req) + +Parse the URL of the given request object (looks at the `req.url` property) +and return the result. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.url` does +not change will return a cached parsed object, rather than parsing again. + +### parseurl.original(req) + +Parse the original URL of the given request object and return the result. +This works by trying to parse `req.originalUrl` if it is a string, otherwise +parses `req.url`. The result is the same as `url.parse` in Node.js core. +Calling this function multiple times on the same `req` where `req.originalUrl` +does not change will return a cached parsed object, rather than parsing again. + +## Benchmark + +```bash +$ npm run-script bench + +> parseurl@1.3.2 bench nodejs-parseurl +> node benchmark/index.js + + http_parser@2.7.0 + node@4.8.4 + v8@4.5.103.47 + uv@1.9.1 + zlib@1.2.11 + ares@1.10.1-DEV + icu@56.1 + modules@46 + openssl@1.0.2k + +> node benchmark/fullurl.js + + Parsing URL "http://localhost:8888/foo/bar?user=tj&pet=fluffy" + + 3 tests completed. + + fasturl x 1,246,766 ops/sec ±0.74% (188 runs sampled) + nativeurl x 91,536 ops/sec ±0.54% (189 runs sampled) + parseurl x 90,645 ops/sec ±0.38% (189 runs sampled) + +> node benchmark/pathquery.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" + + 3 tests completed. + + fasturl x 2,077,650 ops/sec ±0.69% (186 runs sampled) + nativeurl x 638,669 ops/sec ±0.67% (189 runs sampled) + parseurl x 2,431,842 ops/sec ±0.71% (189 runs sampled) + +> node benchmark/samerequest.js + + Parsing URL "/foo/bar?user=tj&pet=fluffy" on same request object + + 3 tests completed. + + fasturl x 2,135,391 ops/sec ±0.69% (188 runs sampled) + nativeurl x 672,809 ops/sec ±3.83% (186 runs sampled) + parseurl x 11,604,947 ops/sec ±0.70% (189 runs sampled) + +> node benchmark/simplepath.js + + Parsing URL "/foo/bar" + + 3 tests completed. + + fasturl x 4,961,391 ops/sec ±0.97% (186 runs sampled) + nativeurl x 914,931 ops/sec ±0.83% (186 runs sampled) + parseurl x 7,559,196 ops/sec ±0.66% (188 runs sampled) + +> node benchmark/slash.js + + Parsing URL "/" + + 3 tests completed. + + fasturl x 4,053,379 ops/sec ±0.91% (187 runs sampled) + nativeurl x 963,999 ops/sec ±0.58% (189 runs sampled) + parseurl x 11,516,143 ops/sec ±0.58% (188 runs sampled) +``` + +## License + + [MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/parseurl.svg +[npm-url]: https://npmjs.org/package/parseurl +[node-version-image]: https://img.shields.io/node/v/parseurl.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/pillarjs/parseurl/master.svg +[travis-url]: https://travis-ci.org/pillarjs/parseurl +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/parseurl/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/parseurl?branch=master +[downloads-image]: https://img.shields.io/npm/dm/parseurl.svg +[downloads-url]: https://npmjs.org/package/parseurl diff --git a/node_modules/parseurl/index.js b/node_modules/parseurl/index.js new file mode 100644 index 00000000..603eabe1 --- /dev/null +++ b/node_modules/parseurl/index.js @@ -0,0 +1,154 @@ +/*! + * parseurl + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var url = require('url') +var parse = url.parse +var Url = url.Url + +/** + * Module exports. + * @public + */ + +module.exports = parseurl +module.exports.original = originalurl + +/** + * Parse the `req` url with memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function parseurl (req) { + var url = req.url + + if (url === undefined) { + // URL is undefined + return undefined + } + + var parsed = req._parsedUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedUrl = parsed) +}; + +/** + * Parse the `req` original url with fallback and memoization. + * + * @param {ServerRequest} req + * @return {Object} + * @public + */ + +function originalurl (req) { + var url = req.originalUrl + + if (typeof url !== 'string') { + // Fallback + return parseurl(req) + } + + var parsed = req._parsedOriginalUrl + + if (fresh(url, parsed)) { + // Return cached URL parse + return parsed + } + + // Parse the URL + parsed = fastparse(url) + parsed._raw = url + + return (req._parsedOriginalUrl = parsed) +}; + +/** + * Parse the `str` url with fast-path short-cut. + * + * @param {string} str + * @return {Object} + * @private + */ + +function fastparse (str) { + if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) { + return parse(str) + } + + var pathname = str + var query = null + var search = null + + // This takes the regexp from https://github.com/joyent/node/pull/7878 + // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/ + // And unrolls it into a for loop + for (var i = 1; i < str.length; i++) { + switch (str.charCodeAt(i)) { + case 0x3f: /* ? */ + if (search === null) { + pathname = str.substring(0, i) + query = str.substring(i + 1) + search = str.substring(i) + } + break + case 0x09: /* \t */ + case 0x0a: /* \n */ + case 0x0c: /* \f */ + case 0x0d: /* \r */ + case 0x20: /* */ + case 0x23: /* # */ + case 0xa0: + case 0xfeff: + return parse(str) + } + } + + var url = Url !== undefined + ? new Url() + : {} + url.path = str + url.href = str + url.pathname = pathname + url.query = query + url.search = search + + return url +} + +/** + * Determine if parsed is still fresh for url. + * + * @param {string} url + * @param {object} parsedUrl + * @return {boolean} + * @private + */ + +function fresh (url, parsedUrl) { + return typeof parsedUrl === 'object' && + parsedUrl !== null && + (Url === undefined || parsedUrl instanceof Url) && + parsedUrl._raw === url +} diff --git a/node_modules/parseurl/package.json b/node_modules/parseurl/package.json new file mode 100644 index 00000000..24fadd6e --- /dev/null +++ b/node_modules/parseurl/package.json @@ -0,0 +1,84 @@ +{ + "_args": [ + [ + "parseurl@1.3.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "parseurl@1.3.2", + "_id": "parseurl@1.3.2", + "_inBundle": false, + "_integrity": "sha1-/CidTtiZMRlGDBViUyYs3I3mW/M=", + "_location": "/parseurl", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "parseurl@1.3.2", + "name": "parseurl", + "escapedName": "parseurl", + "rawSpec": "1.3.2", + "saveSpec": null, + "fetchSpec": "1.3.2" + }, + "_requiredBy": [ + "/express", + "/finalhandler", + "/serve-static" + ], + "_resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.2.tgz", + "_spec": "1.3.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/pillarjs/parseurl/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "description": "parse a url with memoization", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "fast-url-parser": "1.1.3", + "istanbul": "0.4.5", + "mocha": "2.5.3" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/pillarjs/parseurl#readme", + "license": "MIT", + "name": "parseurl", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/parseurl.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint .", + "test": "mocha --check-leaks --bail --reporter spec test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec test/" + }, + "version": "1.3.2" +} diff --git a/node_modules/path-to-regexp/History.md b/node_modules/path-to-regexp/History.md new file mode 100644 index 00000000..7f658784 --- /dev/null +++ b/node_modules/path-to-regexp/History.md @@ -0,0 +1,36 @@ +0.1.7 / 2015-07-28 +================== + + * Fixed regression with escaped round brackets and matching groups. + +0.1.6 / 2015-06-19 +================== + + * Replace `index` feature by outputting all parameters, unnamed and named. + +0.1.5 / 2015-05-08 +================== + + * Add an index property for position in match result. + +0.1.4 / 2015-03-05 +================== + + * Add license information + +0.1.3 / 2014-07-06 +================== + + * Better array support + * Improved support for trailing slash in non-ending mode + +0.1.0 / 2014-03-06 +================== + + * add options.end + +0.0.2 / 2013-02-10 +================== + + * Update to match current express + * add .license property to component.json diff --git a/node_modules/path-to-regexp/LICENSE b/node_modules/path-to-regexp/LICENSE new file mode 100644 index 00000000..983fbe8a --- /dev/null +++ b/node_modules/path-to-regexp/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Blake Embrey (hello@blakeembrey.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/path-to-regexp/Readme.md b/node_modules/path-to-regexp/Readme.md new file mode 100644 index 00000000..95452a6e --- /dev/null +++ b/node_modules/path-to-regexp/Readme.md @@ -0,0 +1,35 @@ +# Path-to-RegExp + +Turn an Express-style path string such as `/user/:name` into a regular expression. + +**Note:** This is a legacy branch. You should upgrade to `1.x`. + +## Usage + +```javascript +var pathToRegexp = require('path-to-regexp'); +``` + +### pathToRegexp(path, keys, options) + + - **path** A string in the express format, an array of such strings, or a regular expression + - **keys** An array to be populated with the keys present in the url. Once the function completes, this will be an array of strings. + - **options** + - **options.sensitive** Defaults to false, set this to true to make routes case sensitive + - **options.strict** Defaults to false, set this to true to make the trailing slash matter. + - **options.end** Defaults to true, set this to false to only match the prefix of the URL. + +```javascript +var keys = []; +var exp = pathToRegexp('/foo/:bar', keys); +//keys = ['bar'] +//exp = /^\/foo\/(?:([^\/]+?))\/?$/i +``` + +## Live Demo + +You can see a live demo of this library in use at [express-route-tester](http://forbeslindesay.github.com/express-route-tester/). + +## License + + MIT diff --git a/node_modules/path-to-regexp/index.js b/node_modules/path-to-regexp/index.js new file mode 100644 index 00000000..500d1dad --- /dev/null +++ b/node_modules/path-to-regexp/index.js @@ -0,0 +1,129 @@ +/** + * Expose `pathtoRegexp`. + */ + +module.exports = pathtoRegexp; + +/** + * Match matching groups in a regular expression. + */ +var MATCHING_GROUP_REGEXP = /\((?!\?)/g; + +/** + * Normalize the given path string, + * returning a regular expression. + * + * An empty array should be passed, + * which will contain the placeholder + * key names. For example "/user/:id" will + * then contain ["id"]. + * + * @param {String|RegExp|Array} path + * @param {Array} keys + * @param {Object} options + * @return {RegExp} + * @api private + */ + +function pathtoRegexp(path, keys, options) { + options = options || {}; + keys = keys || []; + var strict = options.strict; + var end = options.end !== false; + var flags = options.sensitive ? '' : 'i'; + var extraOffset = 0; + var keysOffset = keys.length; + var i = 0; + var name = 0; + var m; + + if (path instanceof RegExp) { + while (m = MATCHING_GROUP_REGEXP.exec(path.source)) { + keys.push({ + name: name++, + optional: false, + offset: m.index + }); + } + + return path; + } + + if (Array.isArray(path)) { + // Map array parts into regexps and return their source. We also pass + // the same keys and options instance into every generation to get + // consistent matching groups before we join the sources together. + path = path.map(function (value) { + return pathtoRegexp(value, keys, options).source; + }); + + return new RegExp('(?:' + path.join('|') + ')', flags); + } + + path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?')) + .replace(/\/\(/g, '/(?:') + .replace(/([\/\.])/g, '\\$1') + .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) { + slash = slash || ''; + format = format || ''; + capture = capture || '([^\\/' + format + ']+?)'; + optional = optional || ''; + + keys.push({ + name: key, + optional: !!optional, + offset: offset + extraOffset + }); + + var result = '' + + (optional ? '' : slash) + + '(?:' + + format + (optional ? slash : '') + capture + + (star ? '((?:[\\/' + format + '].+?)?)' : '') + + ')' + + optional; + + extraOffset += result.length - match.length; + + return result; + }) + .replace(/\*/g, function (star, index) { + var len = keys.length + + while (len-- > keysOffset && keys[len].offset > index) { + keys[len].offset += 3; // Replacement length minus asterisk length. + } + + return '(.*)'; + }); + + // This is a workaround for handling unnamed matching groups. + while (m = MATCHING_GROUP_REGEXP.exec(path)) { + var escapeCount = 0; + var index = m.index; + + while (path.charAt(--index) === '\\') { + escapeCount++; + } + + // It's possible to escape the bracket. + if (escapeCount % 2 === 1) { + continue; + } + + if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) { + keys.splice(keysOffset + i, 0, { + name: name++, // Unnamed matching groups must be consistently linear. + optional: false, + offset: m.index + }); + } + + i++; + } + + // If the path is non-ending, match until the end or a slash. + path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)')); + + return new RegExp(path, flags); +}; diff --git a/node_modules/path-to-regexp/package.json b/node_modules/path-to-regexp/package.json new file mode 100644 index 00000000..7574c4b3 --- /dev/null +++ b/node_modules/path-to-regexp/package.json @@ -0,0 +1,62 @@ +{ + "_args": [ + [ + "path-to-regexp@0.1.7", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "path-to-regexp@0.1.7", + "_id": "path-to-regexp@0.1.7", + "_inBundle": false, + "_integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=", + "_location": "/path-to-regexp", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "path-to-regexp@0.1.7", + "name": "path-to-regexp", + "escapedName": "path-to-regexp", + "rawSpec": "0.1.7", + "saveSpec": null, + "fetchSpec": "0.1.7" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "_spec": "0.1.7", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/component/path-to-regexp/issues" + }, + "component": { + "scripts": { + "path-to-regexp": "index.js" + } + }, + "description": "Express style path to RegExp utility", + "devDependencies": { + "istanbul": "^0.2.6", + "mocha": "^1.17.1" + }, + "files": [ + "index.js", + "LICENSE" + ], + "homepage": "https://github.com/component/path-to-regexp#readme", + "keywords": [ + "express", + "regexp" + ], + "license": "MIT", + "name": "path-to-regexp", + "repository": { + "type": "git", + "url": "git+https://github.com/component/path-to-regexp.git" + }, + "scripts": { + "test": "istanbul cover _mocha -- -R spec" + }, + "version": "0.1.7" +} diff --git a/node_modules/proxy-addr/HISTORY.md b/node_modules/proxy-addr/HISTORY.md new file mode 100644 index 00000000..df583291 --- /dev/null +++ b/node_modules/proxy-addr/HISTORY.md @@ -0,0 +1,145 @@ +2.0.4 / 2018-07-26 +================== + + * deps: ipaddr.js@1.8.0 + +2.0.3 / 2018-02-19 +================== + + * deps: ipaddr.js@1.6.0 + +2.0.2 / 2017-09-24 +================== + + * deps: forwarded@~0.1.2 + - perf: improve header parsing + - perf: reduce overhead when no `X-Forwarded-For` header + +2.0.1 / 2017-09-10 +================== + + * deps: forwarded@~0.1.1 + - Fix trimming leading / trailing OWS + - perf: hoist regular expression + * deps: ipaddr.js@1.5.2 + +2.0.0 / 2017-08-08 +================== + + * Drop support for Node.js below 0.10 + +1.1.5 / 2017-07-25 +================== + + * Fix array argument being altered + * deps: ipaddr.js@1.4.0 + +1.1.4 / 2017-03-24 +================== + + * deps: ipaddr.js@1.3.0 + +1.1.3 / 2017-01-14 +================== + + * deps: ipaddr.js@1.2.0 + +1.1.2 / 2016-05-29 +================== + + * deps: ipaddr.js@1.1.1 + - Fix IPv6-mapped IPv4 validation edge cases + +1.1.1 / 2016-05-03 +================== + + * Fix regression matching mixed versions against multiple subnets + +1.1.0 / 2016-05-01 +================== + + * Fix accepting various invalid netmasks + - IPv4 netmasks must be contingous + - IPv6 addresses cannot be used as a netmask + * deps: ipaddr.js@1.1.0 + +1.0.10 / 2015-12-09 +=================== + + * deps: ipaddr.js@1.0.5 + - Fix regression in `isValid` with non-string arguments + +1.0.9 / 2015-12-01 +================== + + * deps: ipaddr.js@1.0.4 + - Fix accepting some invalid IPv6 addresses + - Reject CIDRs with negative or overlong masks + * perf: enable strict mode + +1.0.8 / 2015-05-10 +================== + + * deps: ipaddr.js@1.0.1 + +1.0.7 / 2015-03-16 +================== + + * deps: ipaddr.js@0.1.9 + - Fix OOM on certain inputs to `isValid` + +1.0.6 / 2015-02-01 +================== + + * deps: ipaddr.js@0.1.8 + +1.0.5 / 2015-01-08 +================== + + * deps: ipaddr.js@0.1.6 + +1.0.4 / 2014-11-23 +================== + + * deps: ipaddr.js@0.1.5 + - Fix edge cases with `isValid` + +1.0.3 / 2014-09-21 +================== + + * Use `forwarded` npm module + +1.0.2 / 2014-09-18 +================== + + * Fix a global leak when multiple subnets are trusted + * Support Node.js 0.6 + * deps: ipaddr.js@0.1.3 + +1.0.1 / 2014-06-03 +================== + + * Fix links in npm package + +1.0.0 / 2014-05-08 +================== + + * Add `trust` argument to determine proxy trust on + * Accepts custom function + * Accepts IPv4/IPv6 address(es) + * Accepts subnets + * Accepts pre-defined names + * Add optional `trust` argument to `proxyaddr.all` to + stop at first untrusted + * Add `proxyaddr.compile` to pre-compile `trust` function + to make subsequent calls faster + +0.0.1 / 2014-05-04 +================== + + * Fix bad npm publish + +0.0.0 / 2014-05-04 +================== + + * Initial release diff --git a/node_modules/proxy-addr/LICENSE b/node_modules/proxy-addr/LICENSE new file mode 100644 index 00000000..cab251c2 --- /dev/null +++ b/node_modules/proxy-addr/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/proxy-addr/README.md b/node_modules/proxy-addr/README.md new file mode 100644 index 00000000..0839e1be --- /dev/null +++ b/node_modules/proxy-addr/README.md @@ -0,0 +1,156 @@ +# proxy-addr + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Determine address of proxied request + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install proxy-addr +``` + +## API + + + +```js +var proxyaddr = require('proxy-addr') +``` + +### proxyaddr(req, trust) + +Return the address of the request, using the given `trust` parameter. + +The `trust` argument is a function that returns `true` if you trust +the address, `false` if you don't. The closest untrusted address is +returned. + + + +```js +proxyaddr(req, function (addr) { return addr === '127.0.0.1' }) +proxyaddr(req, function (addr, i) { return i < 1 }) +``` + +The `trust` arugment may also be a single IP address string or an +array of trusted addresses, as plain IP addresses, CIDR-formatted +strings, or IP/netmask strings. + + + +```js +proxyaddr(req, '127.0.0.1') +proxyaddr(req, ['127.0.0.0/8', '10.0.0.0/8']) +proxyaddr(req, ['127.0.0.0/255.0.0.0', '192.168.0.0/255.255.0.0']) +``` + +This module also supports IPv6. Your IPv6 addresses will be normalized +automatically (i.e. `fe80::00ed:1` equals `fe80:0:0:0:0:0:ed:1`). + + + +```js +proxyaddr(req, '::1') +proxyaddr(req, ['::1/128', 'fe80::/10']) +``` + +This module will automatically work with IPv4-mapped IPv6 addresses +as well to support node.js in IPv6-only mode. This means that you do +not have to specify both `::ffff:a00:1` and `10.0.0.1`. + +As a convenience, this module also takes certain pre-defined names +in addition to IP addresses, which expand into IP addresses: + + + +```js +proxyaddr(req, 'loopback') +proxyaddr(req, ['loopback', 'fc00:ac:1ab5:fff::1/64']) +``` + + * `loopback`: IPv4 and IPv6 loopback addresses (like `::1` and + `127.0.0.1`). + * `linklocal`: IPv4 and IPv6 link-local addresses (like + `fe80::1:1:1:1` and `169.254.0.1`). + * `uniquelocal`: IPv4 private addresses and IPv6 unique-local + addresses (like `fc00:ac:1ab5:fff::1` and `192.168.0.1`). + +When `trust` is specified as a function, it will be called for each +address to determine if it is a trusted address. The function is +given two arguments: `addr` and `i`, where `addr` is a string of +the address to check and `i` is a number that represents the distance +from the socket address. + +### proxyaddr.all(req, [trust]) + +Return all the addresses of the request, optionally stopping at the +first untrusted. This array is ordered from closest to furthest +(i.e. `arr[0] === req.connection.remoteAddress`). + + + +```js +proxyaddr.all(req) +``` + +The optional `trust` argument takes the same arguments as `trust` +does in `proxyaddr(req, trust)`. + + + +```js +proxyaddr.all(req, 'loopback') +``` + +### proxyaddr.compile(val) + +Compiles argument `val` into a `trust` function. This function takes +the same arguments as `trust` does in `proxyaddr(req, trust)` and +returns a function suitable for `proxyaddr(req, trust)`. + + + +```js +var trust = proxyaddr.compile('loopback') +var addr = proxyaddr(req, trust) +``` + +This function is meant to be optimized for use against every request. +It is recommend to compile a trust function up-front for the trusted +configuration and pass that to `proxyaddr(req, trust)` for each request. + +## Testing + +```sh +$ npm test +``` + +## Benchmarks + +```sh +$ npm run-script bench +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/proxy-addr.svg +[npm-url]: https://npmjs.org/package/proxy-addr +[node-version-image]: https://img.shields.io/node/v/proxy-addr.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/proxy-addr/master.svg +[travis-url]: https://travis-ci.org/jshttp/proxy-addr +[coveralls-image]: https://img.shields.io/coveralls/jshttp/proxy-addr/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/proxy-addr?branch=master +[downloads-image]: https://img.shields.io/npm/dm/proxy-addr.svg +[downloads-url]: https://npmjs.org/package/proxy-addr diff --git a/node_modules/proxy-addr/index.js b/node_modules/proxy-addr/index.js new file mode 100644 index 00000000..8bb7d336 --- /dev/null +++ b/node_modules/proxy-addr/index.js @@ -0,0 +1,327 @@ +/*! + * proxy-addr + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = proxyaddr +module.exports.all = alladdrs +module.exports.compile = compile + +/** + * Module dependencies. + * @private + */ + +var forwarded = require('forwarded') +var ipaddr = require('ipaddr.js') + +/** + * Variables. + * @private + */ + +var DIGIT_REGEXP = /^[0-9]+$/ +var isip = ipaddr.isValid +var parseip = ipaddr.parse + +/** + * Pre-defined IP ranges. + * @private + */ + +var IP_RANGES = { + linklocal: ['169.254.0.0/16', 'fe80::/10'], + loopback: ['127.0.0.1/8', '::1/128'], + uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7'] +} + +/** + * Get all addresses in the request, optionally stopping + * at the first untrusted. + * + * @param {Object} request + * @param {Function|Array|String} [trust] + * @public + */ + +function alladdrs (req, trust) { + // get addresses + var addrs = forwarded(req) + + if (!trust) { + // Return all addresses + return addrs + } + + if (typeof trust !== 'function') { + trust = compile(trust) + } + + for (var i = 0; i < addrs.length - 1; i++) { + if (trust(addrs[i], i)) continue + + addrs.length = i + 1 + } + + return addrs +} + +/** + * Compile argument into trust function. + * + * @param {Array|String} val + * @private + */ + +function compile (val) { + if (!val) { + throw new TypeError('argument is required') + } + + var trust + + if (typeof val === 'string') { + trust = [val] + } else if (Array.isArray(val)) { + trust = val.slice() + } else { + throw new TypeError('unsupported trust argument') + } + + for (var i = 0; i < trust.length; i++) { + val = trust[i] + + if (!IP_RANGES.hasOwnProperty(val)) { + continue + } + + // Splice in pre-defined range + val = IP_RANGES[val] + trust.splice.apply(trust, [i, 1].concat(val)) + i += val.length - 1 + } + + return compileTrust(compileRangeSubnets(trust)) +} + +/** + * Compile `arr` elements into range subnets. + * + * @param {Array} arr + * @private + */ + +function compileRangeSubnets (arr) { + var rangeSubnets = new Array(arr.length) + + for (var i = 0; i < arr.length; i++) { + rangeSubnets[i] = parseipNotation(arr[i]) + } + + return rangeSubnets +} + +/** + * Compile range subnet array into trust function. + * + * @param {Array} rangeSubnets + * @private + */ + +function compileTrust (rangeSubnets) { + // Return optimized function based on length + var len = rangeSubnets.length + return len === 0 + ? trustNone + : len === 1 + ? trustSingle(rangeSubnets[0]) + : trustMulti(rangeSubnets) +} + +/** + * Parse IP notation string into range subnet. + * + * @param {String} note + * @private + */ + +function parseipNotation (note) { + var pos = note.lastIndexOf('/') + var str = pos !== -1 + ? note.substring(0, pos) + : note + + if (!isip(str)) { + throw new TypeError('invalid IP address: ' + str) + } + + var ip = parseip(str) + + if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) { + // Store as IPv4 + ip = ip.toIPv4Address() + } + + var max = ip.kind() === 'ipv6' + ? 128 + : 32 + + var range = pos !== -1 + ? note.substring(pos + 1, note.length) + : null + + if (range === null) { + range = max + } else if (DIGIT_REGEXP.test(range)) { + range = parseInt(range, 10) + } else if (ip.kind() === 'ipv4' && isip(range)) { + range = parseNetmask(range) + } else { + range = null + } + + if (range <= 0 || range > max) { + throw new TypeError('invalid range on address: ' + note) + } + + return [ip, range] +} + +/** + * Parse netmask string into CIDR range. + * + * @param {String} netmask + * @private + */ + +function parseNetmask (netmask) { + var ip = parseip(netmask) + var kind = ip.kind() + + return kind === 'ipv4' + ? ip.prefixLengthFromSubnetMask() + : null +} + +/** + * Determine address of proxied request. + * + * @param {Object} request + * @param {Function|Array|String} trust + * @public + */ + +function proxyaddr (req, trust) { + if (!req) { + throw new TypeError('req argument is required') + } + + if (!trust) { + throw new TypeError('trust argument is required') + } + + var addrs = alladdrs(req, trust) + var addr = addrs[addrs.length - 1] + + return addr +} + +/** + * Static trust function to trust nothing. + * + * @private + */ + +function trustNone () { + return false +} + +/** + * Compile trust function for multiple subnets. + * + * @param {Array} subnets + * @private + */ + +function trustMulti (subnets) { + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var ipconv + var kind = ip.kind() + + for (var i = 0; i < subnets.length; i++) { + var subnet = subnets[i] + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetrange = subnet[1] + var trusted = ip + + if (kind !== subnetkind) { + if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + continue + } + + if (!ipconv) { + // Convert IP to match subnet IP kind + ipconv = subnetkind === 'ipv4' + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + trusted = ipconv + } + + if (trusted.match(subnetip, subnetrange)) { + return true + } + } + + return false + } +} + +/** + * Compile trust function for single subnet. + * + * @param {Object} subnet + * @private + */ + +function trustSingle (subnet) { + var subnetip = subnet[0] + var subnetkind = subnetip.kind() + var subnetisipv4 = subnetkind === 'ipv4' + var subnetrange = subnet[1] + + return function trust (addr) { + if (!isip(addr)) return false + + var ip = parseip(addr) + var kind = ip.kind() + + if (kind !== subnetkind) { + if (subnetisipv4 && !ip.isIPv4MappedAddress()) { + // Incompatible IP addresses + return false + } + + // Convert IP to match subnet IP kind + ip = subnetisipv4 + ? ip.toIPv4Address() + : ip.toIPv4MappedAddress() + } + + return ip.match(subnetip, subnetrange) + } +} diff --git a/node_modules/proxy-addr/package.json b/node_modules/proxy-addr/package.json new file mode 100644 index 00000000..750f27fd --- /dev/null +++ b/node_modules/proxy-addr/package.json @@ -0,0 +1,84 @@ +{ + "_args": [ + [ + "proxy-addr@2.0.4", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "proxy-addr@2.0.4", + "_id": "proxy-addr@2.0.4", + "_inBundle": false, + "_integrity": "sha512-5erio2h9jp5CHGwcybmxmVqHmnCBZeewlfJ0pex+UW7Qny7OOZXTtH56TGNyBizkgiOwhJtMKrVzDTeKcySZwA==", + "_location": "/proxy-addr", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "proxy-addr@2.0.4", + "name": "proxy-addr", + "escapedName": "proxy-addr", + "rawSpec": "2.0.4", + "saveSpec": null, + "fetchSpec": "2.0.4" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.4.tgz", + "_spec": "2.0.4", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/jshttp/proxy-addr/issues" + }, + "dependencies": { + "forwarded": "~0.1.2", + "ipaddr.js": "1.8.0" + }, + "description": "Determine address of proxied request", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "4.19.1", + "eslint-config-standard": "11.0.0", + "eslint-plugin-import": "2.13.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "6.0.1", + "eslint-plugin-promise": "3.8.0", + "eslint-plugin-standard": "3.1.0", + "mocha": "3.5.3", + "nyc": "10.3.2" + }, + "engines": { + "node": ">= 0.10" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/proxy-addr#readme", + "keywords": [ + "ip", + "proxy", + "x-forwarded-for" + ], + "license": "MIT", + "name": "proxy-addr", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/proxy-addr.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "nyc --reporter=text npm test", + "test-travis": "nyc --reporter=html --reporter=text npm test" + }, + "version": "2.0.4" +} diff --git a/node_modules/qs/.editorconfig b/node_modules/qs/.editorconfig new file mode 100644 index 00000000..b2654e7a --- /dev/null +++ b/node_modules/qs/.editorconfig @@ -0,0 +1,30 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 140 + +[test/*] +max_line_length = off + +[*.md] +max_line_length = off + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[LICENSE] +indent_size = 2 +max_line_length = off diff --git a/node_modules/qs/.eslintignore b/node_modules/qs/.eslintignore new file mode 100644 index 00000000..1521c8b7 --- /dev/null +++ b/node_modules/qs/.eslintignore @@ -0,0 +1 @@ +dist diff --git a/node_modules/qs/.eslintrc b/node_modules/qs/.eslintrc new file mode 100644 index 00000000..a33d179e --- /dev/null +++ b/node_modules/qs/.eslintrc @@ -0,0 +1,19 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 28], + "consistent-return": 1, + "func-name-matching": 0, + "id-length": [2, { "min": 1, "max": 25, "properties": "never" }], + "indent": [2, 4], + "max-params": [2, 12], + "max-statements": [2, 45], + "no-continue": 1, + "no-magic-numbers": 0, + "no-restricted-syntax": [2, "BreakStatement", "DebuggerStatement", "ForInStatement", "LabeledStatement", "WithStatement"], + "operator-linebreak": [2, "before"], + } +} diff --git a/node_modules/qs/CHANGELOG.md b/node_modules/qs/CHANGELOG.md new file mode 100644 index 00000000..71d5a3e8 --- /dev/null +++ b/node_modules/qs/CHANGELOG.md @@ -0,0 +1,221 @@ +## **6.5.1** +- [Fix] Fix parsing & compacting very deep objects (#224) +- [Refactor] name utils functions +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` +- [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node +- [Tests] Use precise dist for Node.js 0.6 runtime (#225) +- [Tests] make 0.6 required, now that it’s passing +- [Tests] on `node` `v8.2`; fix npm on node 0.6 + +## **6.5.0** +- [New] add `utils.assign` +- [New] pass default encoder/decoder to custom encoder/decoder functions (#206) +- [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) +- [Fix] Handle stringifying empty objects with addQueryPrefix (#217) +- [Fix] do not mutate `options` argument (#207) +- [Refactor] `parse`: cache index to reuse in else statement (#182) +- [Docs] add various badges to readme (#208) +- [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` +- [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 +- [Tests] add `editorconfig-tools` + +## **6.4.0** +- [New] `qs.stringify`: add `encodeValuesOnly` option +- [Fix] follow `allowPrototypes` option during merge (#201, #201) +- [Fix] support keys starting with brackets (#202, #200) +- [Fix] chmod a-x +- [Dev Deps] update `eslint` +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds +- [eslint] reduce warnings + +## **6.3.2** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Dev Deps] update `eslint` +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.3.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` +- [Tests] on all node minors; improve test matrix +- [Docs] document stringify option `allowDots` (#195) +- [Docs] add empty object and array values example (#195) +- [Docs] Fix minor inconsistency/typo (#192) +- [Docs] document stringify option `sort` (#191) +- [Refactor] `stringify`: throw faster with an invalid encoder +- [Refactor] remove unnecessary escapes (#184) +- Remove contributing.md, since `qs` is no longer part of `hapi` (#183) + +## **6.3.0** +- [New] Add support for RFC 1738 (#174, #173) +- [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) +- [Fix] ensure `utils.merge` handles merging two arrays +- [Refactor] only constructors should be capitalized +- [Refactor] capitalized var names are for constructors only +- [Refactor] avoid using a sparse array +- [Robustness] `formats`: cache `String#replace` +- [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` +- [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix +- [Tests] flesh out arrayLimit/arrayFormat tests (#107) +- [Tests] skip Object.create tests when null objects are not available +- [Tests] Turn on eslint for test files (#175) + +## **6.2.3** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.2.2** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## **6.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values +- [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` +- [Tests] remove `parallelshell` since it does not reliably report failures +- [Tests] up to `node` `v6.3`, `v5.12` +- [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` + +## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) +- [New] pass Buffers to the encoder/decoder directly (#161) +- [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) +- [Fix] fix compacting of nested sparse arrays (#150) + +## **6.1.2 +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.1.1** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties + +## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) +- [New] allowDots option for `stringify` (#151) +- [Fix] "sort" option should work at a depth of 3 or more (#151) +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## **6.0.4** +- [Fix] follow `allowPrototypes` option during merge (#201, #200) +- [Fix] chmod a-x +- [Fix] support keys starting with brackets (#202, #200) +- [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds + +## **6.0.3** +- [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties +- [Fix] Restore `dist` directory; will be removed in v7 (#148) + +## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) +- Revert ES6 requirement and restore support for node down to v0.8. + +## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) +- [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json + +## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) +- [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 + +## **5.2.1** +- [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values + +## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) +- [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string + +## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) +- [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional +- [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify + +## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) +- [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false +- [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm + +## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) +- [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional + +## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) +- [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" + +## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) +- [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties +- [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost +- [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing +- [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object +- [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option +- [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. +- [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 +- [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 +- [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign +- [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute + +## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) +- [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object # is not a function + +## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) +- [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option + +## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) +- [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 +- [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader + +## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) +- [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object + +## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) +- [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". + +## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) +- [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 + +## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) +- [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? +- [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 +- [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 + +## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) +- [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number + +## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) +- [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array +- [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x + +## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) +- [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value +- [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty +- [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? + +## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) +- [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 +- [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects + +## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) +- [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present +- [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays +- [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge +- [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? + +## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) +- [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter + +## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) +- [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? +- [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit +- [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 + +## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) +- [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values + +## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) +- [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters +- [**#15**](https://github.com/ljharb/qs/issues/15) Close code block + +## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) +- [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument +- [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed + +## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) +- [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted +- [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null +- [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README + +## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) +- [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index diff --git a/node_modules/qs/LICENSE b/node_modules/qs/LICENSE new file mode 100644 index 00000000..d4569487 --- /dev/null +++ b/node_modules/qs/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2014 Nathan LaFreniere and other contributors. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * The names of any contributors may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * * * + +The complete list of contributors can be found at: https://github.com/hapijs/qs/graphs/contributors diff --git a/node_modules/qs/README.md b/node_modules/qs/README.md new file mode 100644 index 00000000..d8119666 --- /dev/null +++ b/node_modules/qs/README.md @@ -0,0 +1,475 @@ +# qs [![Version Badge][2]][1] + +[![Build Status][3]][4] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +A querystring parsing and stringifying library with some added security. + +Lead Maintainer: [Jordan Harband](https://github.com/ljharb) + +The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). + +## Usage + +```javascript +var qs = require('qs'); +var assert = require('assert'); + +var obj = qs.parse('a=c'); +assert.deepEqual(obj, { a: 'c' }); + +var str = qs.stringify(obj); +assert.equal(str, 'a=c'); +``` + +### Parsing Objects + +[](#preventEval) +```javascript +qs.parse(string, [options]); +``` + +**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. +For example, the string `'foo[bar]=baz'` converts to: + +```javascript +assert.deepEqual(qs.parse('foo[bar]=baz'), { + foo: { + bar: 'baz' + } +}); +``` + +When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: + +```javascript +var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); +assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); +``` + +By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. + +```javascript +var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); +assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); +``` + +URI encoded strings work too: + +```javascript +assert.deepEqual(qs.parse('a%5Bb%5D=c'), { + a: { b: 'c' } +}); +``` + +You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: + +```javascript +assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { + foo: { + bar: { + baz: 'foobarbaz' + } + } +}); +``` + +By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like +`'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: + +```javascript +var expected = { + a: { + b: { + c: { + d: { + e: { + f: { + '[g][h][i]': 'j' + } + } + } + } + } + } +}; +var string = 'a[b][c][d][e][f][g][h][i]=j'; +assert.deepEqual(qs.parse(string), expected); +``` + +This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: + +```javascript +var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); +assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); +``` + +The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. + +For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: + +```javascript +var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); +assert.deepEqual(limited, { a: 'b' }); +``` + +To bypass the leading question mark, use `ignoreQueryPrefix`: + +```javascript +var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); +assert.deepEqual(prefixed, { a: 'b', c: 'd' }); +``` + +An optional delimiter can also be passed: + +```javascript +var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); +assert.deepEqual(delimited, { a: 'b', c: 'd' }); +``` + +Delimiters can be a regular expression too: + +```javascript +var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); +assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); +``` + +Option `allowDots` can be used to enable dot notation: + +```javascript +var withDots = qs.parse('a.b=c', { allowDots: true }); +assert.deepEqual(withDots, { a: { b: 'c' } }); +``` + +### Parsing Arrays + +**qs** can also parse arrays using a similar `[]` notation: + +```javascript +var withArray = qs.parse('a[]=b&a[]=c'); +assert.deepEqual(withArray, { a: ['b', 'c'] }); +``` + +You may specify an index as well: + +```javascript +var withIndexes = qs.parse('a[1]=c&a[0]=b'); +assert.deepEqual(withIndexes, { a: ['b', 'c'] }); +``` + +Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number +to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving +their order: + +```javascript +var noSparse = qs.parse('a[1]=b&a[15]=c'); +assert.deepEqual(noSparse, { a: ['b', 'c'] }); +``` + +Note that an empty string is also a value, and will be preserved: + +```javascript +var withEmptyString = qs.parse('a[]=&a[]=b'); +assert.deepEqual(withEmptyString, { a: ['', 'b'] }); + +var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); +assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); +``` + +**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will +instead be converted to an object with the index as the key: + +```javascript +var withMaxIndex = qs.parse('a[100]=b'); +assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); +``` + +This limit can be overridden by passing an `arrayLimit` option: + +```javascript +var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); +assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); +``` + +To disable array parsing entirely, set `parseArrays` to `false`. + +```javascript +var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); +assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); +``` + +If you mix notations, **qs** will merge the two items into an object: + +```javascript +var mixedNotation = qs.parse('a[0]=b&a[b]=c'); +assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); +``` + +You can also create arrays of objects: + +```javascript +var arraysOfObjects = qs.parse('a[][b]=c'); +assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); +``` + +### Stringifying + +[](#preventEval) +```javascript +qs.stringify(object, [options]); +``` + +When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: + +```javascript +assert.equal(qs.stringify({ a: 'b' }), 'a=b'); +assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); +``` + +This encoding can be disabled by setting the `encode` option to `false`: + +```javascript +var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); +assert.equal(unencoded, 'a[b]=c'); +``` + +Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: +```javascript +var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } +); +assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +``` + +This encoding can also be replaced by a custom encoding method set as `encoder` option: + +```javascript +var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { + // Passed in values `a`, `b`, `c` + return // Return encoded string +}}) +``` + +_(Note: the `encoder` option does not apply if `encode` is `false`)_ + +Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: + +```javascript +var decoded = qs.parse('x=z', { decoder: function (str) { + // Passed in values `x`, `z` + return // Return decoded string +}}) +``` + +Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. + +When arrays are stringified, by default they are given explicit indices: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }); +// 'a[0]=b&a[1]=c&a[2]=d' +``` + +You may override this by setting the `indices` option to `false`: + +```javascript +qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); +// 'a=b&a=c&a=d' +``` + +You may use the `arrayFormat` option to specify the format of the output array: + +```javascript +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) +// 'a[0]=b&a[1]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) +// 'a[]=b&a[]=c' +qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) +// 'a=b&a=c' +``` + +When objects are stringified, by default they use bracket notation: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); +// 'a[b][c]=d&a[b][e]=f' +``` + +You may override this to use dot notation by setting the `allowDots` option to `true`: + +```javascript +qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); +// 'a.b.c=d&a.b.e=f' +``` + +Empty strings and null values will omit the value, but the equals sign (=) remains in place: + +```javascript +assert.equal(qs.stringify({ a: '' }), 'a='); +``` + +Key with no values (such as an empty object or array) will return nothing: + +```javascript +assert.equal(qs.stringify({ a: [] }), ''); +assert.equal(qs.stringify({ a: {} }), ''); +assert.equal(qs.stringify({ a: [{}] }), ''); +assert.equal(qs.stringify({ a: { b: []} }), ''); +assert.equal(qs.stringify({ a: { b: {}} }), ''); +``` + +Properties that are set to `undefined` will be omitted entirely: + +```javascript +assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); +``` + +The query string may optionally be prepended with a question mark: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); +``` + +The delimiter may be overridden with stringify as well: + +```javascript +assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); +``` + +If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: + +```javascript +var date = new Date(7); +assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); +assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), + 'a=7' +); +``` + +You may use the `sort` option to affect the order of parameter keys: + +```javascript +function alphabeticalSort(a, b) { + return a.localeCompare(b); +} +assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); +``` + +Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. +If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you +pass an array, it will be used to select properties and array indices for stringification: + +```javascript +function filterFunc(prefix, value) { + if (prefix == 'b') { + // Return an `undefined` value to omit a property. + return; + } + if (prefix == 'e[f]') { + return value.getTime(); + } + if (prefix == 'e[g][0]') { + return value * 2; + } + return value; +} +qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); +// 'a=b&c=d&e[f]=123&e[g][0]=4' +qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); +// 'a=b&e=f' +qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); +// 'a[0]=b&a[2]=d' +``` + +### Handling of `null` values + +By default, `null` values are treated like empty strings: + +```javascript +var withNull = qs.stringify({ a: null, b: '' }); +assert.equal(withNull, 'a=&b='); +``` + +Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. + +```javascript +var equalsInsensitive = qs.parse('a&b='); +assert.deepEqual(equalsInsensitive, { a: '', b: '' }); +``` + +To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` +values have no `=` sign: + +```javascript +var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); +assert.equal(strictNull, 'a&b='); +``` + +To parse values without `=` back to `null` use the `strictNullHandling` flag: + +```javascript +var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); +assert.deepEqual(parsedStrictNull, { a: null, b: '' }); +``` + +To completely skip rendering keys with `null` values, use the `skipNulls` flag: + +```javascript +var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); +assert.equal(nullsSkipped, 'a=b'); +``` + +### Dealing with special character sets + +By default the encoding and decoding of characters is done in `utf-8`. If you +wish to encode querystrings to a different character set (i.e. +[Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the +[`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: + +```javascript +var encoder = require('qs-iconv/encoder')('shift_jis'); +var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); +assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); +``` + +This also works for decoding of query strings: + +```javascript +var decoder = require('qs-iconv/decoder')('shift_jis'); +var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); +assert.deepEqual(obj, { a: 'こんにちは!' }); +``` + +### RFC 3986 and RFC 1738 space encoding + +RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. +In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. + +``` +assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +``` + +[1]: https://npmjs.org/package/qs +[2]: http://versionbadg.es/ljharb/qs.svg +[3]: https://api.travis-ci.org/ljharb/qs.svg +[4]: https://travis-ci.org/ljharb/qs +[5]: https://david-dm.org/ljharb/qs.svg +[6]: https://david-dm.org/ljharb/qs +[7]: https://david-dm.org/ljharb/qs/dev-status.svg +[8]: https://david-dm.org/ljharb/qs?type=dev +[9]: https://ci.testling.com/ljharb/qs.png +[10]: https://ci.testling.com/ljharb/qs +[11]: https://nodei.co/npm/qs.png?downloads=true&stars=true +[license-image]: http://img.shields.io/npm/l/qs.svg +[license-url]: LICENSE +[downloads-image]: http://img.shields.io/npm/dm/qs.svg +[downloads-url]: http://npm-stat.com/charts.html?package=qs diff --git a/node_modules/qs/dist/qs.js b/node_modules/qs/dist/qs.js new file mode 100644 index 00000000..713c6d1e --- /dev/null +++ b/node_modules/qs/dist/qs.js @@ -0,0 +1,627 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]') { + obj = []; + obj = obj.concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +module.exports = function (str, opts) { + var options = opts ? utils.assign({}, opts) : {}; + + if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; + options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; + +},{"./utils":5}],4:[function(require,module,exports){ +'use strict'; + +var utils = require('./utils'); +var formats = require('./formats'); + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { // eslint-disable-line func-name-matching + return prefix + '[]'; + }, + indices: function indices(prefix, key) { // eslint-disable-line func-name-matching + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { // eslint-disable-line func-name-matching + return prefix; + } +}; + +var toISO = Date.prototype.toISOString; + +var defaults = { + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var stringify = function stringify( // eslint-disable-line func-name-matching + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (Array.isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(stringify( + obj[key], + generateArrayPrefix(prefix, key), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } else { + values = values.concat(stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + } + + return values; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = opts ? utils.assign({}, opts) : {}; + + if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; + var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; + var sort = typeof options.sort === 'function' ? options.sort : null; + var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; + var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; + var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; + if (typeof options.format === 'undefined') { + options.format = formats['default']; + } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { + throw new TypeError('Unknown format option provided.'); + } + var formatter = formats.formatters[options.format]; + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (Array.isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (options.arrayFormat in arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (sort) { + objKeys.sort(sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + keys = keys.concat(stringify( + obj[key], + key, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encode ? encoder : null, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + + var joined = keys.join(delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + return joined.length > 0 ? prefix + joined : ''; +}; + +},{"./formats":1,"./utils":5}],5:[function(require,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + var obj; + + while (queue.length) { + var item = queue.pop(); + obj = item.obj[item.prop]; + + if (Array.isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } + + return obj; +}; + +exports.arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +exports.merge = function merge(target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } else if (typeof target === 'object') { + if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (Array.isArray(target) && !Array.isArray(source)) { + mergeTarget = exports.arrayToObject(target, options); + } + + if (Array.isArray(target) && Array.isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + if (target[i] && typeof target[i] === 'object') { + target[i] = exports.merge(target[i], item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = exports.merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +exports.assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +exports.decode = function (str) { + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function encode(str) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = typeof str === 'string' ? str : String(str); + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + return compactQueue(queue); +}; + +exports.isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +exports.isBuffer = function isBuffer(obj) { + if (obj === null || typeof obj === 'undefined') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; + +},{}]},{},[2])(2) +}); \ No newline at end of file diff --git a/node_modules/qs/lib/formats.js b/node_modules/qs/lib/formats.js new file mode 100644 index 00000000..df459975 --- /dev/null +++ b/node_modules/qs/lib/formats.js @@ -0,0 +1,18 @@ +'use strict'; + +var replace = String.prototype.replace; +var percentTwenties = /%20/g; + +module.exports = { + 'default': 'RFC3986', + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return value; + } + }, + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; diff --git a/node_modules/qs/lib/index.js b/node_modules/qs/lib/index.js new file mode 100644 index 00000000..0d6a97dc --- /dev/null +++ b/node_modules/qs/lib/index.js @@ -0,0 +1,11 @@ +'use strict'; + +var stringify = require('./stringify'); +var parse = require('./parse'); +var formats = require('./formats'); + +module.exports = { + formats: formats, + parse: parse, + stringify: stringify +}; diff --git a/node_modules/qs/lib/parse.js b/node_modules/qs/lib/parse.js new file mode 100644 index 00000000..8c9872ec --- /dev/null +++ b/node_modules/qs/lib/parse.js @@ -0,0 +1,174 @@ +'use strict'; + +var utils = require('./utils'); + +var has = Object.prototype.hasOwnProperty; + +var defaults = { + allowDots: false, + allowPrototypes: false, + arrayLimit: 20, + decoder: utils.decode, + delimiter: '&', + depth: 5, + parameterLimit: 1000, + plainObjects: false, + strictNullHandling: false +}; + +var parseValues = function parseQueryStringValues(str, options) { + var obj = {}; + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; + var parts = cleanStr.split(options.delimiter, limit); + + for (var i = 0; i < parts.length; ++i) { + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key, val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder); + val = options.decoder(part.slice(pos + 1), defaults.decoder); + } + if (has.call(obj, key)) { + obj[key] = [].concat(obj[key]).concat(val); + } else { + obj[key] = val; + } + } + + return obj; +}; + +var parseObject = function (chain, val, options) { + var leaf = val; + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]') { + obj = []; + obj = obj.concat(leaf); + } else { + obj = options.plainObjects ? Object.create(null) : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var index = parseInt(cleanRoot, 10); + if ( + !isNaN(index) + && root !== cleanRoot + && String(index) === cleanRoot + && index >= 0 + && (options.parseArrays && index <= options.arrayLimit) + ) { + obj = []; + obj[index] = leaf; + } else { + obj[cleanRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; +}; + +var parseKeys = function parseQueryStringKeys(givenKey, val, options) { + if (!givenKey) { + return; + } + + // Transform dot notation to bracket notation + var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; + + // The regex chunks + + var brackets = /(\[[^[\]]*])/; + var child = /(\[[^[\]]*])/g; + + // Get the parent + + var segment = brackets.exec(key); + var parent = segment ? key.slice(0, segment.index) : key; + + // Stash the parent if it exists + + var keys = []; + if (parent) { + // If we aren't using plain objects, optionally prefix keys + // that would overwrite object prototype properties + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + keys.push(parent); + } + + // Loop through children appending to the array until we hit depth + + var i = 0; + while ((segment = child.exec(key)) !== null && i < options.depth) { + i += 1; + if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { + if (!options.allowPrototypes) { + return; + } + } + keys.push(segment[1]); + } + + // If there's a remainder, just add whatever is left + + if (segment) { + keys.push('[' + key.slice(segment.index) + ']'); + } + + return parseObject(keys, val, options); +}; + +module.exports = function (str, opts) { + var options = opts ? utils.assign({}, opts) : {}; + + if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; + options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; + options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; + options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; + options.parseArrays = options.parseArrays !== false; + options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; + options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; + options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; + options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; + options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; + options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? Object.create(null) : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? Object.create(null) : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options); + obj = utils.merge(obj, newObj, options); + } + + return utils.compact(obj); +}; diff --git a/node_modules/qs/lib/stringify.js b/node_modules/qs/lib/stringify.js new file mode 100644 index 00000000..ab915ac4 --- /dev/null +++ b/node_modules/qs/lib/stringify.js @@ -0,0 +1,210 @@ +'use strict'; + +var utils = require('./utils'); +var formats = require('./formats'); + +var arrayPrefixGenerators = { + brackets: function brackets(prefix) { // eslint-disable-line func-name-matching + return prefix + '[]'; + }, + indices: function indices(prefix, key) { // eslint-disable-line func-name-matching + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { // eslint-disable-line func-name-matching + return prefix; + } +}; + +var toISO = Date.prototype.toISOString; + +var defaults = { + delimiter: '&', + encode: true, + encoder: utils.encode, + encodeValuesOnly: false, + serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false +}; + +var stringify = function stringify( // eslint-disable-line func-name-matching + object, + prefix, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly +) { + var obj = object; + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; + } + + obj = ''; + } + + if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (Array.isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + if (Array.isArray(obj)) { + values = values.concat(stringify( + obj[key], + generateArrayPrefix(prefix, key), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } else { + values = values.concat(stringify( + obj[key], + prefix + (allowDots ? '.' + key : '[' + key + ']'), + generateArrayPrefix, + strictNullHandling, + skipNulls, + encoder, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + } + + return values; +}; + +module.exports = function (object, opts) { + var obj = object; + var options = opts ? utils.assign({}, opts) : {}; + + if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; + var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; + var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; + var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; + var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; + var sort = typeof options.sort === 'function' ? options.sort : null; + var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; + var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; + var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; + if (typeof options.format === 'undefined') { + options.format = formats['default']; + } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { + throw new TypeError('Unknown format option provided.'); + } + var formatter = formats.formatters[options.format]; + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (Array.isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var arrayFormat; + if (options.arrayFormat in arrayPrefixGenerators) { + arrayFormat = options.arrayFormat; + } else if ('indices' in options) { + arrayFormat = options.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = 'indices'; + } + + var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (sort) { + objKeys.sort(sort); + } + + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (skipNulls && obj[key] === null) { + continue; + } + + keys = keys.concat(stringify( + obj[key], + key, + generateArrayPrefix, + strictNullHandling, + skipNulls, + encode ? encoder : null, + filter, + sort, + allowDots, + serializeDate, + formatter, + encodeValuesOnly + )); + } + + var joined = keys.join(delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + return joined.length > 0 ? prefix + joined : ''; +}; diff --git a/node_modules/qs/lib/utils.js b/node_modules/qs/lib/utils.js new file mode 100644 index 00000000..06cae2f0 --- /dev/null +++ b/node_modules/qs/lib/utils.js @@ -0,0 +1,202 @@ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + + return array; +}()); + +var compactQueue = function compactQueue(queue) { + var obj; + + while (queue.length) { + var item = queue.pop(); + obj = item.obj[item.prop]; + + if (Array.isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + + item.obj[item.prop] = compacted; + } + } + + return obj; +}; + +exports.arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; +}; + +exports.merge = function merge(target, source, options) { + if (!source) { + return target; + } + + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } else if (typeof target === 'object') { + if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (typeof target !== 'object') { + return [target].concat(source); + } + + var mergeTarget = target; + if (Array.isArray(target) && !Array.isArray(source)) { + mergeTarget = exports.arrayToObject(target, options); + } + + if (Array.isArray(target) && Array.isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + if (target[i] && typeof target[i] === 'object') { + target[i] = exports.merge(target[i], item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + acc[key] = exports.merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); +}; + +exports.assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +}; + +exports.decode = function (str) { + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; + +exports.encode = function encode(str) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = typeof str === 'string' ? str : String(str); + + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); + + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } + + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } + + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + return out; +}; + +exports.compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = []; + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + + return compactQueue(queue); +}; + +exports.isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; + +exports.isBuffer = function isBuffer(obj) { + if (obj === null || typeof obj === 'undefined') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; diff --git a/node_modules/qs/package.json b/node_modules/qs/package.json new file mode 100644 index 00000000..05f9dd3f --- /dev/null +++ b/node_modules/qs/package.json @@ -0,0 +1,83 @@ +{ + "_args": [ + [ + "qs@6.5.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "qs@6.5.1", + "_id": "qs@6.5.1", + "_inBundle": false, + "_integrity": "sha512-eRzhrN1WSINYCDCbrz796z37LOe3m5tmW7RQf6oBntukAG1nmovJvhnwHHRMAfeoItc1m2Hk02WER2aQ/iqs+A==", + "_location": "/qs", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "qs@6.5.1", + "name": "qs", + "escapedName": "qs", + "rawSpec": "6.5.1", + "saveSpec": null, + "fetchSpec": "6.5.1" + }, + "_requiredBy": [ + "/body-parser", + "/express" + ], + "_resolved": "https://registry.npmjs.org/qs/-/qs-6.5.1.tgz", + "_spec": "6.5.1", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/ljharb/qs/issues" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "dependencies": {}, + "description": "A querystring parser that supports nesting and arrays, with a depth limit", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "browserify": "^14.4.0", + "covert": "^1.1.0", + "editorconfig-tools": "^0.1.1", + "eslint": "^4.6.1", + "evalmd": "^0.0.17", + "iconv-lite": "^0.4.18", + "mkdirp": "^0.5.1", + "qs-iconv": "^1.0.4", + "safe-publish-latest": "^1.1.1", + "tape": "^4.8.0" + }, + "engines": { + "node": ">=0.6" + }, + "homepage": "https://github.com/ljharb/qs", + "keywords": [ + "querystring", + "qs" + ], + "license": "BSD-3-Clause", + "main": "lib/index.js", + "name": "qs", + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/qs.git" + }, + "scripts": { + "coverage": "covert test", + "dist": "mkdirp dist && browserify --standalone Qs lib/index.js > dist/qs.js", + "lint": "eslint lib/*.js test/*.js", + "prelint": "editorconfig-tools check * lib/* test/*", + "prepublish": "safe-publish-latest && npm run dist", + "pretest": "npm run --silent readme && npm run --silent lint", + "readme": "evalmd README.md", + "test": "npm run --silent coverage", + "tests-only": "node test" + }, + "version": "6.5.1" +} diff --git a/node_modules/qs/test/.eslintrc b/node_modules/qs/test/.eslintrc new file mode 100644 index 00000000..20175d64 --- /dev/null +++ b/node_modules/qs/test/.eslintrc @@ -0,0 +1,15 @@ +{ + "rules": { + "array-bracket-newline": 0, + "array-element-newline": 0, + "consistent-return": 2, + "max-lines": 0, + "max-nested-callbacks": [2, 3], + "max-statements": 0, + "no-buffer-constructor": 0, + "no-extend-native": 0, + "no-magic-numbers": 0, + "object-curly-newline": 0, + "sort-keys": 0 + } +} diff --git a/node_modules/qs/test/index.js b/node_modules/qs/test/index.js new file mode 100644 index 00000000..5e6bc8fb --- /dev/null +++ b/node_modules/qs/test/index.js @@ -0,0 +1,7 @@ +'use strict'; + +require('./parse'); + +require('./stringify'); + +require('./utils'); diff --git a/node_modules/qs/test/parse.js b/node_modules/qs/test/parse.js new file mode 100644 index 00000000..d7d86419 --- /dev/null +++ b/node_modules/qs/test/parse.js @@ -0,0 +1,573 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); + +test('parse()', function (t) { + t.test('parses a simple string', function (st) { + st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); + st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); + st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); + st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); + st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); + st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); + st.deepEqual(qs.parse('foo'), { foo: '' }); + st.deepEqual(qs.parse('foo='), { foo: '' }); + st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); + st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); + st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); + st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); + st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); + st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); + st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); + st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { + cht: 'p3', + chd: 't:60,40', + chs: '250x100', + chl: 'Hello|World' + }); + st.end(); + }); + + t.test('allows enabling dot notation', function (st) { + st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); + st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); + t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); + t.deepEqual( + qs.parse('a[b][c][d][e][f][g][h]=i'), + { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, + 'defaults to a depth of 5' + ); + + t.test('only parses one level when depth = 1', function (st) { + st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); + st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); + st.end(); + }); + + t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); + + t.test('parses an explicit array', function (st) { + st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); + st.end(); + }); + + t.test('parses a mix of simple and explicit arrays', function (st) { + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); + + st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); + + st.end(); + }); + + t.test('parses a nested array', function (st) { + st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); + st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); + st.end(); + }); + + t.test('allows to specify array indices', function (st) { + st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); + st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); + st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); + st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); + st.end(); + }); + + t.test('limits specific array indices to arrayLimit', function (st) { + st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); + st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); + st.end(); + }); + + t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); + + t.test('supports encoded = signs', function (st) { + st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); + st.end(); + }); + + t.test('is ok with url encoded strings', function (st) { + st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); + st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); + st.end(); + }); + + t.test('allows brackets in the value', function (st) { + st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); + st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); + st.end(); + }); + + t.test('allows empty values', function (st) { + st.deepEqual(qs.parse(''), {}); + st.deepEqual(qs.parse(null), {}); + st.deepEqual(qs.parse(undefined), {}); + st.end(); + }); + + t.test('transforms arrays to objects', function (st) { + st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); + st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); + st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); + st.end(); + }); + + t.test('transforms arrays to objects (dot notation)', function (st) { + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); + st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); + st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); + st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); + st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); + st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); + st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); + st.end(); + }); + + t.test('correctly prunes undefined values when converting an array to an object', function (st) { + st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); + st.end(); + }); + + t.test('supports malformed uri characters', function (st) { + st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); + st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); + st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); + st.end(); + }); + + t.test('doesn\'t produce empty keys', function (st) { + st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); + st.end(); + }); + + t.test('cannot access Object prototype', function (st) { + qs.parse('constructor[prototype][bad]=bad'); + qs.parse('bad[constructor][prototype][bad]=bad'); + st.equal(typeof Object.prototype.bad, 'undefined'); + st.end(); + }); + + t.test('parses arrays of objects', function (st) { + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); + st.end(); + }); + + t.test('allows for empty strings in arrays', function (st) { + st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); + + st.deepEqual( + qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 20 + array indices: null then empty string works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', null, 'c', ''] }, + 'with arrayLimit 0 + array brackets: null then empty string works' + ); + + st.deepEqual( + qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 20 + array indices: empty string then null works' + ); + st.deepEqual( + qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), + { a: ['b', '', 'c', null] }, + 'with arrayLimit 0 + array brackets: empty string then null works' + ); + + st.deepEqual( + qs.parse('a[]=&a[]=b&a[]=c'), + { a: ['', 'b', 'c'] }, + 'array brackets: empty strings work' + ); + st.end(); + }); + + t.test('compacts sparse arrays', function (st) { + st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); + st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); + st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); + st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); + st.end(); + }); + + t.test('parses semi-parsed strings', function (st) { + st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); + st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); + st.end(); + }); + + t.test('parses buffers correctly', function (st) { + var b = new Buffer('test'); + st.deepEqual(qs.parse({ a: b }), { a: b }); + st.end(); + }); + + t.test('continues parsing when no parent is found', function (st) { + st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); + st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); + st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); + st.end(); + }); + + t.test('does not error when parsing a very long array', function (st) { + var str = 'a[]=a'; + while (Buffer.byteLength(str) < 128 * 1024) { + str = str + '&' + str; + } + + st.doesNotThrow(function () { + qs.parse(str); + }); + + st.end(); + }); + + t.test('should not throw when a native prototype has an enumerable property', { parallel: false }, function (st) { + Object.prototype.crash = ''; + Array.prototype.crash = ''; + st.doesNotThrow(qs.parse.bind(null, 'a=b')); + st.deepEqual(qs.parse('a=b'), { a: 'b' }); + st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); + st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); + delete Object.prototype.crash; + delete Array.prototype.crash; + st.end(); + }); + + t.test('parses a string with an alternative string delimiter', function (st) { + st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('parses a string with an alternative RegExp delimiter', function (st) { + st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not use non-splittable objects as delimiters', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding parameter limit', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); + st.end(); + }); + + t.test('allows setting the parameter limit to Infinity', function (st) { + st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('allows overriding array limit', function (st) { + st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); + st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); + st.end(); + }); + + t.test('allows disabling array parsing', function (st) { + st.deepEqual(qs.parse('a[0]=b&a[1]=c', { parseArrays: false }), { a: { 0: 'b', 1: 'c' } }); + st.end(); + }); + + t.test('allows for query string prefix', function (st) { + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); + st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); + st.end(); + }); + + t.test('parses an object', function (st) { + var input = { + 'user[name]': { 'pop[bob]': 3 }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object in dot notation', function (st) { + var input = { + 'user.name': { 'pop[bob]': 3 }, + 'user.email.': null + }; + + var expected = { + user: { + name: { 'pop[bob]': 3 }, + email: null + } + }; + + var result = qs.parse(input, { allowDots: true }); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('parses an object and not child values', function (st) { + var input = { + 'user[name]': { 'pop[bob]': { test: 3 } }, + 'user[email]': null + }; + + var expected = { + user: { + name: { 'pop[bob]': { test: 3 } }, + email: null + } + }; + + var result = qs.parse(input); + + st.deepEqual(result, expected); + st.end(); + }); + + t.test('does not blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.parse('a=b&c=d'); + global.Buffer = tempBuffer; + st.deepEqual(result, { a: 'b', c: 'd' }); + st.end(); + }); + + t.test('does not crash when parsing circular references', function (st) { + var a = {}; + a.b = a; + + var parsed; + + st.doesNotThrow(function () { + parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + st.equal('bar' in parsed.foo, true); + st.equal('baz' in parsed.foo, true); + st.equal(parsed.foo.bar, 'baz'); + st.deepEqual(parsed.foo.baz, a); + st.end(); + }); + + t.test('does not crash when parsing deep objects', function (st) { + var parsed; + var str = 'foo'; + + for (var i = 0; i < 5000; i++) { + str += '[p]'; + } + + str += '=bar'; + + st.doesNotThrow(function () { + parsed = qs.parse(str, { depth: 5000 }); + }); + + st.equal('foo' in parsed, true, 'parsed has "foo" property'); + + var depth = 0; + var ref = parsed.foo; + while ((ref = ref.p)) { + depth += 1; + } + + st.equal(depth, 5000, 'parsed is 5000 properties deep'); + + st.end(); + }); + + t.test('parses null objects correctly', { skip: !Object.create }, function (st) { + var a = Object.create(null); + a.b = 'c'; + + st.deepEqual(qs.parse(a), { b: 'c' }); + var result = qs.parse({ a: a }); + st.equal('a' in result, true, 'result has "a" property'); + st.deepEqual(result.a, a); + st.end(); + }); + + t.test('parses dates correctly', function (st) { + var now = new Date(); + st.deepEqual(qs.parse({ a: now }), { a: now }); + st.end(); + }); + + t.test('parses regular expressions correctly', function (st) { + var re = /^test$/; + st.deepEqual(qs.parse({ a: re }), { a: re }); + st.end(); + }); + + t.test('does not allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: false }), + {}, + 'bare "toString" results in {}' + ); + + st.end(); + }); + + t.test('can allow overwriting prototype properties', function (st) { + st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); + st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); + + st.deepEqual( + qs.parse('toString', { allowPrototypes: true }), + { toString: '' }, + 'bare "toString" results in { toString: "" }' + ); + + st.end(); + }); + + t.test('params starting with a closing bracket', function (st) { + st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); + st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); + st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); + st.end(); + }); + + t.test('params starting with a starting bracket', function (st) { + st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); + st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); + st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); + st.end(); + }); + + t.test('add keys to objects', function (st) { + st.deepEqual( + qs.parse('a[b]=c&a=d'), + { a: { b: 'c', d: true } }, + 'can add keys to objects' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString'), + { a: { b: 'c' } }, + 'can not overwrite prototype' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with allowPrototypes true' + ); + + st.deepEqual( + qs.parse('a[b]=c&a=toString', { plainObjects: true }), + { a: { b: 'c', toString: true } }, + 'can overwrite prototype with plainObjects true' + ); + + st.end(); + }); + + t.test('can return null objects', { skip: !Object.create }, function (st) { + var expected = Object.create(null); + expected.a = Object.create(null); + expected.a.b = 'c'; + expected.a.hasOwnProperty = 'd'; + st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); + st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null)); + var expectedArray = Object.create(null); + expectedArray.a = Object.create(null); + expectedArray.a[0] = 'b'; + expectedArray.a.c = 'd'; + st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); + st.end(); + }); + + t.test('can parse with custom encoding', function (st) { + st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { + decoder: function (str) { + var reg = /%([0-9A-F]{2})/ig; + var result = []; + var parts = reg.exec(str); + while (parts) { + result.push(parseInt(parts[1], 16)); + parts = reg.exec(str); + } + return iconv.decode(new Buffer(result), 'shift_jis').toString(); + } + }), { 県: '大阪府' }); + st.end(); + }); + + t.test('receives the default decoder as a second argument', function (st) { + st.plan(1); + qs.parse('a', { + decoder: function (str, defaultDecoder) { + st.equal(defaultDecoder, utils.decode); + } + }); + st.end(); + }); + + t.test('throws error with wrong decoder', function (st) { + st['throws'](function () { + qs.parse({}, { decoder: 'string' }); + }, new TypeError('Decoder has to be a function.')); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.parse('a[b]=true', options); + st.deepEqual(options, {}); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/stringify.js b/node_modules/qs/test/stringify.js new file mode 100644 index 00000000..124a99dc --- /dev/null +++ b/node_modules/qs/test/stringify.js @@ -0,0 +1,596 @@ +'use strict'; + +var test = require('tape'); +var qs = require('../'); +var utils = require('../lib/utils'); +var iconv = require('iconv-lite'); + +test('stringify()', function (t) { + t.test('stringifies a querystring object', function (st) { + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: 1 }), 'a=1'); + st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); + st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); + st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC'); + st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); + st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90'); + st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7'); + st.end(); + }); + + t.test('adds query prefix', function (st) { + st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); + st.end(); + }); + + t.test('with query prefix, outputs blank string given an empty object', function (st) { + st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); + st.end(); + }); + + t.test('stringifies a nested object', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies a nested object with dots notation', function (st) { + st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); + st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); + st.end(); + }); + + t.test('stringifies an array value', function (st) { + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), + 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: ['b', 'c', 'd'] }), + 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', + 'default => indices' + ); + st.end(); + }); + + t.test('omits nulls when asked', function (st) { + st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b'); + st.end(); + }); + + t.test('omits nested nulls when asked', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('omits array indices when asked', function (st) { + st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); + st.end(); + }); + + t.test('stringifies a nested array value', function (st) { + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'indices' }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'brackets' }), 'a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d'); + st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); + st.end(); + }); + + t.test('stringifies a nested array value with dots notation', function (st) { + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a.b[0]=c&a.b[1]=d', + 'indices: stringifies with dots + indices' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a.b[]=c&a.b[]=d', + 'brackets: stringifies with dots + brackets' + ); + st.equal( + qs.stringify( + { a: { b: ['c', 'd'] } }, + { allowDots: true, encode: false } + ), + 'a.b[0]=c&a.b[1]=d', + 'default: stringifies with dots + indices' + ); + st.end(); + }); + + t.test('stringifies an object inside an array', function (st) { + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D=c', + 'indices => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 'c' }] }), + 'a%5B0%5D%5Bb%5D=c', + 'default => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices' }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'indices => indices' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets' }), + 'a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1', + 'brackets => brackets' + ); + + st.equal( + qs.stringify({ a: [{ b: { c: [1] } }] }), + 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an array with mixed objects and primitives', function (st) { + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'indices' }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'indices => indices' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'brackets' }), + 'a[][b]=1&a[]=2&a[]=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false }), + 'a[0][b]=1&a[1]=2&a[2]=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('stringifies an object inside an array with dots notation', function (st) { + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b=c', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b=c', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: 'c' }] }, + { allowDots: true, encode: false } + ), + 'a[0].b=c', + 'default => indices' + ); + + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'indices' } + ), + 'a[0].b.c[0]=1', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false, arrayFormat: 'brackets' } + ), + 'a[].b.c[]=1', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: [{ b: { c: [1] } }] }, + { allowDots: true, encode: false } + ), + 'a[0].b.c[0]=1', + 'default => indices' + ); + + st.end(); + }); + + t.test('does not omit object keys when indices = false', function (st) { + st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when indices=true', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); + st.end(); + }); + + t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); + st.end(); + }); + + t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) { + st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); + st.end(); + }); + + t.test('stringifies a complicated object', function (st) { + st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); + st.end(); + }); + + t.test('stringifies an empty value', function (st) { + st.equal(qs.stringify({ a: '' }), 'a='); + st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); + + st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); + st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); + + st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); + st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); + + st.end(); + }); + + t.test('stringifies a null object', { skip: !Object.create }, function (st) { + var obj = Object.create(null); + obj.a = 'b'; + st.equal(qs.stringify(obj), 'a=b'); + st.end(); + }); + + t.test('returns an empty string for invalid input', function (st) { + st.equal(qs.stringify(undefined), ''); + st.equal(qs.stringify(false), ''); + st.equal(qs.stringify(null), ''); + st.equal(qs.stringify(''), ''); + st.end(); + }); + + t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) { + var obj = { a: Object.create(null) }; + + obj.a.b = 'c'; + st.equal(qs.stringify(obj), 'a%5Bb%5D=c'); + st.end(); + }); + + t.test('drops keys with a value of undefined', function (st) { + st.equal(qs.stringify({ a: undefined }), ''); + + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); + st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); + st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); + st.end(); + }); + + t.test('url encodes values', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('stringifies a date', function (st) { + var now = new Date(); + var str = 'a=' + encodeURIComponent(now.toISOString()); + st.equal(qs.stringify({ a: now }), str); + st.end(); + }); + + t.test('stringifies the weird object from qs', function (st) { + st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); + st.end(); + }); + + t.test('skips properties that are part of the object prototype', function (st) { + Object.prototype.crash = 'test'; + st.equal(qs.stringify({ a: 'b' }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); + delete Object.prototype.crash; + st.end(); + }); + + t.test('stringifies boolean values', function (st) { + st.equal(qs.stringify({ a: true }), 'a=true'); + st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); + st.equal(qs.stringify({ b: false }), 'b=false'); + st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); + st.end(); + }); + + t.test('stringifies buffer values', function (st) { + st.equal(qs.stringify({ a: new Buffer('test') }), 'a=test'); + st.equal(qs.stringify({ a: { b: new Buffer('test') } }), 'a%5Bb%5D=test'); + st.end(); + }); + + t.test('stringifies an object using an alternative delimiter', function (st) { + st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); + st.end(); + }); + + t.test('doesn\'t blow up when Buffer global is missing', function (st) { + var tempBuffer = global.Buffer; + delete global.Buffer; + var result = qs.stringify({ a: 'b', c: 'd' }); + global.Buffer = tempBuffer; + st.equal(result, 'a=b&c=d'); + st.end(); + }); + + t.test('selects properties when filter=array', function (st) { + st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); + st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); + + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'indices => indices' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } + ), + 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', + 'brackets => brackets' + ); + st.equal( + qs.stringify( + { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, + { filter: ['a', 'b', 0, 2] } + ), + 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', + 'default => indices' + ); + + st.end(); + }); + + t.test('supports custom representations when filter=function', function (st) { + var calls = 0; + var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; + var filterFunc = function (prefix, value) { + calls += 1; + if (calls === 1) { + st.equal(prefix, '', 'prefix is empty'); + st.equal(value, obj); + } else if (prefix === 'c') { + return void 0; + } else if (value instanceof Date) { + st.equal(prefix, 'e[f]'); + return value.getTime(); + } + return value; + }; + + st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); + st.equal(calls, 5); + st.end(); + }); + + t.test('can disable uri encoding', function (st) { + st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); + st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); + st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); + st.end(); + }); + + t.test('can sort the keys', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); + st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); + st.end(); + }); + + t.test('can sort the keys at depth 3 or more too', function (st) { + var sort = function (a, b) { + return a.localeCompare(b); + }; + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: sort, encode: false } + ), + 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' + ); + st.equal( + qs.stringify( + { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, + { sort: null, encode: false } + ), + 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' + ); + st.end(); + }); + + t.test('can stringify with custom encoding', function (st) { + st.equal(qs.stringify({ 県: '大阪府', '': '' }, { + encoder: function (str) { + if (str.length === 0) { + return ''; + } + var buf = iconv.encode(str, 'shiftjis'); + var result = []; + for (var i = 0; i < buf.length; ++i) { + result.push(buf.readUInt8(i).toString(16)); + } + return '%' + result.join('%'); + } + }), '%8c%a7=%91%e5%8d%e3%95%7b&='); + st.end(); + }); + + t.test('receives the default encoder as a second argument', function (st) { + st.plan(2); + qs.stringify({ a: 1 }, { + encoder: function (str, defaultEncoder) { + st.equal(defaultEncoder, utils.encode); + } + }); + st.end(); + }); + + t.test('throws error with wrong encoder', function (st) { + st['throws'](function () { + qs.stringify({}, { encoder: 'string' }); + }, new TypeError('Encoder has to be a function.')); + st.end(); + }); + + t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { + st.equal(qs.stringify({ a: new Buffer([1]) }, { + encoder: function (buffer) { + if (typeof buffer === 'string') { + return buffer; + } + return String.fromCharCode(buffer.readUInt8(0) + 97); + } + }), 'a=b'); + st.end(); + }); + + t.test('serializeDate option', function (st) { + var date = new Date(); + st.equal( + qs.stringify({ a: date }), + 'a=' + date.toISOString().replace(/:/g, '%3A'), + 'default is toISOString' + ); + + var mutatedDate = new Date(); + mutatedDate.toISOString = function () { + throw new SyntaxError(); + }; + st['throws'](function () { + mutatedDate.toISOString(); + }, SyntaxError); + st.equal( + qs.stringify({ a: mutatedDate }), + 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), + 'toISOString works even when method is not locally present' + ); + + var specificDate = new Date(6); + st.equal( + qs.stringify( + { a: specificDate }, + { serializeDate: function (d) { return d.getTime() * 7; } } + ), + 'a=42', + 'custom serializeDate function called' + ); + + st.end(); + }); + + t.test('RFC 1738 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); + st.end(); + }); + + t.test('RFC 3986 spaces serialization', function (st) { + st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); + st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); + st.end(); + }); + + t.test('Backward compatibility to RFC 3986', function (st) { + st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); + st.end(); + }); + + t.test('Edge cases and unknown formats', function (st) { + ['UFO1234', false, 1234, null, {}, []].forEach( + function (format) { + st['throws']( + function () { + qs.stringify({ a: 'b c' }, { format: format }); + }, + new TypeError('Unknown format option provided.') + ); + } + ); + st.end(); + }); + + t.test('encodeValuesOnly', function (st) { + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } + ), + 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h' + ); + st.equal( + qs.stringify( + { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] } + ), + 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h' + ); + st.end(); + }); + + t.test('encodeValuesOnly - strictNullHandling', function (st) { + st.equal( + qs.stringify( + { a: { b: null } }, + { encodeValuesOnly: true, strictNullHandling: true } + ), + 'a[b]' + ); + st.end(); + }); + + t.test('does not mutate the options argument', function (st) { + var options = {}; + qs.stringify({}, options); + st.deepEqual(options, {}); + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/qs/test/utils.js b/node_modules/qs/test/utils.js new file mode 100644 index 00000000..eff4011a --- /dev/null +++ b/node_modules/qs/test/utils.js @@ -0,0 +1,34 @@ +'use strict'; + +var test = require('tape'); +var utils = require('../lib/utils'); + +test('merge()', function (t) { + t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); + + var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); + t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); + + var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); + t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); + + var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); + t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); + + var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); + t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); + + t.end(); +}); + +test('assign()', function (t) { + var target = { a: 1, b: 2 }; + var source = { b: 3, c: 4 }; + var result = utils.assign(target, source); + + t.equal(result, target, 'returns the target'); + t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); + t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); + + t.end(); +}); diff --git a/node_modules/range-parser/HISTORY.md b/node_modules/range-parser/HISTORY.md new file mode 100644 index 00000000..5e01eef4 --- /dev/null +++ b/node_modules/range-parser/HISTORY.md @@ -0,0 +1,51 @@ +1.2.0 / 2016-06-01 +================== + + * Add `combine` option to combine overlapping ranges + +1.1.0 / 2016-05-13 +================== + + * Fix incorrectly returning -1 when there is at least one valid range + * perf: remove internal function + +1.0.3 / 2015-10-29 +================== + + * perf: enable strict mode + +1.0.2 / 2014-09-08 +================== + + * Support Node.js 0.6 + +1.0.1 / 2014-09-07 +================== + + * Move repository to jshttp + +1.0.0 / 2013-12-11 +================== + + * Add repository to package.json + * Add MIT license + +0.0.4 / 2012-06-17 +================== + + * Change ret -1 for unsatisfiable and -2 when invalid + +0.0.3 / 2012-06-17 +================== + + * Fix last-byte-pos default to len - 1 + +0.0.2 / 2012-06-14 +================== + + * Add `.type` + +0.0.1 / 2012-06-11 +================== + + * Initial release diff --git a/node_modules/range-parser/LICENSE b/node_modules/range-parser/LICENSE new file mode 100644 index 00000000..35999543 --- /dev/null +++ b/node_modules/range-parser/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012-2014 TJ Holowaychuk +Copyright (c) 2015-2016 Douglas Christopher Wilson [ +// { start: 0, end: 10 }, +// { start: 50, end: 60 } +// ] +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/range-parser.svg +[npm-url]: https://npmjs.org/package/range-parser +[node-version-image]: https://img.shields.io/node/v/range-parser.svg +[node-version-url]: https://nodejs.org/endownload +[travis-image]: https://img.shields.io/travis/jshttp/range-parser.svg +[travis-url]: https://travis-ci.org/jshttp/range-parser +[coveralls-image]: https://img.shields.io/coveralls/jshttp/range-parser.svg +[coveralls-url]: https://coveralls.io/r/jshttp/range-parser +[downloads-image]: https://img.shields.io/npm/dm/range-parser.svg +[downloads-url]: https://npmjs.org/package/range-parser diff --git a/node_modules/range-parser/index.js b/node_modules/range-parser/index.js new file mode 100644 index 00000000..83b2eb6b --- /dev/null +++ b/node_modules/range-parser/index.js @@ -0,0 +1,158 @@ +/*! + * range-parser + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = rangeParser + +/** + * Parse "Range" header `str` relative to the given file `size`. + * + * @param {Number} size + * @param {String} str + * @param {Object} [options] + * @return {Array} + * @public + */ + +function rangeParser (size, str, options) { + var index = str.indexOf('=') + + if (index === -1) { + return -2 + } + + // split the range string + var arr = str.slice(index + 1).split(',') + var ranges = [] + + // add ranges type + ranges.type = str.slice(0, index) + + // parse all ranges + for (var i = 0; i < arr.length; i++) { + var range = arr[i].split('-') + var start = parseInt(range[0], 10) + var end = parseInt(range[1], 10) + + // -nnn + if (isNaN(start)) { + start = size - end + end = size - 1 + // nnn- + } else if (isNaN(end)) { + end = size - 1 + } + + // limit last-byte-pos to current length + if (end > size - 1) { + end = size - 1 + } + + // invalid or unsatisifiable + if (isNaN(start) || isNaN(end) || start > end || start < 0) { + continue + } + + // add range + ranges.push({ + start: start, + end: end + }) + } + + if (ranges.length < 1) { + // unsatisifiable + return -1 + } + + return options && options.combine + ? combineRanges(ranges) + : ranges +} + +/** + * Combine overlapping & adjacent ranges. + * @private + */ + +function combineRanges (ranges) { + var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart) + + for (var j = 0, i = 1; i < ordered.length; i++) { + var range = ordered[i] + var current = ordered[j] + + if (range.start > current.end + 1) { + // next range + ordered[++j] = range + } else if (range.end > current.end) { + // extend range + current.end = range.end + current.index = Math.min(current.index, range.index) + } + } + + // trim ordered array + ordered.length = j + 1 + + // generate combined range + var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex) + + // copy ranges type + combined.type = ranges.type + + return combined +} + +/** + * Map function to add index value to ranges. + * @private + */ + +function mapWithIndex (range, index) { + return { + start: range.start, + end: range.end, + index: index + } +} + +/** + * Map function to remove index value from ranges. + * @private + */ + +function mapWithoutIndex (range) { + return { + start: range.start, + end: range.end + } +} + +/** + * Sort function to sort ranges by index. + * @private + */ + +function sortByRangeIndex (a, b) { + return a.index - b.index +} + +/** + * Sort function to sort ranges by start position. + * @private + */ + +function sortByRangeStart (a, b) { + return a.start - b.start +} diff --git a/node_modules/range-parser/package.json b/node_modules/range-parser/package.json new file mode 100644 index 00000000..c6291e51 --- /dev/null +++ b/node_modules/range-parser/package.json @@ -0,0 +1,90 @@ +{ + "_args": [ + [ + "range-parser@1.2.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "range-parser@1.2.0", + "_id": "range-parser@1.2.0", + "_inBundle": false, + "_integrity": "sha1-9JvmtIeJTdxA3MlKMi9hEJLgDV4=", + "_location": "/range-parser", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "range-parser@1.2.0", + "name": "range-parser", + "escapedName": "range-parser", + "rawSpec": "1.2.0", + "saveSpec": null, + "fetchSpec": "1.2.0" + }, + "_requiredBy": [ + "/express", + "/send" + ], + "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.0.tgz", + "_spec": "1.2.0", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca", + "url": "http://tjholowaychuk.com" + }, + "bugs": { + "url": "https://github.com/jshttp/range-parser/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "James Wyatt Cready", + "email": "wyatt.cready@lanetix.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "description": "Range header field string parser", + "devDependencies": { + "eslint": "2.11.1", + "eslint-config-standard": "5.3.1", + "eslint-plugin-promise": "1.1.0", + "eslint-plugin-standard": "1.3.2", + "istanbul": "0.4.3", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "homepage": "https://github.com/jshttp/range-parser#readme", + "keywords": [ + "range", + "parser", + "http" + ], + "license": "MIT", + "name": "range-parser", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/range-parser.git" + }, + "scripts": { + "lint": "eslint **/*.js", + "test": "mocha --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "version": "1.2.0" +} diff --git a/node_modules/raw-body/HISTORY.md b/node_modules/raw-body/HISTORY.md new file mode 100644 index 00000000..9f1961f8 --- /dev/null +++ b/node_modules/raw-body/HISTORY.md @@ -0,0 +1,247 @@ +2.3.2 / 2017-09-09 +================== + + * deps: iconv-lite@0.4.19 + - Fix ISO-8859-1regression + - Update Windows-1255 + +2.3.1 / 2017-09-07 +================== + + * deps: bytes@3.0.0 + * deps: http-errors@1.6.2 + - deps: depd@1.1.1 + * perf: skip buffer decoding on overage chunk + +2.3.0 / 2017-08-04 +================== + + * Add TypeScript definitions + * Use `http-errors` for standard emitted errors + * deps: bytes@2.5.0 + * deps: iconv-lite@0.4.18 + - Add support for React Native + - Add a warning if not loaded as utf-8 + - Fix CESU-8 decoding in Node.js 8 + - Improve speed of ISO-8859-1 encoding + +2.2.0 / 2017-01-02 +================== + + * deps: iconv-lite@0.4.15 + - Added encoding MS-31J + - Added encoding MS-932 + - Added encoding MS-936 + - Added encoding MS-949 + - Added encoding MS-950 + - Fix GBK/GB18030 handling of Euro character + +2.1.7 / 2016-06-19 +================== + + * deps: bytes@2.4.0 + * perf: remove double-cleanup on happy path + +2.1.6 / 2016-03-07 +================== + + * deps: bytes@2.3.0 + - Drop partial bytes on all parsed units + - Fix parsing byte string that looks like hex + +2.1.5 / 2015-11-30 +================== + + * deps: bytes@2.2.0 + * deps: iconv-lite@0.4.13 + +2.1.4 / 2015-09-27 +================== + + * Fix masking critical errors from `iconv-lite` + * deps: iconv-lite@0.4.12 + - Fix CESU-8 decoding in Node.js 4.x + +2.1.3 / 2015-09-12 +================== + + * Fix sync callback when attaching data listener causes sync read + - Node.js 0.10 compatibility issue + +2.1.2 / 2015-07-05 +================== + + * Fix error stack traces to skip `makeError` + * deps: iconv-lite@0.4.11 + - Add encoding CESU-8 + +2.1.1 / 2015-06-14 +================== + + * Use `unpipe` module for unpiping requests + +2.1.0 / 2015-05-28 +================== + + * deps: iconv-lite@0.4.10 + - Improved UTF-16 endianness detection + - Leading BOM is now removed when decoding + - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails + +2.0.2 / 2015-05-21 +================== + + * deps: bytes@2.1.0 + - Slight optimizations + +2.0.1 / 2015-05-10 +================== + + * Fix a false-positive when unpiping in Node.js 0.8 + +2.0.0 / 2015-05-08 +================== + + * Return a promise without callback instead of thunk + * deps: bytes@2.0.1 + - units no longer case sensitive when parsing + +1.3.4 / 2015-04-15 +================== + + * Fix hanging callback if request aborts during read + * deps: iconv-lite@0.4.8 + - Add encoding alias UNICODE-1-1-UTF-7 + +1.3.3 / 2015-02-08 +================== + + * deps: iconv-lite@0.4.7 + - Gracefully support enumerables on `Object.prototype` + +1.3.2 / 2015-01-20 +================== + + * deps: iconv-lite@0.4.6 + - Fix rare aliases of single-byte encodings + +1.3.1 / 2014-11-21 +================== + + * deps: iconv-lite@0.4.5 + - Fix Windows-31J and X-SJIS encoding support + +1.3.0 / 2014-07-20 +================== + + * Fully unpipe the stream on error + - Fixes `Cannot switch to old mode now` error on Node.js 0.10+ + +1.2.3 / 2014-07-20 +================== + + * deps: iconv-lite@0.4.4 + - Added encoding UTF-7 + +1.2.2 / 2014-06-19 +================== + + * Send invalid encoding error to callback + +1.2.1 / 2014-06-15 +================== + + * deps: iconv-lite@0.4.3 + - Added encodings UTF-16BE and UTF-16 with BOM + +1.2.0 / 2014-06-13 +================== + + * Passing string as `options` interpreted as encoding + * Support all encodings from `iconv-lite` + +1.1.7 / 2014-06-12 +================== + + * use `string_decoder` module from npm + +1.1.6 / 2014-05-27 +================== + + * check encoding for old streams1 + * support node.js < 0.10.6 + +1.1.5 / 2014-05-14 +================== + + * bump bytes + +1.1.4 / 2014-04-19 +================== + + * allow true as an option + * bump bytes + +1.1.3 / 2014-03-02 +================== + + * fix case when length=null + +1.1.2 / 2013-12-01 +================== + + * be less strict on state.encoding check + +1.1.1 / 2013-11-27 +================== + + * add engines + +1.1.0 / 2013-11-27 +================== + + * add err.statusCode and err.type + * allow for encoding option to be true + * pause the stream instead of dumping on error + * throw if the stream's encoding is set + +1.0.1 / 2013-11-19 +================== + + * dont support streams1, throw if dev set encoding + +1.0.0 / 2013-11-17 +================== + + * rename `expected` option to `length` + +0.2.0 / 2013-11-15 +================== + + * republish + +0.1.1 / 2013-11-15 +================== + + * use bytes + +0.1.0 / 2013-11-11 +================== + + * generator support + +0.0.3 / 2013-10-10 +================== + + * update repo + +0.0.2 / 2013-09-14 +================== + + * dump stream on bad headers + * listen to events after defining received and buffers + +0.0.1 / 2013-09-14 +================== + + * Initial release diff --git a/node_modules/raw-body/LICENSE b/node_modules/raw-body/LICENSE new file mode 100644 index 00000000..d695c8fd --- /dev/null +++ b/node_modules/raw-body/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2013-2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/raw-body/README.md b/node_modules/raw-body/README.md new file mode 100644 index 00000000..c4db8a6b --- /dev/null +++ b/node_modules/raw-body/README.md @@ -0,0 +1,219 @@ +# raw-body + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build status][travis-image]][travis-url] +[![Test coverage][coveralls-image]][coveralls-url] + +Gets the entire buffer of a stream either as a `Buffer` or a string. +Validates the stream's length against an expected length and maximum limit. +Ideal for parsing request bodies. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install raw-body +``` + +### TypeScript + +This module includes a [TypeScript](https://www.typescriptlang.org/) +declarition file to enable auto complete in compatible editors and type +information for TypeScript projects. This module depends on the Node.js +types, so install `@types/node`: + +```sh +$ npm install @types/node +``` + +## API + + + +```js +var getRawBody = require('raw-body') +``` + +### getRawBody(stream, [options], [callback]) + +**Returns a promise if no callback specified and global `Promise` exists.** + +Options: + +- `length` - The length of the stream. + If the contents of the stream do not add up to this length, + an `400` error code is returned. +- `limit` - The byte limit of the body. + This is the number of bytes or any string format supported by + [bytes](https://www.npmjs.com/package/bytes), + for example `1000`, `'500kb'` or `'3mb'`. + If the body ends up being larger than this limit, + a `413` error code is returned. +- `encoding` - The encoding to use to decode the body into a string. + By default, a `Buffer` instance will be returned when no encoding is specified. + Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`. + You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme). + +You can also pass a string in place of options to just specify the encoding. + +If an error occurs, the stream will be paused, everything unpiped, +and you are responsible for correctly disposing the stream. +For HTTP requests, no handling is required if you send a response. +For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. + +## Errors + +This module creates errors depending on the error condition during reading. +The error may be an error from the underlying Node.js implementation, but is +otherwise an error created by this module, which has the following attributes: + + * `limit` - the limit in bytes + * `length` and `expected` - the expected length of the stream + * `received` - the received bytes + * `encoding` - the invalid encoding + * `status` and `statusCode` - the corresponding status code for the error + * `type` - the error type + +### Types + +The errors from this module have a `type` property which allows for the progamatic +determination of the type of error returned. + +#### encoding.unsupported + +This error will occur when the `encoding` option is specified, but the value does +not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme) +module. + +#### entity.too.large + +This error will occur when the `limit` option is specified, but the stream has +an entity that is larger. + +#### request.aborted + +This error will occur when the request stream is aborted by the client before +reading the body has finished. + +#### request.size.invalid + +This error will occur when the `length` option is specified, but the stream has +emitted more bytes. + +#### stream.encoding.set + +This error will occur when the given stream has an encoding set on it, making it +a decoded stream. The stream should not have an encoding set and is expected to +emit `Buffer` objects. + +## Examples + +### Simple Express example + +```js +var contentType = require('content-type') +var express = require('express') +var getRawBody = require('raw-body') + +var app = express() + +app.use(function (req, res, next) { + getRawBody(req, { + length: req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(req).parameters.charset + }, function (err, string) { + if (err) return next(err) + req.text = string + next() + }) +}) + +// now access req.text +``` + +### Simple Koa example + +```js +var contentType = require('content-type') +var getRawBody = require('raw-body') +var koa = require('koa') + +var app = koa() + +app.use(function * (next) { + this.text = yield getRawBody(this.req, { + length: this.req.headers['content-length'], + limit: '1mb', + encoding: contentType.parse(this.req).parameters.charset + }) + yield next +}) + +// now access this.text +``` + +### Using as a promise + +To use this library as a promise, simply omit the `callback` and a promise is +returned, provided that a global `Promise` is defined. + +```js +var getRawBody = require('raw-body') +var http = require('http') + +var server = http.createServer(function (req, res) { + getRawBody(req) + .then(function (buf) { + res.statusCode = 200 + res.end(buf.length + ' bytes submitted') + }) + .catch(function (err) { + res.statusCode = 500 + res.end(err.message) + }) +}) + +server.listen(3000) +``` + +### Using with TypeScript + +```ts +import * as getRawBody from 'raw-body'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + getRawBody(req) + .then((buf) => { + res.statusCode = 200; + res.end(buf.length + ' bytes submitted'); + }) + .catch((err) => { + res.statusCode = err.statusCode; + res.end(err.message); + }); +}); + +server.listen(3000); +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/raw-body.svg +[npm-url]: https://npmjs.org/package/raw-body +[node-version-image]: https://img.shields.io/node/v/raw-body.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg +[travis-url]: https://travis-ci.org/stream-utils/raw-body +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master +[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg +[downloads-url]: https://npmjs.org/package/raw-body diff --git a/node_modules/raw-body/index.d.ts b/node_modules/raw-body/index.d.ts new file mode 100644 index 00000000..dcbbebd4 --- /dev/null +++ b/node_modules/raw-body/index.d.ts @@ -0,0 +1,87 @@ +import { Readable } from 'stream'; + +declare namespace getRawBody { + export type Encoding = string | true; + + export interface Options { + /** + * The expected length of the stream. + */ + length?: number | string | null; + /** + * The byte limit of the body. This is the number of bytes or any string + * format supported by `bytes`, for example `1000`, `'500kb'` or `'3mb'`. + */ + limit?: number | string | null; + /** + * The encoding to use to decode the body into a string. By default, a + * `Buffer` instance will be returned when no encoding is specified. Most + * likely, you want `utf-8`, so setting encoding to `true` will decode as + * `utf-8`. You can use any type of encoding supported by `iconv-lite`. + */ + encoding?: Encoding | null; + } + + export interface RawBodyError extends Error { + /** + * The limit in bytes. + */ + limit?: number; + /** + * The expected length of the stream. + */ + length?: number; + expected?: number; + /** + * The received bytes. + */ + received?: number; + /** + * The encoding. + */ + encoding?: string; + /** + * The corresponding status code for the error. + */ + status: number; + statusCode: number; + /** + * The error type. + */ + type: string; + } +} + +/** + * Gets the entire buffer of a stream either as a `Buffer` or a string. + * Validates the stream's length against an expected length and maximum + * limit. Ideal for parsing request bodies. + */ +declare function getRawBody( + stream: Readable, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding, + callback: (err: getRawBody.RawBodyError, body: string) => void +): void; + +declare function getRawBody( + stream: Readable, + options: getRawBody.Options, + callback: (err: getRawBody.RawBodyError, body: Buffer) => void +): void; + +declare function getRawBody( + stream: Readable, + options: (getRawBody.Options & { encoding: getRawBody.Encoding }) | getRawBody.Encoding +): Promise; + +declare function getRawBody( + stream: Readable, + options?: getRawBody.Options +): Promise; + +export = getRawBody; diff --git a/node_modules/raw-body/index.js b/node_modules/raw-body/index.js new file mode 100644 index 00000000..7fe81860 --- /dev/null +++ b/node_modules/raw-body/index.js @@ -0,0 +1,286 @@ +/*! + * raw-body + * Copyright(c) 2013-2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var bytes = require('bytes') +var createError = require('http-errors') +var iconv = require('iconv-lite') +var unpipe = require('unpipe') + +/** + * Module exports. + * @public + */ + +module.exports = getRawBody + +/** + * Module variables. + * @private + */ + +var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: / + +/** + * Get the decoder for a given encoding. + * + * @param {string} encoding + * @private + */ + +function getDecoder (encoding) { + if (!encoding) return null + + try { + return iconv.getDecoder(encoding) + } catch (e) { + // error getting decoder + if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e + + // the encoding was not found + throw createError(415, 'specified encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) + } +} + +/** + * Get the raw body of a stream (typically HTTP). + * + * @param {object} stream + * @param {object|string|function} [options] + * @param {function} [callback] + * @public + */ + +function getRawBody (stream, options, callback) { + var done = callback + var opts = options || {} + + if (options === true || typeof options === 'string') { + // short cut for encoding + opts = { + encoding: options + } + } + + if (typeof options === 'function') { + done = options + opts = {} + } + + // validate callback is a function, if provided + if (done !== undefined && typeof done !== 'function') { + throw new TypeError('argument callback must be a function') + } + + // require the callback without promises + if (!done && !global.Promise) { + throw new TypeError('argument callback is required') + } + + // get encoding + var encoding = opts.encoding !== true + ? opts.encoding + : 'utf-8' + + // convert the limit to an integer + var limit = bytes.parse(opts.limit) + + // convert the expected length to an integer + var length = opts.length != null && !isNaN(opts.length) + ? parseInt(opts.length, 10) + : null + + if (done) { + // classic callback style + return readStream(stream, encoding, length, limit, done) + } + + return new Promise(function executor (resolve, reject) { + readStream(stream, encoding, length, limit, function onRead (err, buf) { + if (err) return reject(err) + resolve(buf) + }) + }) +} + +/** + * Halt a stream. + * + * @param {Object} stream + * @private + */ + +function halt (stream) { + // unpipe everything from the stream + unpipe(stream) + + // pause stream + if (typeof stream.pause === 'function') { + stream.pause() + } +} + +/** + * Read the data from the stream. + * + * @param {object} stream + * @param {string} encoding + * @param {number} length + * @param {number} limit + * @param {function} callback + * @public + */ + +function readStream (stream, encoding, length, limit, callback) { + var complete = false + var sync = true + + // check the length and limit options. + // note: we intentionally leave the stream paused, + // so users should handle the stream themselves. + if (limit !== null && length !== null && length > limit) { + return done(createError(413, 'request entity too large', { + expected: length, + length: length, + limit: limit, + type: 'entity.too.large' + })) + } + + // streams1: assert request encoding is buffer. + // streams2+: assert the stream encoding is buffer. + // stream._decoder: streams1 + // state.encoding: streams2 + // state.decoder: streams2, specifically < 0.10.6 + var state = stream._readableState + if (stream._decoder || (state && (state.encoding || state.decoder))) { + // developer error + return done(createError(500, 'stream encoding should not be set', { + type: 'stream.encoding.set' + })) + } + + var received = 0 + var decoder + + try { + decoder = getDecoder(encoding) + } catch (err) { + return done(err) + } + + var buffer = decoder + ? '' + : [] + + // attach listeners + stream.on('aborted', onAborted) + stream.on('close', cleanup) + stream.on('data', onData) + stream.on('end', onEnd) + stream.on('error', onEnd) + + // mark sync section complete + sync = false + + function done () { + var args = new Array(arguments.length) + + // copy arguments + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + + // mark complete + complete = true + + if (sync) { + process.nextTick(invokeCallback) + } else { + invokeCallback() + } + + function invokeCallback () { + cleanup() + + if (args[0]) { + // halt the stream on error + halt(stream) + } + + callback.apply(null, args) + } + } + + function onAborted () { + if (complete) return + + done(createError(400, 'request aborted', { + code: 'ECONNABORTED', + expected: length, + length: length, + received: received, + type: 'request.aborted' + })) + } + + function onData (chunk) { + if (complete) return + + received += chunk.length + + if (limit !== null && received > limit) { + done(createError(413, 'request entity too large', { + limit: limit, + received: received, + type: 'entity.too.large' + })) + } else if (decoder) { + buffer += decoder.write(chunk) + } else { + buffer.push(chunk) + } + } + + function onEnd (err) { + if (complete) return + if (err) return done(err) + + if (length !== null && received !== length) { + done(createError(400, 'request size did not match content length', { + expected: length, + length: length, + received: received, + type: 'request.size.invalid' + })) + } else { + var string = decoder + ? buffer + (decoder.end() || '') + : Buffer.concat(buffer) + done(null, string) + } + } + + function cleanup () { + buffer = null + + stream.removeListener('aborted', onAborted) + stream.removeListener('data', onData) + stream.removeListener('end', onEnd) + stream.removeListener('error', onEnd) + stream.removeListener('close', cleanup) + } +} diff --git a/node_modules/raw-body/node_modules/depd/History.md b/node_modules/raw-body/node_modules/depd/History.md new file mode 100644 index 00000000..f0016499 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/History.md @@ -0,0 +1,90 @@ +1.1.1 / 2017-07-27 +================== + + * Remove unnecessary `Buffer` loading + * Support Node.js 0.6 to 8.x + +1.1.0 / 2015-09-14 +================== + + * Enable strict mode in more places + * Support io.js 3.x + * Support io.js 2.x + * Support web browser loading + - Requires bundler like Browserify or webpack + +1.0.1 / 2015-04-07 +================== + + * Fix `TypeError`s when under `'use strict'` code + * Fix useless type name on auto-generated messages + * Support io.js 1.x + * Support Node.js 0.12 + +1.0.0 / 2014-09-17 +================== + + * No changes + +0.4.5 / 2014-09-09 +================== + + * Improve call speed to functions using the function wrapper + * Support Node.js 0.6 + +0.4.4 / 2014-07-27 +================== + + * Work-around v8 generating empty stack traces + +0.4.3 / 2014-07-26 +================== + + * Fix exception when global `Error.stackTraceLimit` is too low + +0.4.2 / 2014-07-19 +================== + + * Correct call site for wrapped functions and properties + +0.4.1 / 2014-07-19 +================== + + * Improve automatic message generation for function properties + +0.4.0 / 2014-07-19 +================== + + * Add `TRACE_DEPRECATION` environment variable + * Remove non-standard grey color from color output + * Support `--no-deprecation` argument + * Support `--trace-deprecation` argument + * Support `deprecate.property(fn, prop, message)` + +0.3.0 / 2014-06-16 +================== + + * Add `NO_DEPRECATION` environment variable + +0.2.0 / 2014-06-15 +================== + + * Add `deprecate.property(obj, prop, message)` + * Remove `supports-color` dependency for node.js 0.8 + +0.1.0 / 2014-06-15 +================== + + * Add `deprecate.function(fn, message)` + * Add `process.on('deprecation', fn)` emitter + * Automatically generate message when omitted from `deprecate()` + +0.0.1 / 2014-06-15 +================== + + * Fix warning for dynamic calls at singe call site + +0.0.0 / 2014-06-15 +================== + + * Initial implementation diff --git a/node_modules/raw-body/node_modules/depd/LICENSE b/node_modules/raw-body/node_modules/depd/LICENSE new file mode 100644 index 00000000..84441fbb --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/raw-body/node_modules/depd/Readme.md b/node_modules/raw-body/node_modules/depd/Readme.md new file mode 100644 index 00000000..9e7d8726 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/Readme.md @@ -0,0 +1,283 @@ +# depd + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![Gratipay][gratipay-image]][gratipay-url] + +Deprecate all the things + +> With great modules comes great responsibility; mark things deprecated! + +## Install + +This module is installed directly using `npm`: + +```sh +$ npm install depd +``` + +This module can also be bundled with systems like +[Browserify](http://browserify.org/) or [webpack](https://webpack.github.io/), +though by default this module will alter it's API to no longer display or +track deprecations. + +## API + + + +```js +var deprecate = require('depd')('my-module') +``` + +This library allows you to display deprecation messages to your users. +This library goes above and beyond with deprecation warnings by +introspection of the call stack (but only the bits that it is interested +in). + +Instead of just warning on the first invocation of a deprecated +function and never again, this module will warn on the first invocation +of a deprecated function per unique call site, making it ideal to alert +users of all deprecated uses across the code base, rather than just +whatever happens to execute first. + +The deprecation warnings from this module also include the file and line +information for the call into the module that the deprecated function was +in. + +**NOTE** this library has a similar interface to the `debug` module, and +this module uses the calling file to get the boundary for the call stacks, +so you should always create a new `deprecate` object in each file and not +within some central file. + +### depd(namespace) + +Create a new deprecate function that uses the given namespace name in the +messages and will display the call site prior to the stack entering the +file this function was called from. It is highly suggested you use the +name of your module as the namespace. + +### deprecate(message) + +Call this function from deprecated code to display a deprecation message. +This message will appear once per unique caller site. Caller site is the +first call site in the stack in a different file from the caller of this +function. + +If the message is omitted, a message is generated for you based on the site +of the `deprecate()` call and will display the name of the function called, +similar to the name displayed in a stack trace. + +### deprecate.function(fn, message) + +Call this function to wrap a given function in a deprecation message on any +call to the function. An optional message can be supplied to provide a custom +message. + +### deprecate.property(obj, prop, message) + +Call this function to wrap a given property on object in a deprecation message +on any accessing or setting of the property. An optional message can be supplied +to provide a custom message. + +The method must be called on the object where the property belongs (not +inherited from the prototype). + +If the property is a data descriptor, it will be converted to an accessor +descriptor in order to display the deprecation message. + +### process.on('deprecation', fn) + +This module will allow easy capturing of deprecation errors by emitting the +errors as the type "deprecation" on the global `process`. If there are no +listeners for this type, the errors are written to STDERR as normal, but if +there are any listeners, nothing will be written to STDERR and instead only +emitted. From there, you can write the errors in a different format or to a +logging source. + +The error represents the deprecation and is emitted only once with the same +rules as writing to STDERR. The error has the following properties: + + - `message` - This is the message given by the library + - `name` - This is always `'DeprecationError'` + - `namespace` - This is the namespace the deprecation came from + - `stack` - This is the stack of the call to the deprecated thing + +Example `error.stack` output: + +``` +DeprecationError: my-cool-module deprecated oldfunction + at Object. ([eval]-wrapper:6:22) + at Module._compile (module.js:456:26) + at evalScript (node.js:532:25) + at startup (node.js:80:7) + at node.js:902:3 +``` + +### process.env.NO_DEPRECATION + +As a user of modules that are deprecated, the environment variable `NO_DEPRECATION` +is provided as a quick solution to silencing deprecation warnings from being +output. The format of this is similar to that of `DEBUG`: + +```sh +$ NO_DEPRECATION=my-module,othermod node app.js +``` + +This will suppress deprecations from being output for "my-module" and "othermod". +The value is a list of comma-separated namespaces. To suppress every warning +across all namespaces, use the value `*` for a namespace. + +Providing the argument `--no-deprecation` to the `node` executable will suppress +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not suppress the deperecations given to any "deprecation" +event listeners, just the output to STDERR. + +### process.env.TRACE_DEPRECATION + +As a user of modules that are deprecated, the environment variable `TRACE_DEPRECATION` +is provided as a solution to getting more detailed location information in deprecation +warnings by including the entire stack trace. The format of this is the same as +`NO_DEPRECATION`: + +```sh +$ TRACE_DEPRECATION=my-module,othermod node app.js +``` + +This will include stack traces for deprecations being output for "my-module" and +"othermod". The value is a list of comma-separated namespaces. To trace every +warning across all namespaces, use the value `*` for a namespace. + +Providing the argument `--trace-deprecation` to the `node` executable will trace +all deprecations (only available in Node.js 0.8 or higher). + +**NOTE** This will not trace the deperecations silenced by `NO_DEPRECATION`. + +## Display + +![message](files/message.png) + +When a user calls a function in your library that you mark deprecated, they +will see the following written to STDERR (in the given colors, similar colors +and layout to the `debug` module): + +``` +bright cyan bright yellow +| | reset cyan +| | | | +▼ ▼ ▼ ▼ +my-cool-module deprecated oldfunction [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ +| | | | +namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +If the user redirects their STDERR to a file or somewhere that does not support +colors, they see (similar layout to the `debug` module): + +``` +Sun, 15 Jun 2014 05:21:37 GMT my-cool-module deprecated oldfunction at [eval]-wrapper:6:22 +▲ ▲ ▲ ▲ ▲ +| | | | | +timestamp of message namespace | | location of mycoolmod.oldfunction() call + | deprecation message + the word "deprecated" +``` + +## Examples + +### Deprecating all calls to a function + +This will display a deprecated message about "oldfunction" being deprecated +from "my-module" on STDERR. + +```js +var deprecate = require('depd')('my-cool-module') + +// message automatically derived from function name +// Object.oldfunction +exports.oldfunction = deprecate.function(function oldfunction () { + // all calls to function are deprecated +}) + +// specific message +exports.oldfunction = deprecate.function(function () { + // all calls to function are deprecated +}, 'oldfunction') +``` + +### Conditionally deprecating a function call + +This will display a deprecated message about "weirdfunction" being deprecated +from "my-module" on STDERR when called with less than 2 arguments. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } +} +``` + +When calling `deprecate` as a function, the warning is counted per call site +within your own module, so you can display different deprecations depending +on different situations and the users will still get all the warnings: + +```js +var deprecate = require('depd')('my-cool-module') + +exports.weirdfunction = function () { + if (arguments.length < 2) { + // calls with 0 or 1 args are deprecated + deprecate('weirdfunction args < 2') + } else if (typeof arguments[0] !== 'string') { + // calls with non-string first argument are deprecated + deprecate('weirdfunction non-string first arg') + } +} +``` + +### Deprecating property access + +This will display a deprecated message about "oldprop" being deprecated +from "my-module" on STDERR when accessed. A deprecation will be displayed +when setting the value and when getting the value. + +```js +var deprecate = require('depd')('my-cool-module') + +exports.oldprop = 'something' + +// message automatically derives from property name +deprecate.property(exports, 'oldprop') + +// explicit message +deprecate.property(exports, 'oldprop', 'oldprop >= 0.10') +``` + +## License + +[MIT](LICENSE) + +[npm-version-image]: https://img.shields.io/npm/v/depd.svg +[npm-downloads-image]: https://img.shields.io/npm/dm/depd.svg +[npm-url]: https://npmjs.org/package/depd +[travis-image]: https://img.shields.io/travis/dougwilson/nodejs-depd/master.svg?label=linux +[travis-url]: https://travis-ci.org/dougwilson/nodejs-depd +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/nodejs-depd/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/nodejs-depd +[coveralls-image]: https://img.shields.io/coveralls/dougwilson/nodejs-depd/master.svg +[coveralls-url]: https://coveralls.io/r/dougwilson/nodejs-depd?branch=master +[node-image]: https://img.shields.io/node/v/depd.svg +[node-url]: https://nodejs.org/en/download/ +[gratipay-image]: https://img.shields.io/gratipay/dougwilson.svg +[gratipay-url]: https://www.gratipay.com/dougwilson/ diff --git a/node_modules/raw-body/node_modules/depd/index.js b/node_modules/raw-body/node_modules/depd/index.js new file mode 100644 index 00000000..73d81ab5 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/index.js @@ -0,0 +1,520 @@ +/*! + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var callSiteToString = require('./lib/compat').callSiteToString +var eventListenerCount = require('./lib/compat').eventListenerCount +var relative = require('path').relative + +/** + * Module exports. + */ + +module.exports = depd + +/** + * Get the path to base files on. + */ + +var basePath = process.cwd() + +/** + * Determine if namespace is contained in the string. + */ + +function containsNamespace (str, namespace) { + var val = str.split(/[ ,]+/) + + namespace = String(namespace).toLowerCase() + + for (var i = 0; i < val.length; i++) { + if (!(str = val[i])) continue + + // namespace contained + if (str === '*' || str.toLowerCase() === namespace) { + return true + } + } + + return false +} + +/** + * Convert a data descriptor to accessor descriptor. + */ + +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} + +/** + * Create arguments string to keep arity. + */ + +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} + +/** + * Create stack string from stack. + */ + +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } + + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Determine if namespace is ignored. + */ + +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + + // namespace ignored + return containsNamespace(str, namespace) +} + +/** + * Determine if namespace is traced. + */ + +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} + +/** + * Display deprecation message. + */ + +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + callSite = callSiteLocation(stack[1]) + callSite.name = site.name + file = callSite[0] + } else { + // get call site + i = 2 + site = callSiteLocation(stack[i]) + callSite = site + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } + + var key = caller + ? site.join(':') + '__' + caller.join(':') + : undefined + + if (key !== undefined && key in this._warned) { + // already warned + return + } + + this._warned[key] = true + + // generate automatic message from call site + if (!message) { + message = callSite === site || !callSite.name + ? defaultMessage(site) + : defaultMessage(callSite) + } + + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, message, stack.slice(i)) + process.emit('deprecation', err) + return + } + + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var msg = format.call(this, message, caller, stack.slice(i)) + process.stderr.write(msg + '\n', 'utf8') +} + +/** + * Get call site location as array. + */ + +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + + var site = [file, line, colm] + + site.callSite = callSite + site.name = callSite.getFunctionName() + + return site +} + +/** + * Generate a default message from the site. + */ + +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name + + // make useful anonymous name + if (!funcName) { + funcName = '' + } + + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined + } + + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } + + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} + +/** + * Format deprecation message without color. + */ + +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() + + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + + return formatted +} + +/** + * Format deprecation message with color. + */ + +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset + + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } + + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} + +/** + * Format call site location. + */ + +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} + +/** + * Get the stack as array of call sites. + */ + +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) + + // capture the stack + Error.captureStackTrace(obj) + + // slice this function off the top + var stack = obj.stack.slice(1) + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack +} + +/** + * Capture call site stack from v8. + */ + +function prepareObjectStackTrace (obj, stack) { + return stack +} + +/** + * Return a wrapped function in a deprecation message. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) + + site.name = fn.name + + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') + + return deprecatedfn +} + +/** + * Wrap property in a deprecation message. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } + + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) + + // set site name + site.name = prop + + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } + + var get = descriptor.get + var set = descriptor.set + + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) + } + } + + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} + +/** + * Create DeprecationError for deprecation + */ + +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } + + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) + + return error +} diff --git a/node_modules/raw-body/node_modules/depd/lib/browser/index.js b/node_modules/raw-body/node_modules/depd/lib/browser/index.js new file mode 100644 index 00000000..6be45cc2 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/lib/browser/index.js @@ -0,0 +1,77 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = depd + +/** + * Create deprecate for namespace in caller. + */ + +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } + + function deprecate (message) { + // no-op in browser + } + + deprecate._file = undefined + deprecate._ignored = true + deprecate._namespace = namespace + deprecate._traced = false + deprecate._warned = Object.create(null) + + deprecate.function = wrapfunction + deprecate.property = wrapproperty + + return deprecate +} + +/** + * Return a wrapped function in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } + + return fn +} + +/** + * Wrap property in a deprecation message. + * + * This is a no-op version of the wrapper, which does nothing but call + * validation. + */ + +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + + if (!descriptor) { + throw new TypeError('must call property on owner object') + } + + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } +} diff --git a/node_modules/raw-body/node_modules/depd/lib/compat/callsite-tostring.js b/node_modules/raw-body/node_modules/depd/lib/compat/callsite-tostring.js new file mode 100644 index 00000000..73186dc6 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/lib/compat/callsite-tostring.js @@ -0,0 +1,103 @@ +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = callSiteToString + +/** + * Format a CallSite file location to a string. + */ + +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' + + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } + + if (fileName) { + fileLocation += fileName + + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber + + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } + + return fileLocation || 'unknown source' +} + +/** + * Format a CallSite to a string. + */ + +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' + + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) + + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } + + line += functionName + + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } + + if (addSuffix) { + line += ' (' + fileLocation + ')' + } + + return line +} + +/** + * Get constructor name of reviver. + */ + +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} diff --git a/node_modules/raw-body/node_modules/depd/lib/compat/event-listener-count.js b/node_modules/raw-body/node_modules/depd/lib/compat/event-listener-count.js new file mode 100644 index 00000000..3a8925d1 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/lib/compat/event-listener-count.js @@ -0,0 +1,22 @@ +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = eventListenerCount + +/** + * Get the count of listeners on an event emitter of a specific type. + */ + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length +} diff --git a/node_modules/raw-body/node_modules/depd/lib/compat/index.js b/node_modules/raw-body/node_modules/depd/lib/compat/index.js new file mode 100644 index 00000000..955b3336 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/lib/compat/index.js @@ -0,0 +1,79 @@ +/*! + * depd + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var EventEmitter = require('events').EventEmitter + +/** + * Module exports. + * @public + */ + +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace + + function prepareObjectStackTrace (obj, stack) { + return stack + } + + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 + + // capture the stack + Error.captureStackTrace(obj) + + // slice the stack + var stack = obj.stack.slice() + + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit + + return stack[0].toString ? toString : require('./callsite-tostring') +}) + +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || require('./event-listener-count') +}) + +/** + * Define a lazy property. + */ + +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) + + return val + } + + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} + +/** + * Call toString() on the obj + */ + +function toString (obj) { + return obj.toString() +} diff --git a/node_modules/raw-body/node_modules/depd/package.json b/node_modules/raw-body/node_modules/depd/package.json new file mode 100644 index 00000000..043164a2 --- /dev/null +++ b/node_modules/raw-body/node_modules/depd/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "depd@1.1.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "depd@1.1.1", + "_id": "depd@1.1.1", + "_inBundle": false, + "_integrity": "sha1-V4O04cRZ8G+lyif5kfPQbnoxA1k=", + "_location": "/raw-body/depd", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "depd@1.1.1", + "name": "depd", + "escapedName": "depd", + "rawSpec": "1.1.1", + "saveSpec": null, + "fetchSpec": "1.1.1" + }, + "_requiredBy": [ + "/raw-body/http-errors" + ], + "_resolved": "https://registry.npmjs.org/depd/-/depd-1.1.1.tgz", + "_spec": "1.1.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "browser": "lib/browser/index.js", + "bugs": { + "url": "https://github.com/dougwilson/nodejs-depd/issues" + }, + "description": "Deprecate all the things", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "7.1.0", + "eslint-plugin-markdown": "1.0.0-beta.7", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "2.3.1", + "istanbul": "0.4.5", + "mocha": "~1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "lib/", + "History.md", + "LICENSE", + "index.js", + "Readme.md" + ], + "homepage": "https://github.com/dougwilson/nodejs-depd#readme", + "keywords": [ + "deprecate", + "deprecated" + ], + "license": "MIT", + "name": "depd", + "repository": { + "type": "git", + "url": "git+https://github.com/dougwilson/nodejs-depd.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --no-exit test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/" + }, + "version": "1.1.1" +} diff --git a/node_modules/raw-body/node_modules/http-errors/HISTORY.md b/node_modules/raw-body/node_modules/http-errors/HISTORY.md new file mode 100644 index 00000000..b6ee4a0a --- /dev/null +++ b/node_modules/raw-body/node_modules/http-errors/HISTORY.md @@ -0,0 +1,124 @@ +2017-08-04 / 1.6.2 +================== + + * deps: depd@1.1.1 + - Remove unnecessary `Buffer` loading + +2017-02-20 / 1.6.1 +================== + + * deps: setprototypeof@1.0.3 + - Fix shim for old browsers + +2017-02-14 / 1.6.0 +================== + + * Accept custom 4xx and 5xx status codes in factory + * Add deprecation message to `"I'mateapot"` export + * Deprecate passing status code as anything except first argument in factory + * Deprecate using non-error status codes + * Make `message` property enumerable for `HttpError`s + +2016-11-16 / 1.5.1 +================== + + * deps: inherits@2.0.3 + - Fix issue loading in browser + * deps: setprototypeof@1.0.2 + * deps: statuses@'>= 1.3.1 < 2' + +2016-05-18 / 1.5.0 +================== + + * Support new code `421 Misdirected Request` + * Use `setprototypeof` module to replace `__proto__` setting + * deps: statuses@'>= 1.3.0 < 2' + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: enable strict mode + +2016-01-28 / 1.4.0 +================== + + * Add `HttpError` export, for `err instanceof createError.HttpError` + * deps: inherits@2.0.1 + * deps: statuses@'>= 1.2.1 < 2' + - Fix message for status 451 + - Remove incorrect nginx status code + +2015-02-02 / 1.3.1 +================== + + * Fix regression where status can be overwritten in `createError` `props` + +2015-02-01 / 1.3.0 +================== + + * Construct errors using defined constructors from `createError` + * Fix error names that are not identifiers + - `createError["I'mateapot"]` is now `createError.ImATeapot` + * Set a meaningful `name` property on constructed errors + +2014-12-09 / 1.2.8 +================== + + * Fix stack trace from exported function + * Remove `arguments.callee` usage + +2014-10-14 / 1.2.7 +================== + + * Remove duplicate line + +2014-10-02 / 1.2.6 +================== + + * Fix `expose` to be `true` for `ClientError` constructor + +2014-09-28 / 1.2.5 +================== + + * deps: statuses@1 + +2014-09-21 / 1.2.4 +================== + + * Fix dependency version to work with old `npm`s + +2014-09-21 / 1.2.3 +================== + + * deps: statuses@~1.1.0 + +2014-09-21 / 1.2.2 +================== + + * Fix publish error + +2014-09-21 / 1.2.1 +================== + + * Support Node.js 0.6 + * Use `inherits` instead of `util` + +2014-09-09 / 1.2.0 +================== + + * Fix the way inheriting functions + * Support `expose` being provided in properties argument + +2014-09-08 / 1.1.0 +================== + + * Default status to 500 + * Support provided `error` to extend + +2014-09-08 / 1.0.1 +================== + + * Fix accepting string message + +2014-09-08 / 1.0.0 +================== + + * Initial release diff --git a/node_modules/raw-body/node_modules/http-errors/LICENSE b/node_modules/raw-body/node_modules/http-errors/LICENSE new file mode 100644 index 00000000..82af4df5 --- /dev/null +++ b/node_modules/raw-body/node_modules/http-errors/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong me@jongleberry.com +Copyright (c) 2016 Douglas Christopher Wilson doug@somethingdoug.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/raw-body/node_modules/http-errors/README.md b/node_modules/raw-body/node_modules/http-errors/README.md new file mode 100644 index 00000000..79663d82 --- /dev/null +++ b/node_modules/raw-body/node_modules/http-errors/README.md @@ -0,0 +1,135 @@ +# http-errors + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Create HTTP errors for Express, Koa, Connect, etc. with ease. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install http-errors +``` + +## Example + +```js +var createError = require('http-errors') +var express = require('express') +var app = express() + +app.use(function (req, res, next) { + if (!req.user) return next(createError(401, 'Please login to view this page.')) + next() +}) +``` + +## API + +This is the current API, currently extracted from Koa and subject to change. + +All errors inherit from JavaScript `Error` and the exported `createError.HttpError`. + +### Error Properties + +- `expose` - can be used to signal if `message` should be sent to the client, + defaulting to `false` when `status` >= 500 +- `headers` - can be an object of header names to values to be sent to the + client, defaulting to `undefined`. When defined, the key names should all + be lower-cased +- `message` - the traditional error message, which should be kept short and all + single line +- `status` - the status code of the error, mirroring `statusCode` for general + compatibility +- `statusCode` - the status code of the error, defaulting to `500` + +### createError([status], [message], [properties]) + + + +```js +var err = createError(404, 'This video does not exist!') +``` + +- `status: 500` - the status code as a number +- `message` - the message of the error, defaulting to node's text for that status code. +- `properties` - custom properties to attach to the object + +### new createError\[code || name\](\[msg]\)) + + + +```js +var err = new createError.NotFound() +``` + +- `code` - the status code as a number +- `name` - the name of the error as a "bumpy case", i.e. `NotFound` or `InternalServerError`. + +#### List of all constructors + +|Status Code|Constructor Name | +|-----------|-----------------------------| +|400 |BadRequest | +|401 |Unauthorized | +|402 |PaymentRequired | +|403 |Forbidden | +|404 |NotFound | +|405 |MethodNotAllowed | +|406 |NotAcceptable | +|407 |ProxyAuthenticationRequired | +|408 |RequestTimeout | +|409 |Conflict | +|410 |Gone | +|411 |LengthRequired | +|412 |PreconditionFailed | +|413 |PayloadTooLarge | +|414 |URITooLong | +|415 |UnsupportedMediaType | +|416 |RangeNotSatisfiable | +|417 |ExpectationFailed | +|418 |ImATeapot | +|421 |MisdirectedRequest | +|422 |UnprocessableEntity | +|423 |Locked | +|424 |FailedDependency | +|425 |UnorderedCollection | +|426 |UpgradeRequired | +|428 |PreconditionRequired | +|429 |TooManyRequests | +|431 |RequestHeaderFieldsTooLarge | +|451 |UnavailableForLegalReasons | +|500 |InternalServerError | +|501 |NotImplemented | +|502 |BadGateway | +|503 |ServiceUnavailable | +|504 |GatewayTimeout | +|505 |HTTPVersionNotSupported | +|506 |VariantAlsoNegotiates | +|507 |InsufficientStorage | +|508 |LoopDetected | +|509 |BandwidthLimitExceeded | +|510 |NotExtended | +|511 |NetworkAuthenticationRequired| + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/http-errors.svg +[npm-url]: https://npmjs.org/package/http-errors +[node-version-image]: https://img.shields.io/node/v/http-errors.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/http-errors.svg +[travis-url]: https://travis-ci.org/jshttp/http-errors +[coveralls-image]: https://img.shields.io/coveralls/jshttp/http-errors.svg +[coveralls-url]: https://coveralls.io/r/jshttp/http-errors +[downloads-image]: https://img.shields.io/npm/dm/http-errors.svg +[downloads-url]: https://npmjs.org/package/http-errors diff --git a/node_modules/raw-body/node_modules/http-errors/index.js b/node_modules/raw-body/node_modules/http-errors/index.js new file mode 100644 index 00000000..9509303e --- /dev/null +++ b/node_modules/raw-body/node_modules/http-errors/index.js @@ -0,0 +1,260 @@ +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var deprecate = require('depd')('http-errors') +var setPrototypeOf = require('setprototypeof') +var statuses = require('statuses') +var inherits = require('inherits') + +/** + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. + * + * @returns {Error} + * @public + */ + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue + } + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') + } + break + case 'object': + props = arg + break + } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] + } + } + + return err +} + +/** + * Create HTTP error abstract base class. + * @private + */ + +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } + + inherits(HttpError, Error) + + return HttpError +} + +/** + * Create a constructor for a client error. + * @private + */ + +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break + } + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) + + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} + +/** + * Convert a string of words to a JavaScript identifier. + * @private + */ + +function toIdentifier (str) { + return str.split(' ').map(function (token) { + return token.slice(0, 1).toUpperCase() + token.slice(1) + }).join('').replace(/[^ _0-9a-z]/gi, '') +} diff --git a/node_modules/raw-body/node_modules/http-errors/package.json b/node_modules/raw-body/node_modules/http-errors/package.json new file mode 100644 index 00000000..4d1b051b --- /dev/null +++ b/node_modules/raw-body/node_modules/http-errors/package.json @@ -0,0 +1,93 @@ +{ + "_args": [ + [ + "http-errors@1.6.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "http-errors@1.6.2", + "_id": "http-errors@1.6.2", + "_inBundle": false, + "_integrity": "sha1-CgAsyFcHGSp+eUbO7cERVfYOxzY=", + "_location": "/raw-body/http-errors", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "http-errors@1.6.2", + "name": "http-errors", + "escapedName": "http-errors", + "rawSpec": "1.6.2", + "saveSpec": null, + "fetchSpec": "1.6.2" + }, + "_requiredBy": [ + "/raw-body" + ], + "_resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.2.tgz", + "_spec": "1.6.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/jshttp/http-errors/issues" + }, + "contributors": [ + { + "name": "Alan Plum", + "email": "me@pluma.io" + }, + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + } + ], + "dependencies": { + "depd": "1.1.1", + "inherits": "2.0.3", + "setprototypeof": "1.0.3", + "statuses": ">= 1.3.1 < 2" + }, + "description": "Create HTTP error objects", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "index.js", + "HISTORY.md", + "LICENSE", + "README.md" + ], + "homepage": "https://github.com/jshttp/http-errors#readme", + "keywords": [ + "http", + "error" + ], + "license": "MIT", + "name": "http-errors", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/http-errors.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot" + }, + "version": "1.6.2" +} diff --git a/node_modules/raw-body/node_modules/setprototypeof/LICENSE b/node_modules/raw-body/node_modules/setprototypeof/LICENSE new file mode 100644 index 00000000..61afa2f1 --- /dev/null +++ b/node_modules/raw-body/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +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/raw-body/node_modules/setprototypeof/README.md b/node_modules/raw-body/node_modules/setprototypeof/README.md new file mode 100644 index 00000000..01d79470 --- /dev/null +++ b/node_modules/raw-body/node_modules/setprototypeof/README.md @@ -0,0 +1,21 @@ +# Polyfill for `Object.setPrototypeOf` + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof'); + +var obj = {}; +setPrototypeOf(obj, { + foo: function() { + return 'bar'; + } +}); +obj.foo(); // bar +``` diff --git a/node_modules/raw-body/node_modules/setprototypeof/index.js b/node_modules/raw-body/node_modules/setprototypeof/index.js new file mode 100644 index 00000000..93ea4176 --- /dev/null +++ b/node_modules/raw-body/node_modules/setprototypeof/index.js @@ -0,0 +1,15 @@ +module.exports = Object.setPrototypeOf || ({__proto__:[]} instanceof Array ? setProtoOf : mixinProperties); + +function setProtoOf(obj, proto) { + obj.__proto__ = proto; + return obj; +} + +function mixinProperties(obj, proto) { + for (var prop in proto) { + if (!obj.hasOwnProperty(prop)) { + obj[prop] = proto[prop]; + } + } + return obj; +} diff --git a/node_modules/raw-body/node_modules/setprototypeof/package.json b/node_modules/raw-body/node_modules/setprototypeof/package.json new file mode 100644 index 00000000..5914944f --- /dev/null +++ b/node_modules/raw-body/node_modules/setprototypeof/package.json @@ -0,0 +1,54 @@ +{ + "_args": [ + [ + "setprototypeof@1.0.3", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "setprototypeof@1.0.3", + "_id": "setprototypeof@1.0.3", + "_inBundle": false, + "_integrity": "sha1-ZlZ+NwQ+608E2RvWWMDL77VbjgQ=", + "_location": "/raw-body/setprototypeof", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "setprototypeof@1.0.3", + "name": "setprototypeof", + "escapedName": "setprototypeof", + "rawSpec": "1.0.3", + "saveSpec": null, + "fetchSpec": "1.0.3" + }, + "_requiredBy": [ + "/raw-body/http-errors" + ], + "_resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.0.3.tgz", + "_spec": "1.0.3", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Wes Todd" + }, + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "description": "A small polyfill for Object.setprototypeof", + "homepage": "https://github.com/wesleytodd/setprototypeof", + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "license": "ISC", + "main": "index.js", + "name": "setprototypeof", + "repository": { + "type": "git", + "url": "git+https://github.com/wesleytodd/setprototypeof.git" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "version": "1.0.3" +} diff --git a/node_modules/raw-body/package.json b/node_modules/raw-body/package.json new file mode 100644 index 00000000..63f02cf4 --- /dev/null +++ b/node_modules/raw-body/package.json @@ -0,0 +1,97 @@ +{ + "_args": [ + [ + "raw-body@2.3.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "raw-body@2.3.2", + "_id": "raw-body@2.3.2", + "_inBundle": false, + "_integrity": "sha1-vNYMd9Prk83gBQKVw/N5OJvIj4k=", + "_location": "/raw-body", + "_phantomChildren": { + "inherits": "2.0.3", + "statuses": "1.4.0" + }, + "_requested": { + "type": "version", + "registry": true, + "raw": "raw-body@2.3.2", + "name": "raw-body", + "escapedName": "raw-body", + "rawSpec": "2.3.2", + "saveSpec": null, + "fetchSpec": "2.3.2" + }, + "_requiredBy": [ + "/body-parser", + "/express-graphql" + ], + "_resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.3.2.tgz", + "_spec": "2.3.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + }, + "bugs": { + "url": "https://github.com/stream-utils/raw-body/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Raynos", + "email": "raynos2@gmail.com" + } + ], + "dependencies": { + "bytes": "3.0.0", + "http-errors": "1.6.2", + "iconv-lite": "0.4.19", + "unpipe": "1.0.0" + }, + "description": "Get and validate the raw body of a readable stream.", + "devDependencies": { + "bluebird": "3.5.0", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "readable-stream": "2.3.3", + "safe-buffer": "5.1.1" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.d.ts", + "index.js" + ], + "homepage": "https://github.com/stream-utils/raw-body#readme", + "license": "MIT", + "name": "raw-body", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/raw-body.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --trace-deprecation --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --trace-deprecation --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --trace-deprecation --reporter spec --check-leaks test/" + }, + "version": "2.3.2" +} diff --git a/node_modules/safe-buffer/.travis.yml b/node_modules/safe-buffer/.travis.yml new file mode 100644 index 00000000..7b20f28c --- /dev/null +++ b/node_modules/safe-buffer/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - 'node' + - '5' + - '4' + - '0.12' + - '0.10' diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 00000000..0c068cee --- /dev/null +++ b/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/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 00000000..e9a81afd --- /dev/null +++ b/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/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 00000000..22438dab --- /dev/null +++ b/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/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 00000000..9b975bc7 --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,65 @@ +{ + "_args": [ + [ + "safe-buffer@5.1.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "safe-buffer@5.1.1", + "_id": "safe-buffer@5.1.1", + "_inBundle": false, + "_integrity": "sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "safe-buffer@5.1.1", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "5.1.1", + "saveSpec": null, + "fetchSpec": "5.1.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.1.tgz", + "_spec": "5.1.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^4.0.0", + "zuul": "^3.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", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "version": "5.1.1" +} diff --git a/node_modules/safe-buffer/test.js b/node_modules/safe-buffer/test.js new file mode 100644 index 00000000..4925059c --- /dev/null +++ b/node_modules/safe-buffer/test.js @@ -0,0 +1,101 @@ +/* eslint-disable node/no-deprecated-api */ + +var test = require('tape') +var SafeBuffer = require('./').Buffer + +test('new SafeBuffer(value) works just like Buffer', function (t) { + t.deepEqual(new SafeBuffer('hey'), new Buffer('hey')) + t.deepEqual(new SafeBuffer('hey', 'utf8'), new Buffer('hey', 'utf8')) + t.deepEqual(new SafeBuffer('686579', 'hex'), new Buffer('686579', 'hex')) + t.deepEqual(new SafeBuffer([1, 2, 3]), new Buffer([1, 2, 3])) + t.deepEqual(new SafeBuffer(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) + + t.equal(typeof SafeBuffer.isBuffer, 'function') + t.equal(SafeBuffer.isBuffer(new SafeBuffer('hey')), true) + t.equal(Buffer.isBuffer(new SafeBuffer('hey')), true) + t.notOk(SafeBuffer.isBuffer({})) + + t.end() +}) + +test('SafeBuffer.from(value) converts to a Buffer', function (t) { + t.deepEqual(SafeBuffer.from('hey'), new Buffer('hey')) + t.deepEqual(SafeBuffer.from('hey', 'utf8'), new Buffer('hey', 'utf8')) + t.deepEqual(SafeBuffer.from('686579', 'hex'), new Buffer('686579', 'hex')) + t.deepEqual(SafeBuffer.from([1, 2, 3]), new Buffer([1, 2, 3])) + t.deepEqual(SafeBuffer.from(new Uint8Array([1, 2, 3])), new Buffer(new Uint8Array([1, 2, 3]))) + + t.end() +}) + +test('SafeBuffer.alloc(number) returns zeroed-out memory', function (t) { + for (var i = 0; i < 10; i++) { + var expected1 = new Buffer(1000) + expected1.fill(0) + t.deepEqual(SafeBuffer.alloc(1000), expected1) + + var expected2 = new Buffer(1000 * 1000) + expected2.fill(0) + t.deepEqual(SafeBuffer.alloc(1000 * 1000), expected2) + } + t.end() +}) + +test('SafeBuffer.allocUnsafe(number)', function (t) { + var buf = SafeBuffer.allocUnsafe(100) // unitialized memory + t.equal(buf.length, 100) + t.equal(SafeBuffer.isBuffer(buf), true) + t.equal(Buffer.isBuffer(buf), true) + t.end() +}) + +test('SafeBuffer.from() throws with number types', function (t) { + t.plan(5) + t.throws(function () { + SafeBuffer.from(0) + }) + t.throws(function () { + SafeBuffer.from(-1) + }) + t.throws(function () { + SafeBuffer.from(NaN) + }) + t.throws(function () { + SafeBuffer.from(Infinity) + }) + t.throws(function () { + SafeBuffer.from(99) + }) +}) + +test('SafeBuffer.allocUnsafe() throws with non-number types', function (t) { + t.plan(4) + t.throws(function () { + SafeBuffer.allocUnsafe('hey') + }) + t.throws(function () { + SafeBuffer.allocUnsafe('hey', 'utf8') + }) + t.throws(function () { + SafeBuffer.allocUnsafe([1, 2, 3]) + }) + t.throws(function () { + SafeBuffer.allocUnsafe({}) + }) +}) + +test('SafeBuffer.alloc() throws with non-number types', function (t) { + t.plan(4) + t.throws(function () { + SafeBuffer.alloc('hey') + }) + t.throws(function () { + SafeBuffer.alloc('hey', 'utf8') + }) + t.throws(function () { + SafeBuffer.alloc([1, 2, 3]) + }) + t.throws(function () { + SafeBuffer.alloc({}) + }) +}) diff --git a/node_modules/send/HISTORY.md b/node_modules/send/HISTORY.md new file mode 100644 index 00000000..88ab9304 --- /dev/null +++ b/node_modules/send/HISTORY.md @@ -0,0 +1,462 @@ +0.16.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in default error & redirects + * deps: depd@~1.1.2 + - perf: remove argument reassignment + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: statuses@~1.4.0 + +0.16.1 / 2017-09-29 +=================== + + * Fix regression in edge-case behavior for empty `path` + +0.16.0 / 2017-09-27 +=================== + + * Add `immutable` option + * Fix missing `` in default error & redirects + * Use instance methods on steam to check for listeners + * deps: mime@1.4.1 + - Add 70 new types for file extensions + - Set charset as "UTF-8" for .js and .json + * perf: improve path validation speed + +0.15.6 / 2017-09-22 +=================== + + * deps: debug@2.6.9 + * perf: improve `If-Match` token parsing + +0.15.5 / 2017-09-20 +=================== + + * deps: etag@~1.8.1 + - perf: replace regular expression with substring + * deps: fresh@0.5.2 + - Fix handling of modified headers with invalid dates + - perf: improve ETag match loop + - perf: improve `If-None-Match` token parsing + +0.15.4 / 2017-08-05 +=================== + + * deps: debug@2.6.8 + * deps: depd@~1.1.1 + - Remove unnecessary `Buffer` loading + * deps: http-errors@~1.6.2 + - deps: depd@1.1.1 + +0.15.3 / 2017-05-16 +=================== + + * deps: debug@2.6.7 + - deps: ms@2.0.0 + * deps: ms@2.0.0 + +0.15.2 / 2017-04-26 +=================== + + * deps: debug@2.6.4 + - Fix `DEBUG_MAX_ARRAY_LENGTH` + - deps: ms@0.7.3 + * deps: ms@1.0.0 + +0.15.1 / 2017-03-04 +=================== + + * Fix issue when `Date.parse` does not return `NaN` on invalid date + * Fix strict violation in broken environments + +0.15.0 / 2017-02-25 +=================== + + * Support `If-Match` and `If-Unmodified-Since` headers + * Add `res` and `path` arguments to `directory` event + * Remove usage of `res._headers` private field + - Improves compatibility with Node.js 8 nightly + * Send complete HTML document in redirect & error responses + * Set default CSP header in redirect & error responses + * Use `res.getHeaderNames()` when available + * Use `res.headersSent` when available + * deps: debug@2.6.1 + - Allow colors in workers + - Deprecated `DEBUG_FD` environment variable set to `3` or higher + - Fix error when running under React Native + - Use same color for same namespace + - deps: ms@0.7.2 + * deps: etag@~1.8.0 + * deps: fresh@0.5.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - perf: delay reading header values until needed + - perf: enable strict mode + - perf: hoist regular expressions + - perf: remove duplicate conditional + - perf: remove unnecessary boolean coercions + - perf: skip checking modified time if ETag check failed + - perf: skip parsing `If-None-Match` when no `ETag` header + - perf: use `Date.parse` instead of `new Date` + * deps: http-errors@~1.6.1 + - Make `message` property enumerable for `HttpError`s + - deps: setprototypeof@1.0.3 + +0.14.2 / 2017-01-23 +=================== + + * deps: http-errors@~1.5.1 + - deps: inherits@2.0.3 + - deps: setprototypeof@1.0.2 + - deps: statuses@'>= 1.3.1 < 2' + * deps: ms@0.7.2 + * deps: statuses@~1.3.1 + +0.14.1 / 2016-06-09 +=================== + + * Fix redirect error when `path` contains raw non-URL characters + * Fix redirect when `path` starts with multiple forward slashes + +0.14.0 / 2016-06-06 +=================== + + * Add `acceptRanges` option + * Add `cacheControl` option + * Attempt to combine multiple ranges into single range + * Correctly inherit from `Stream` class + * Fix `Content-Range` header in 416 responses when using `start`/`end` options + * Fix `Content-Range` header missing from default 416 responses + * Ignore non-byte `Range` headers + * deps: http-errors@~1.5.0 + - Add `HttpError` export, for `err instanceof createError.HttpError` + - Support new code `421 Misdirected Request` + - Use `setprototypeof` module to replace `__proto__` setting + - deps: inherits@2.0.1 + - deps: statuses@'>= 1.3.0 < 2' + - perf: enable strict mode + * deps: range-parser@~1.2.0 + - Fix incorrectly returning -1 when there is at least one valid range + - perf: remove internal function + * deps: statuses@~1.3.0 + - Add `421 Misdirected Request` + - perf: enable strict mode + * perf: remove argument reassignment + +0.13.2 / 2016-03-05 +=================== + + * Fix invalid `Content-Type` header when `send.mime.default_type` unset + +0.13.1 / 2016-01-16 +=================== + + * deps: depd@~1.1.0 + - Support web browser loading + - perf: enable strict mode + * deps: destroy@~1.0.4 + - perf: enable strict mode + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: range-parser@~1.0.3 + - perf: enable strict mode + +0.13.0 / 2015-06-16 +=================== + + * Allow Node.js HTTP server to set `Date` response header + * Fix incorrectly removing `Content-Location` on 304 response + * Improve the default redirect response headers + * Send appropriate headers on default error response + * Use `http-errors` for standard emitted errors + * Use `statuses` instead of `http` module for status messages + * deps: escape-html@1.0.2 + * deps: etag@~1.7.0 + - Improve stat performance by removing hashing + * deps: fresh@0.3.0 + - Add weak `ETag` matching support + * deps: on-finished@~2.3.0 + - Add defined behavior for HTTP `CONNECT` requests + - Add defined behavior for HTTP `Upgrade` requests + - deps: ee-first@1.1.1 + * perf: enable strict mode + * perf: remove unnecessary array allocations + +0.12.3 / 2015-05-13 +=================== + + * deps: debug@~2.2.0 + - deps: ms@0.7.1 + * deps: depd@~1.0.1 + * deps: etag@~1.6.0 + - Improve support for JXcore + - Support "fake" stats objects in environments without `fs` + * deps: ms@0.7.1 + - Prevent extraordinarily long inputs + * deps: on-finished@~2.2.1 + +0.12.2 / 2015-03-13 +=================== + + * Throw errors early for invalid `extensions` or `index` options + * deps: debug@~2.1.3 + - Fix high intensity foreground color for bold + - deps: ms@0.7.0 + +0.12.1 / 2015-02-17 +=================== + + * Fix regression sending zero-length files + +0.12.0 / 2015-02-16 +=================== + + * Always read the stat size from the file + * Fix mutating passed-in `options` + * deps: mime@1.3.4 + +0.11.1 / 2015-01-20 +=================== + + * Fix `root` path disclosure + +0.11.0 / 2015-01-05 +=================== + + * deps: debug@~2.1.1 + * deps: etag@~1.5.1 + - deps: crc@3.2.1 + * deps: ms@0.7.0 + - Add `milliseconds` + - Add `msecs` + - Add `secs` + - Add `mins` + - Add `hrs` + - Add `yrs` + * deps: on-finished@~2.2.0 + +0.10.1 / 2014-10-22 +=================== + + * deps: on-finished@~2.1.1 + - Fix handling of pipelined requests + +0.10.0 / 2014-10-15 +=================== + + * deps: debug@~2.1.0 + - Implement `DEBUG_FD` env variable support + * deps: depd@~1.0.0 + * deps: etag@~1.5.0 + - Improve string performance + - Slightly improve speed for weak ETags over 1KB + +0.9.3 / 2014-09-24 +================== + + * deps: etag@~1.4.0 + - Support "fake" stats objects + +0.9.2 / 2014-09-15 +================== + + * deps: depd@0.4.5 + * deps: etag@~1.3.1 + * deps: range-parser@~1.0.2 + +0.9.1 / 2014-09-07 +================== + + * deps: fresh@0.2.4 + +0.9.0 / 2014-09-07 +================== + + * Add `lastModified` option + * Use `etag` to generate `ETag` header + * deps: debug@~2.0.0 + +0.8.5 / 2014-09-04 +================== + + * Fix malicious path detection for empty string path + +0.8.4 / 2014-09-04 +================== + + * Fix a path traversal issue when using `root` + +0.8.3 / 2014-08-16 +================== + + * deps: destroy@1.0.3 + - renamed from dethroy + * deps: on-finished@2.1.0 + +0.8.2 / 2014-08-14 +================== + + * Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + * deps: dethroy@1.0.2 + +0.8.1 / 2014-08-05 +================== + + * Fix `extensions` behavior when file already has extension + +0.8.0 / 2014-08-05 +================== + + * Add `extensions` option + +0.7.4 / 2014-08-04 +================== + + * Fix serving index files without root dir + +0.7.3 / 2014-07-29 +================== + + * Fix incorrect 403 on Windows and Node.js 0.11 + +0.7.2 / 2014-07-27 +================== + + * deps: depd@0.4.4 + - Work-around v8 generating empty stack traces + +0.7.1 / 2014-07-26 +================== + + * deps: depd@0.4.3 + - Fix exception when global `Error.stackTraceLimit` is too low + +0.7.0 / 2014-07-20 +================== + + * Deprecate `hidden` option; use `dotfiles` option + * Add `dotfiles` option + * deps: debug@1.0.4 + * deps: depd@0.4.2 + - Add `TRACE_DEPRECATION` environment variable + - Remove non-standard grey color from color output + - Support `--no-deprecation` argument + - Support `--trace-deprecation` argument + +0.6.0 / 2014-07-11 +================== + + * Deprecate `from` option; use `root` option + * Deprecate `send.etag()` -- use `etag` in `options` + * Deprecate `send.hidden()` -- use `hidden` in `options` + * Deprecate `send.index()` -- use `index` in `options` + * Deprecate `send.maxage()` -- use `maxAge` in `options` + * Deprecate `send.root()` -- use `root` in `options` + * Cap `maxAge` value to 1 year + * deps: debug@1.0.3 + - Add support for multiple wildcards in namespaces + +0.5.0 / 2014-06-28 +================== + + * Accept string for `maxAge` (converted by `ms`) + * Add `headers` event + * Include link in default redirect response + * Use `EventEmitter.listenerCount` to count listeners + +0.4.3 / 2014-06-11 +================== + + * Do not throw un-catchable error on file open race condition + * Use `escape-html` for HTML escaping + * deps: debug@1.0.2 + - fix some debugging output colors on node.js 0.8 + * deps: finished@1.2.2 + * deps: fresh@0.2.2 + +0.4.2 / 2014-06-09 +================== + + * fix "event emitter leak" warnings + * deps: debug@1.0.1 + * deps: finished@1.2.1 + +0.4.1 / 2014-06-02 +================== + + * Send `max-age` in `Cache-Control` in correct format + +0.4.0 / 2014-05-27 +================== + + * Calculate ETag with md5 for reduced collisions + * Fix wrong behavior when index file matches directory + * Ignore stream errors after request ends + - Goodbye `EBADF, read` + * Skip directories in index file search + * deps: debug@0.8.1 + +0.3.0 / 2014-04-24 +================== + + * Fix sending files with dots without root set + * Coerce option types + * Accept API options in options object + * Set etags to "weak" + * Include file path in etag + * Make "Can't set headers after they are sent." catchable + * Send full entity-body for multi range requests + * Default directory access to 403 when index disabled + * Support multiple index paths + * Support "If-Range" header + * Control whether to generate etags + * deps: mime@1.2.11 + +0.2.0 / 2014-01-29 +================== + + * update range-parser and fresh + +0.1.4 / 2013-08-11 +================== + + * update fresh + +0.1.3 / 2013-07-08 +================== + + * Revert "Fix fd leak" + +0.1.2 / 2013-07-03 +================== + + * Fix fd leak + +0.1.0 / 2012-08-25 +================== + + * add options parameter to send() that is passed to fs.createReadStream() [kanongil] + +0.0.4 / 2012-08-16 +================== + + * allow custom "Accept-Ranges" definition + +0.0.3 / 2012-07-16 +================== + + * fix normalization of the root directory. Closes #3 + +0.0.2 / 2012-07-09 +================== + + * add passing of req explicitly for now (YUCK) + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/send/LICENSE b/node_modules/send/LICENSE new file mode 100644 index 00000000..4aa69e83 --- /dev/null +++ b/node_modules/send/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2012 TJ Holowaychuk +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/send/README.md b/node_modules/send/README.md new file mode 100644 index 00000000..1a244035 --- /dev/null +++ b/node_modules/send/README.md @@ -0,0 +1,306 @@ +# send + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Send is a library for streaming files from the file system as a http response +supporting partial responses (Ranges), conditional-GET negotiation (If-Match, +If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, +and granular events which may be leveraged to take appropriate actions in your +application or framework. + +Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static). + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```bash +$ npm install send +``` + +## API + + + +```js +var send = require('send') +``` + +### send(req, path, [options]) + +Create a new `SendStream` for the given path to send to a `res`. The `req` is +the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded, +not the actual file-system path). + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + +Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Send a 403 for any request for a dotfile. + - `'ignore'` Pretend like the dotfile does not exist and 404. + +The default value is _similar_ to `'ignore'`, with the exception that +this default will not ignore the files within a directory that begins +with a dot, for backward-compatibility. + +##### end + +Byte offset at which the stream ends, defaults to the length of the file +minus 1. The end is inclusive in the stream, meaning `end: 3` will include +the 4th byte in the stream. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +If a given file doesn't exist, try appending one of the given extensions, +in the given order. By default, this is disabled (set to `false`). An +example value that will serve extension-less HTML files: `['html', 'htm']`. +This is skipped if the requested file already has an extension. + +##### immutable + +Enable or diable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default send supports "index.html" files, to disable this +set `false` or to supply a new index pass a string or an array +in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. +This can also be a string accepted by the +[ms](https://www.npmjs.org/package/ms#readme) module. + +##### root + +Serve files relative to `path`. + +##### start + +Byte offset at which the stream starts, defaults to 0. The start is inclusive, +meaning `start: 2` will include the 3rd byte in the stream. + +#### Events + +The `SendStream` is an event emitter and will emit the following events: + + - `error` an error occurred `(err)` + - `directory` a directory was requested `(res, path)` + - `file` a file was requested `(path, stat)` + - `headers` the headers are about to be set on a file `(res, path, stat)` + - `stream` file streaming has started `(stream)` + - `end` streaming has completed + +#### .pipe + +The `pipe` method is used to pipe the response into the Node.js HTTP response +object, typically `send(req, path, options).pipe(res)`. + +### .mime + +The `mime` export is the global instance of of the +[`mime` npm module](https://www.npmjs.com/package/mime). + +This is used to configure the MIME types that are associated with file extensions +as well as other options for how to resolve the MIME type of a file (like the +default type to use for an unknown file extension). + +## Error-handling + +By default when no `error` listeners are present an automatic response will be +made, otherwise you have full control over the response, aka you may show a 5xx +page etc. + +## Caching + +It does _not_ perform internal caching, you should use a reverse proxy cache +such as Varnish for this, or those fancy things called CDNs. If your +application is small enough that it would benefit from single-node memory +caching, it's small enough that it does not need caching at all ;). + +## Debugging + +To enable `debug()` instrumentation output export __DEBUG__: + +``` +$ DEBUG=send node app +``` + +## Running tests + +``` +$ npm install +$ npm test +``` + +## Examples + +### Small example + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname).pipe(res) +}) + +server.listen(3000) +``` + +### Custom file types + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +// Default unknown types to text/plain +send.mime.default_type = 'text/plain' + +// Add a custom type +send.mime.define({ + 'application/x-my-type': ['x-mt', 'x-mtt'] +}) + +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname).pipe(res) +}) + +server.listen(3000) +``` + +### Custom directory index view + +This is a example of serving up a structure of directories with a +custom function to render a listing of a directory. + +```js +var http = require('http') +var fs = require('fs') +var parseUrl = require('parseurl') +var send = require('send') + +// Transfer arbitrary files from within /www/example.com/public/* +// with a custom handler for directory listing +var server = http.createServer(function onRequest (req, res) { + send(req, parseUrl(req).pathname, {index: false, root: '/www/example.com/public'}) + .once('directory', directory) + .pipe(res) +}) + +server.listen(3000) + +// Custom directory handler +function directory (res, path) { + var stream = this + + // redirect to trailing slash for consistent url + if (!stream.hasTrailingSlash()) { + return stream.redirect(path) + } + + // get directory list + fs.readdir(path, function onReaddir (err, list) { + if (err) return stream.error(err) + + // render an index for the directory + res.setHeader('Content-Type', 'text/plain; charset=UTF-8') + res.end(list.join('\n') + '\n') + }) +} +``` + +### Serving from a root directory with custom error-handling + +```js +var http = require('http') +var parseUrl = require('parseurl') +var send = require('send') + +var server = http.createServer(function onRequest (req, res) { + // your custom error-handling logic: + function error (err) { + res.statusCode = err.status || 500 + res.end(err.message) + } + + // your custom headers + function headers (res, path, stat) { + // serve all files for download + res.setHeader('Content-Disposition', 'attachment') + } + + // your custom directory handling logic: + function redirect () { + res.statusCode = 301 + res.setHeader('Location', req.url + '/') + res.end('Redirecting to ' + req.url + '/') + } + + // transfer arbitrary files from within + // /www/example.com/public/* + send(req, parseUrl(req).pathname, {root: '/www/example.com/public'}) + .on('error', error) + .on('directory', redirect) + .on('headers', headers) + .pipe(res) +}) + +server.listen(3000) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/send.svg +[npm-url]: https://npmjs.org/package/send +[travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux +[travis-url]: https://travis-ci.org/pillarjs/send +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/send +[coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg +[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master +[downloads-image]: https://img.shields.io/npm/dm/send.svg +[downloads-url]: https://npmjs.org/package/send diff --git a/node_modules/send/index.js b/node_modules/send/index.js new file mode 100644 index 00000000..f297c4c5 --- /dev/null +++ b/node_modules/send/index.js @@ -0,0 +1,1130 @@ +/*! + * send + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var createError = require('http-errors') +var debug = require('debug')('send') +var deprecate = require('depd')('send') +var destroy = require('destroy') +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var etag = require('etag') +var fresh = require('fresh') +var fs = require('fs') +var mime = require('mime') +var ms = require('ms') +var onFinished = require('on-finished') +var parseRange = require('range-parser') +var path = require('path') +var statuses = require('statuses') +var Stream = require('stream') +var util = require('util') + +/** + * Path function references. + * @private + */ + +var extname = path.extname +var join = path.join +var normalize = path.normalize +var resolve = path.resolve +var sep = path.sep + +/** + * Regular expression for identifying a bytes Range header. + * @private + */ + +var BYTES_RANGE_REGEXP = /^ *bytes=/ + +/** + * Maximum value allowed for the max age. + * @private + */ + +var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year + +/** + * Regular expression to match a path with a directory up component. + * @private + */ + +var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/ + +/** + * Module exports. + * @public + */ + +module.exports = send +module.exports.mime = mime + +/** + * Return a `SendStream` for `req` and `path`. + * + * @param {object} req + * @param {string} path + * @param {object} [options] + * @return {SendStream} + * @public + */ + +function send (req, path, options) { + return new SendStream(req, path, options) +} + +/** + * Initialize a `SendStream` with the given `path`. + * + * @param {Request} req + * @param {String} path + * @param {object} [options] + * @private + */ + +function SendStream (req, path, options) { + Stream.call(this) + + var opts = options || {} + + this.options = opts + this.path = path + this.req = req + + this._acceptRanges = opts.acceptRanges !== undefined + ? Boolean(opts.acceptRanges) + : true + + this._cacheControl = opts.cacheControl !== undefined + ? Boolean(opts.cacheControl) + : true + + this._etag = opts.etag !== undefined + ? Boolean(opts.etag) + : true + + this._dotfiles = opts.dotfiles !== undefined + ? opts.dotfiles + : 'ignore' + + if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') { + throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"') + } + + this._hidden = Boolean(opts.hidden) + + if (opts.hidden !== undefined) { + deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead') + } + + // legacy support + if (opts.dotfiles === undefined) { + this._dotfiles = undefined + } + + this._extensions = opts.extensions !== undefined + ? normalizeList(opts.extensions, 'extensions option') + : [] + + this._immutable = opts.immutable !== undefined + ? Boolean(opts.immutable) + : false + + this._index = opts.index !== undefined + ? normalizeList(opts.index, 'index option') + : ['index.html'] + + this._lastModified = opts.lastModified !== undefined + ? Boolean(opts.lastModified) + : true + + this._maxage = opts.maxAge || opts.maxage + this._maxage = typeof this._maxage === 'string' + ? ms(this._maxage) + : Number(this._maxage) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + + this._root = opts.root + ? resolve(opts.root) + : null + + if (!this._root && opts.from) { + this.from(opts.from) + } +} + +/** + * Inherits from `Stream`. + */ + +util.inherits(SendStream, Stream) + +/** + * Enable or disable etag generation. + * + * @param {Boolean} val + * @return {SendStream} + * @api public + */ + +SendStream.prototype.etag = deprecate.function(function etag (val) { + this._etag = Boolean(val) + debug('etag %s', this._etag) + return this +}, 'send.etag: pass etag as option') + +/** + * Enable or disable "hidden" (dot) files. + * + * @param {Boolean} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.hidden = deprecate.function(function hidden (val) { + this._hidden = Boolean(val) + this._dotfiles = undefined + debug('hidden %s', this._hidden) + return this +}, 'send.hidden: use dotfiles option') + +/** + * Set index `paths`, set to a falsy + * value to disable index support. + * + * @param {String|Boolean|Array} paths + * @return {SendStream} + * @api public + */ + +SendStream.prototype.index = deprecate.function(function index (paths) { + var index = !paths ? [] : normalizeList(paths, 'paths argument') + debug('index %o', paths) + this._index = index + return this +}, 'send.index: pass index as option') + +/** + * Set root `path`. + * + * @param {String} path + * @return {SendStream} + * @api public + */ + +SendStream.prototype.root = function root (path) { + this._root = resolve(String(path)) + debug('root %s', this._root) + return this +} + +SendStream.prototype.from = deprecate.function(SendStream.prototype.root, + 'send.from: pass root as option') + +SendStream.prototype.root = deprecate.function(SendStream.prototype.root, + 'send.root: pass root as option') + +/** + * Set max-age to `maxAge`. + * + * @param {Number} maxAge + * @return {SendStream} + * @api public + */ + +SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) { + this._maxage = typeof maxAge === 'string' + ? ms(maxAge) + : Number(maxAge) + this._maxage = !isNaN(this._maxage) + ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) + : 0 + debug('max-age %d', this._maxage) + return this +}, 'send.maxage: pass maxAge as option') + +/** + * Emit error with `status`. + * + * @param {number} status + * @param {Error} [err] + * @private + */ + +SendStream.prototype.error = function error (status, err) { + // emit if listeners instead of responding + if (hasListeners(this, 'error')) { + return this.emit('error', createError(status, err, { + expose: false + })) + } + + var res = this.res + var msg = statuses[status] || String(status) + var doc = createHtmlDocument('Error', escapeHtml(msg)) + + // clear existing headers + clearHeaders(res) + + // add error headers + if (err && err.headers) { + setHeaders(res, err.headers) + } + + // send basic response + res.statusCode = status + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'self'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.end(doc) +} + +/** + * Check if the pathname ends with "/". + * + * @return {boolean} + * @private + */ + +SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () { + return this.path[this.path.length - 1] === '/' +} + +/** + * Check if this is a conditional GET request. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isConditionalGET = function isConditionalGET () { + return this.req.headers['if-match'] || + this.req.headers['if-unmodified-since'] || + this.req.headers['if-none-match'] || + this.req.headers['if-modified-since'] +} + +/** + * Check if the request preconditions failed. + * + * @return {boolean} + * @private + */ + +SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () { + var req = this.req + var res = this.res + + // if-match + var match = req.headers['if-match'] + if (match) { + var etag = res.getHeader('ETag') + return !etag || (match !== '*' && parseTokenList(match).every(function (match) { + return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag + })) + } + + // if-unmodified-since + var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since']) + if (!isNaN(unmodifiedSince)) { + var lastModified = parseHttpDate(res.getHeader('Last-Modified')) + return isNaN(lastModified) || lastModified > unmodifiedSince + } + + return false +} + +/** + * Strip content-* header fields. + * + * @private + */ + +SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () { + var res = this.res + var headers = getHeaderNames(res) + + for (var i = 0; i < headers.length; i++) { + var header = headers[i] + if (header.substr(0, 8) === 'content-' && header !== 'content-location') { + res.removeHeader(header) + } + } +} + +/** + * Respond with 304 not modified. + * + * @api private + */ + +SendStream.prototype.notModified = function notModified () { + var res = this.res + debug('not modified') + this.removeContentHeaderFields() + res.statusCode = 304 + res.end() +} + +/** + * Raise error that headers already sent. + * + * @api private + */ + +SendStream.prototype.headersAlreadySent = function headersAlreadySent () { + var err = new Error('Can\'t set headers after they are sent.') + debug('headers already sent') + this.error(500, err) +} + +/** + * Check if the request is cacheable, aka + * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isCachable = function isCachable () { + var statusCode = this.res.statusCode + return (statusCode >= 200 && statusCode < 300) || + statusCode === 304 +} + +/** + * Handle stat() error. + * + * @param {Error} error + * @private + */ + +SendStream.prototype.onStatError = function onStatError (error) { + switch (error.code) { + case 'ENAMETOOLONG': + case 'ENOENT': + case 'ENOTDIR': + this.error(404, error) + break + default: + this.error(500, error) + break + } +} + +/** + * Check if the cache is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isFresh = function isFresh () { + return fresh(this.req.headers, { + 'etag': this.res.getHeader('ETag'), + 'last-modified': this.res.getHeader('Last-Modified') + }) +} + +/** + * Check if the range is fresh. + * + * @return {Boolean} + * @api private + */ + +SendStream.prototype.isRangeFresh = function isRangeFresh () { + var ifRange = this.req.headers['if-range'] + + if (!ifRange) { + return true + } + + // if-range as etag + if (ifRange.indexOf('"') !== -1) { + var etag = this.res.getHeader('ETag') + return Boolean(etag && ifRange.indexOf(etag) !== -1) + } + + // if-range as modified date + var lastModified = this.res.getHeader('Last-Modified') + return parseHttpDate(lastModified) <= parseHttpDate(ifRange) +} + +/** + * Redirect to path. + * + * @param {string} path + * @private + */ + +SendStream.prototype.redirect = function redirect (path) { + var res = this.res + + if (hasListeners(this, 'directory')) { + this.emit('directory', res, path) + return + } + + if (this.hasTrailingSlash()) { + this.error(403) + return + } + + var loc = encodeUrl(collapseLeadingSlashes(this.path + '/')) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + + escapeHtml(loc) + '') + + // redirect + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'self'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) +} + +/** + * Pipe to `res. + * + * @param {Stream} res + * @return {Stream} res + * @api public + */ + +SendStream.prototype.pipe = function pipe (res) { + // root path + var root = this._root + + // references + this.res = res + + // decode the path + var path = decode(this.path) + if (path === -1) { + this.error(400) + return res + } + + // null byte(s) + if (~path.indexOf('\0')) { + this.error(400) + return res + } + + var parts + if (root !== null) { + // normalize + if (path) { + path = normalize('.' + sep + path) + } + + // malicious path + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = path.split(sep) + + // join / normalize from optional root dir + path = normalize(join(root, path)) + root = normalize(root + sep) + } else { + // ".." is malicious without "root" + if (UP_PATH_REGEXP.test(path)) { + debug('malicious path "%s"', path) + this.error(403) + return res + } + + // explode path parts + parts = normalize(path).split(sep) + + // resolve the path + path = resolve(path) + } + + // dotfile handling + if (containsDotFile(parts)) { + var access = this._dotfiles + + // legacy support + if (access === undefined) { + access = parts[parts.length - 1][0] === '.' + ? (this._hidden ? 'allow' : 'ignore') + : 'allow' + } + + debug('%s dotfile "%s"', access, path) + switch (access) { + case 'allow': + break + case 'deny': + this.error(403) + return res + case 'ignore': + default: + this.error(404) + return res + } + } + + // index file support + if (this._index.length && this.hasTrailingSlash()) { + this.sendIndex(path) + return res + } + + this.sendFile(path) + return res +} + +/** + * Transfer `path`. + * + * @param {String} path + * @api public + */ + +SendStream.prototype.send = function send (path, stat) { + var len = stat.size + var options = this.options + var opts = {} + var res = this.res + var req = this.req + var ranges = req.headers.range + var offset = options.start || 0 + + if (headersSent(res)) { + // impossible to send now + this.headersAlreadySent() + return + } + + debug('pipe "%s"', path) + + // set header fields + this.setHeader(path, stat) + + // set content-type + this.type(path) + + // conditional GET support + if (this.isConditionalGET()) { + if (this.isPreconditionFailure()) { + this.error(412) + return + } + + if (this.isCachable() && this.isFresh()) { + this.notModified() + return + } + } + + // adjust len to start/end options + len = Math.max(0, len - offset) + if (options.end !== undefined) { + var bytes = options.end - offset + 1 + if (len > bytes) len = bytes + } + + // Range support + if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) { + // parse + ranges = parseRange(len, ranges, { + combine: true + }) + + // If-Range support + if (!this.isRangeFresh()) { + debug('range stale') + ranges = -2 + } + + // unsatisfiable + if (ranges === -1) { + debug('range unsatisfiable') + + // Content-Range + res.setHeader('Content-Range', contentRange('bytes', len)) + + // 416 Requested Range Not Satisfiable + return this.error(416, { + headers: {'Content-Range': res.getHeader('Content-Range')} + }) + } + + // valid (syntactically invalid/multiple ranges are treated as a regular response) + if (ranges !== -2 && ranges.length === 1) { + debug('range %j', ranges) + + // Content-Range + res.statusCode = 206 + res.setHeader('Content-Range', contentRange('bytes', len, ranges[0])) + + // adjust for requested range + offset += ranges[0].start + len = ranges[0].end - ranges[0].start + 1 + } + } + + // clone options + for (var prop in options) { + opts[prop] = options[prop] + } + + // set read options + opts.start = offset + opts.end = Math.max(offset, offset + len - 1) + + // content-length + res.setHeader('Content-Length', len) + + // HEAD support + if (req.method === 'HEAD') { + res.end() + return + } + + this.stream(path, opts) +} + +/** + * Transfer file for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendFile = function sendFile (path) { + var i = 0 + var self = this + + debug('stat "%s"', path) + fs.stat(path, function onstat (err, stat) { + if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) { + // not found, check extensions + return next(err) + } + if (err) return self.onStatError(err) + if (stat.isDirectory()) return self.redirect(path) + self.emit('file', path, stat) + self.send(path, stat) + }) + + function next (err) { + if (self._extensions.length <= i) { + return err + ? self.onStatError(err) + : self.error(404) + } + + var p = path + '.' + self._extensions[i++] + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } +} + +/** + * Transfer index for `path`. + * + * @param {String} path + * @api private + */ +SendStream.prototype.sendIndex = function sendIndex (path) { + var i = -1 + var self = this + + function next (err) { + if (++i >= self._index.length) { + if (err) return self.onStatError(err) + return self.error(404) + } + + var p = join(path, self._index[i]) + + debug('stat "%s"', p) + fs.stat(p, function (err, stat) { + if (err) return next(err) + if (stat.isDirectory()) return next() + self.emit('file', p, stat) + self.send(p, stat) + }) + } + + next() +} + +/** + * Stream `path` to the response. + * + * @param {String} path + * @param {Object} options + * @api private + */ + +SendStream.prototype.stream = function stream (path, options) { + // TODO: this is all lame, refactor meeee + var finished = false + var self = this + var res = this.res + + // pipe + var stream = fs.createReadStream(path, options) + this.emit('stream', stream) + stream.pipe(res) + + // response finished, done with the fd + onFinished(res, function onfinished () { + finished = true + destroy(stream) + }) + + // error handling code-smell + stream.on('error', function onerror (err) { + // request already finished + if (finished) return + + // clean up stream + finished = true + destroy(stream) + + // error + self.onStatError(err) + }) + + // end + stream.on('end', function onend () { + self.emit('end') + }) +} + +/** + * Set content-type based on `path` + * if it hasn't been explicitly set. + * + * @param {String} path + * @api private + */ + +SendStream.prototype.type = function type (path) { + var res = this.res + + if (res.getHeader('Content-Type')) return + + var type = mime.lookup(path) + + if (!type) { + debug('no content-type') + return + } + + var charset = mime.charsets.lookup(type) + + debug('content-type %s', type) + res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')) +} + +/** + * Set response header fields, most + * fields may be pre-defined. + * + * @param {String} path + * @param {Object} stat + * @api private + */ + +SendStream.prototype.setHeader = function setHeader (path, stat) { + var res = this.res + + this.emit('headers', res, path, stat) + + if (this._acceptRanges && !res.getHeader('Accept-Ranges')) { + debug('accept ranges') + res.setHeader('Accept-Ranges', 'bytes') + } + + if (this._cacheControl && !res.getHeader('Cache-Control')) { + var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000) + + if (this._immutable) { + cacheControl += ', immutable' + } + + debug('cache-control %s', cacheControl) + res.setHeader('Cache-Control', cacheControl) + } + + if (this._lastModified && !res.getHeader('Last-Modified')) { + var modified = stat.mtime.toUTCString() + debug('modified %s', modified) + res.setHeader('Last-Modified', modified) + } + + if (this._etag && !res.getHeader('ETag')) { + var val = etag(stat) + debug('etag %s', val) + res.setHeader('ETag', val) + } +} + +/** + * Clear all headers from a response. + * + * @param {object} res + * @private + */ + +function clearHeaders (res) { + var headers = getHeaderNames(res) + + for (var i = 0; i < headers.length; i++) { + res.removeHeader(headers[i]) + } +} + +/** + * Collapse all leading slashes into a single slash + * + * @param {string} str + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str[i] !== '/') { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Determine if path parts contain a dotfile. + * + * @api private + */ + +function containsDotFile (parts) { + for (var i = 0; i < parts.length; i++) { + var part = parts[i] + if (part.length > 1 && part[0] === '.') { + return true + } + } + + return false +} + +/** + * Create a Content-Range header. + * + * @param {string} type + * @param {number} size + * @param {array} [range] + */ + +function contentRange (type, size, range) { + return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
    ' + body + '
    \n' + + '\n' + + '\n' +} + +/** + * decodeURIComponent. + * + * Allows V8 to only deoptimize this fn instead of all + * of send(). + * + * @param {String} path + * @api private + */ + +function decode (path) { + try { + return decodeURIComponent(path) + } catch (err) { + return -1 + } +} + +/** + * Get the header names on a respnse. + * + * @param {object} res + * @returns {array[string]} + * @private + */ + +function getHeaderNames (res) { + return typeof res.getHeaderNames !== 'function' + ? Object.keys(res._headers || {}) + : res.getHeaderNames() +} + +/** + * Determine if emitter has listeners of a given type. + * + * The way to do this check is done three different ways in Node.js >= 0.8 + * so this consolidates them into a minimal set using instance methods. + * + * @param {EventEmitter} emitter + * @param {string} type + * @returns {boolean} + * @private + */ + +function hasListeners (emitter, type) { + var count = typeof emitter.listenerCount !== 'function' + ? emitter.listeners(type).length + : emitter.listenerCount(type) + + return count > 0 +} + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} + +/** + * Normalize the index option into an array. + * + * @param {boolean|string|array} val + * @param {string} name + * @private + */ + +function normalizeList (val, name) { + var list = [].concat(val || []) + + for (var i = 0; i < list.length; i++) { + if (typeof list[i] !== 'string') { + throw new TypeError(name + ' must be array of strings or false') + } + } + + return list +} + +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) + + return typeof timestamp === 'number' + ? timestamp + : NaN +} + +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ + +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(str.substring(start, end)) + + return list +} + +/** + * Set an object of headers on a response. + * + * @param {object} res + * @param {object} headers + * @private + */ + +function setHeaders (res, headers) { + var keys = Object.keys(headers) + + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } +} diff --git a/node_modules/send/package.json b/node_modules/send/package.json new file mode 100644 index 00000000..a1ca52d3 --- /dev/null +++ b/node_modules/send/package.json @@ -0,0 +1,109 @@ +{ + "_args": [ + [ + "send@0.16.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "send@0.16.2", + "_id": "send@0.16.2", + "_inBundle": false, + "_integrity": "sha512-E64YFPUssFHEFBvpbbjr44NCLtI1AohxQ8ZSiJjQLskAdKuriYEP6VyGEsRDH8ScozGpkaX1BGvhanqCwkcEZw==", + "_location": "/send", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "send@0.16.2", + "name": "send", + "escapedName": "send", + "rawSpec": "0.16.2", + "saveSpec": null, + "fetchSpec": "0.16.2" + }, + "_requiredBy": [ + "/express", + "/serve-static" + ], + "_resolved": "https://registry.npmjs.org/send/-/send-0.16.2.tgz", + "_spec": "0.16.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "bugs": { + "url": "https://github.com/pillarjs/send/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "James Wyatt Cready", + "email": "jcready@gmail.com" + }, + { + "name": "Jesús Leganés Combarro", + "email": "piranna@gmail.com" + } + ], + "dependencies": { + "debug": "2.6.9", + "depd": "~1.1.2", + "destroy": "~1.0.4", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "~1.6.2", + "mime": "1.4.1", + "ms": "2.0.0", + "on-finished": "~2.3.0", + "range-parser": "~1.2.0", + "statuses": "~1.4.0" + }, + "description": "Better streaming static file server with Range and conditional-GET support", + "devDependencies": { + "after": "0.8.2", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "engines": { + "node": ">= 0.8.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "homepage": "https://github.com/pillarjs/send#readme", + "keywords": [ + "static", + "file", + "server" + ], + "license": "MIT", + "name": "send", + "repository": { + "type": "git", + "url": "git+https://github.com/pillarjs/send.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --check-leaks --reporter spec --bail", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --check-leaks --reporter spec", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --check-leaks --reporter dot" + }, + "version": "0.16.2" +} diff --git a/node_modules/serve-static/HISTORY.md b/node_modules/serve-static/HISTORY.md new file mode 100644 index 00000000..6886ce59 --- /dev/null +++ b/node_modules/serve-static/HISTORY.md @@ -0,0 +1,433 @@ +1.13.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in redirects + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: send@0.16.2 + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + +1.13.1 / 2017-09-29 +=================== + + * Fix regression when `root` is incorrectly set to a file + * deps: send@0.16.1 + +1.13.0 / 2017-09-27 +=================== + + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + +1.12.6 / 2017-09-22 +=================== + + * deps: send@0.15.6 + - deps: debug@2.6.9 + - perf: improve `If-Match` token parsing + * perf: improve slash collapsing + +1.12.5 / 2017-09-21 +=================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: send@0.15.5 + - Fix handling of modified headers with invalid dates + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + +1.12.4 / 2017-08-05 +=================== + + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + +1.12.3 / 2017-05-16 +=================== + + * deps: send@0.15.3 + - deps: debug@2.6.7 + +1.12.2 / 2017-04-26 +=================== + + * deps: send@0.15.2 + - deps: debug@2.6.4 + +1.12.1 / 2017-03-04 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + +1.12.0 / 2017-02-25 +=================== + + * Send complete HTML document in redirect response + * Set default CSP header in redirect response + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + +1.11.2 / 2017-01-23 +=================== + + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + +1.11.1 / 2016-06-10 +=================== + + * Fix redirect error when `req.url` contains raw non-URL characters + * deps: send@0.14.1 + +1.11.0 / 2016-06-07 +=================== + + * Use status code 301 for redirects + * deps: send@0.14.0 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + +1.10.3 / 2016-05-30 +=================== + + * deps: send@0.13.2 + - Fix invalid `Content-Type` header when `send.mime.default_type` unset + +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +1.9.3 / 2015-05-14 +================== + + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +1.9.2 / 2015-03-14 +================== + + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +1.9.1 / 2015-02-17 +================== + + * deps: send@0.12.1 + - Fix regression sending zero-length files + +1.9.0 / 2015-02-16 +================== + + * deps: send@0.12.0 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +1.8.1 / 2015-01-20 +================== + + * Fix redirect loop in Node.js 0.11.14 + * deps: send@0.11.1 + - Fix root path disclosure + +1.8.0 / 2015-01-05 +================== + + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +1.7.2 / 2015-01-02 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +1.6.5 / 2015-02-04 +================== + + * Fix potential open redirect when mounted at root + - Back-ported from v1.7.2 + +1.6.4 / 2014-10-08 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/node_modules/serve-static/LICENSE b/node_modules/serve-static/LICENSE new file mode 100644 index 00000000..cbe62e8e --- /dev/null +++ b/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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/serve-static/README.md b/node_modules/serve-static/README.md new file mode 100644 index 00000000..269becbd --- /dev/null +++ b/node_modules/serve-static/README.md @@ -0,0 +1,258 @@ +# serve-static + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Linux Build][travis-image]][travis-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install serve-static +``` + +## API + + + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + + Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. To disable this set `false` or to supply a new index pass a +string or an array in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. This +can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) +module. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', {'index': ['index.html', 'index.htm']}) + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + 'index': false, + 'setHeaders': setHeaders +}) + +// Set header to force download +function setHeaders (res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']})) +app.listen(3000) +``` + +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are look for in `public-optimized/` first, then `public/` second as +a fallback. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file type. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public'), { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl (res, path) { + if (serveStatic.mime.lookup(path) === 'text/html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/serve-static.svg +[npm-url]: https://npmjs.org/package/serve-static +[travis-image]: https://img.shields.io/travis/expressjs/serve-static/master.svg?label=linux +[travis-url]: https://travis-ci.org/expressjs/serve-static +[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/serve-static/master.svg?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static +[coveralls-image]: https://img.shields.io/coveralls/expressjs/serve-static/master.svg +[coveralls-url]: https://coveralls.io/r/expressjs/serve-static +[downloads-image]: https://img.shields.io/npm/dm/serve-static.svg +[downloads-url]: https://npmjs.org/package/serve-static diff --git a/node_modules/serve-static/index.js b/node_modules/serve-static/index.js new file mode 100644 index 00000000..75ddd291 --- /dev/null +++ b/node_modules/serve-static/index.js @@ -0,0 +1,210 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic (root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic (req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile () { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error (err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) !== 0x2f /* / */) { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + + /** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
    ' + body + '
    \n' + + '\n' + + '\n' +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener () { + return function notFound () { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener () { + return function redirect (res) { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = encodeUrl(url.format(originalUrl)) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + + escapeHtml(loc) + '') + + // send redirect response + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'self'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) + } +} diff --git a/node_modules/serve-static/package.json b/node_modules/serve-static/package.json new file mode 100644 index 00000000..1d25ec2d --- /dev/null +++ b/node_modules/serve-static/package.json @@ -0,0 +1,78 @@ +{ + "_args": [ + [ + "serve-static@1.13.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "serve-static@1.13.2", + "_id": "serve-static@1.13.2", + "_inBundle": false, + "_integrity": "sha512-p/tdJrO4U387R9oMjb1oj7qSMaMfmOyd4j9hOFoxZe2baQszgHcSWjuya/CiT5kgZZKRudHNOA0pYXOl8rQ5nw==", + "_location": "/serve-static", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "serve-static@1.13.2", + "name": "serve-static", + "escapedName": "serve-static", + "rawSpec": "1.13.2", + "saveSpec": null, + "fetchSpec": "1.13.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.13.2.tgz", + "_spec": "1.13.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/expressjs/serve-static/issues" + }, + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.2", + "send": "0.16.2" + }, + "description": "Serve static files", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "engines": { + "node": ">= 0.8.0" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "homepage": "https://github.com/expressjs/serve-static#readme", + "license": "MIT", + "name": "serve-static", + "repository": { + "type": "git", + "url": "git+https://github.com/expressjs/serve-static.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/" + }, + "version": "1.13.2" +} diff --git a/node_modules/setprototypeof/LICENSE b/node_modules/setprototypeof/LICENSE new file mode 100644 index 00000000..61afa2f1 --- /dev/null +++ b/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +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/setprototypeof/README.md b/node_modules/setprototypeof/README.md new file mode 100644 index 00000000..826bf029 --- /dev/null +++ b/node_modules/setprototypeof/README.md @@ -0,0 +1,26 @@ +# Polyfill for `Object.setPrototypeOf` + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof'); + +var obj = {}; +setPrototypeOf(obj, { + foo: function() { + return 'bar'; + } +}); +obj.foo(); // bar +``` + +TypeScript is also supported: +```typescript +import setPrototypeOf = require('setprototypeof'); +``` \ No newline at end of file diff --git a/node_modules/setprototypeof/index.d.ts b/node_modules/setprototypeof/index.d.ts new file mode 100644 index 00000000..f108ecd0 --- /dev/null +++ b/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/node_modules/setprototypeof/index.js b/node_modules/setprototypeof/index.js new file mode 100644 index 00000000..93ea4176 --- /dev/null +++ b/node_modules/setprototypeof/index.js @@ -0,0 +1,15 @@ +module.exports = Object.setPrototypeOf || ({__proto__:[]} instanceof Array ? setProtoOf : mixinProperties); + +function setProtoOf(obj, proto) { + obj.__proto__ = proto; + return obj; +} + +function mixinProperties(obj, proto) { + for (var prop in proto) { + if (!obj.hasOwnProperty(prop)) { + obj[prop] = proto[prop]; + } + } + return obj; +} diff --git a/node_modules/setprototypeof/package.json b/node_modules/setprototypeof/package.json new file mode 100644 index 00000000..42c0f217 --- /dev/null +++ b/node_modules/setprototypeof/package.json @@ -0,0 +1,56 @@ +{ + "_args": [ + [ + "setprototypeof@1.1.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "setprototypeof@1.1.0", + "_id": "setprototypeof@1.1.0", + "_inBundle": false, + "_integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "_location": "/setprototypeof", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "setprototypeof@1.1.0", + "name": "setprototypeof", + "escapedName": "setprototypeof", + "rawSpec": "1.1.0", + "saveSpec": null, + "fetchSpec": "1.1.0" + }, + "_requiredBy": [ + "/express", + "/http-errors" + ], + "_resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", + "_spec": "1.1.0", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Wes Todd" + }, + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "description": "A small polyfill for Object.setprototypeof", + "homepage": "https://github.com/wesleytodd/setprototypeof", + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "license": "ISC", + "main": "index.js", + "name": "setprototypeof", + "repository": { + "type": "git", + "url": "git+https://github.com/wesleytodd/setprototypeof.git" + }, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "typings": "index.d.ts", + "version": "1.1.0" +} diff --git a/node_modules/statuses/HISTORY.md b/node_modules/statuses/HISTORY.md new file mode 100644 index 00000000..7b59790a --- /dev/null +++ b/node_modules/statuses/HISTORY.md @@ -0,0 +1,60 @@ +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/statuses/LICENSE b/node_modules/statuses/LICENSE new file mode 100644 index 00000000..28a31618 --- /dev/null +++ b/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +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/statuses/README.md b/node_modules/statuses/README.md new file mode 100644 index 00000000..0fe5720d --- /dev/null +++ b/node_modules/statuses/README.md @@ -0,0 +1,127 @@ +# Statuses + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### var code = status(Integer || String) + +If `Integer` or `String` is a valid HTTP code or status message, then the +appropriate `code` will be returned. Otherwise, an error will be thrown. + + + +```js +status(403) // => 403 +status('403') // => 403 +status('forbidden') // => 403 +status('Forbidden') // => 403 +status(306) // throws, as it's not supported by node.js +``` + +### status.STATUS_CODES + +Returns an object which maps status codes to status messages, in +the same format as the +[Node.js http module](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### var msg = status[code] + +Map of `code` to `status message`. `undefined` for invalid `code`s. + + + +```js +status[404] // => 'Not Found' +``` + +### var code = status[msg] + +Map of `status message` to `code`. `msg` can either be title-cased or +lower-cased. `undefined` for invalid `status message`s. + + + +```js +status['not found'] // => 404 +status['Not Found'] // => 404 +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +[npm-image]: https://img.shields.io/npm/v/statuses.svg +[npm-url]: https://npmjs.org/package/statuses +[node-version-image]: https://img.shields.io/node/v/statuses.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/statuses.svg +[travis-url]: https://travis-ci.org/jshttp/statuses +[coveralls-image]: https://img.shields.io/coveralls/jshttp/statuses.svg +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[downloads-image]: https://img.shields.io/npm/dm/statuses.svg +[downloads-url]: https://npmjs.org/package/statuses diff --git a/node_modules/statuses/codes.json b/node_modules/statuses/codes.json new file mode 100644 index 00000000..66f70e35 --- /dev/null +++ b/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "306": "(Unused)", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Unordered Collection", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 00000000..4df469a0 --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,113 @@ +/*! + * 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.STATUS_CODES = codes + +// array of status codes +status.codes = populateStatusesMap(status, 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 +} + +/** + * Populate the statuses map for given codes. + * @private + */ + +function populateStatusesMap (statuses, codes) { + var arr = [] + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // Populate properties + statuses[status] = message + statuses[message] = status + statuses[message.toLowerCase()] = status + + // Add to array + arr.push(status) + }) + + return arr +} + +/** + * 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') { + if (!status[code]) throw new Error('invalid status code: ' + code) + return code + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + if (!status[n]) throw new Error('invalid status code: ' + n) + return n + } + + n = status[code.toLowerCase()] + if (!n) throw new Error('invalid status message: "' + code + '"') + return n +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 00000000..03bff224 --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,94 @@ +{ + "_args": [ + [ + "statuses@1.4.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "statuses@1.4.0", + "_id": "statuses@1.4.0", + "_inBundle": false, + "_integrity": "sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==", + "_location": "/statuses", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "statuses@1.4.0", + "name": "statuses", + "escapedName": "statuses", + "rawSpec": "1.4.0", + "saveSpec": null, + "fetchSpec": "1.4.0" + }, + "_requiredBy": [ + "/express", + "/finalhandler", + "/http-errors", + "/raw-body/http-errors", + "/send" + ], + "_resolved": "https://registry.npmjs.org/statuses/-/statuses-1.4.0.tgz", + "_spec": "1.4.0", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/statuses/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "description": "HTTP status utility", + "devDependencies": { + "csv-parse": "1.2.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.2.0", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5", + "raw-body": "2.3.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "homepage": "https://github.com/jshttp/statuses#readme", + "keywords": [ + "http", + "status", + "code" + ], + "license": "MIT", + "name": "statuses", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/statuses.git" + }, + "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": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "update": "npm run fetch && npm run build" + }, + "version": "1.4.0" +} diff --git a/node_modules/type-is/HISTORY.md b/node_modules/type-is/HISTORY.md new file mode 100644 index 00000000..183290cb --- /dev/null +++ b/node_modules/type-is/HISTORY.md @@ -0,0 +1,236 @@ +1.6.16 / 2018-02-16 +=================== + + * deps: mime-types@~2.1.18 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add extension `.mjs` to `application/javascript` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add glTF types and extensions + - Add new mime types + - Update extensions `.md` and `.markdown` to be `text/markdown` + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +1.6.15 / 2017-03-31 +=================== + + * deps: mime-types@~2.1.15 + - Add new mime types + +1.6.14 / 2016-11-18 +=================== + + * deps: mime-types@~2.1.13 + - Add new mime types + +1.6.13 / 2016-05-18 +=================== + + * deps: mime-types@~2.1.11 + - Add new mime types + +1.6.12 / 2016-02-28 +=================== + + * deps: mime-types@~2.1.10 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +1.6.11 / 2016-01-29 +=================== + + * deps: mime-types@~2.1.9 + - Add new mime types + +1.6.10 / 2015-12-01 +=================== + + * deps: mime-types@~2.1.8 + - Add new mime types + +1.6.9 / 2015-09-27 +================== + + * deps: mime-types@~2.1.7 + - Add new mime types + +1.6.8 / 2015-09-04 +================== + + * deps: mime-types@~2.1.6 + - Add new mime types + +1.6.7 / 2015-08-20 +================== + + * Fix type error when given invalid type to match against + * deps: mime-types@~2.1.5 + - Add new mime types + +1.6.6 / 2015-07-31 +================== + + * deps: mime-types@~2.1.4 + - Add new mime types + +1.6.5 / 2015-07-16 +================== + + * deps: mime-types@~2.1.3 + - Add new mime types + +1.6.4 / 2015-07-01 +================== + + * deps: mime-types@~2.1.2 + - Add new mime types + * perf: enable strict mode + * perf: remove argument reassignment + +1.6.3 / 2015-06-08 +================== + + * deps: mime-types@~2.1.1 + - Add new mime types + * perf: reduce try block size + * perf: remove bitwise operations + +1.6.2 / 2015-05-10 +================== + + * deps: mime-types@~2.0.11 + - Add new mime types + +1.6.1 / 2015-03-13 +================== + + * deps: mime-types@~2.0.10 + - Add new mime types + +1.6.0 / 2015-02-12 +================== + + * fix false-positives in `hasBody` `Transfer-Encoding` check + * support wildcard for both type and subtype (`*/*`) + +1.5.7 / 2015-02-09 +================== + + * fix argument reassignment + * deps: mime-types@~2.0.9 + - Add new mime types + +1.5.6 / 2015-01-29 +================== + + * deps: mime-types@~2.0.8 + - Add new mime types + +1.5.5 / 2014-12-30 +================== + + * deps: mime-types@~2.0.7 + - Add new mime types + - Fix missing extensions + - Fix various invalid MIME type entries + - Remove example template MIME types + - deps: mime-db@~1.5.0 + +1.5.4 / 2014-12-10 +================== + + * deps: mime-types@~2.0.4 + - Add new mime types + - deps: mime-db@~1.3.0 + +1.5.3 / 2014-11-09 +================== + + * deps: mime-types@~2.0.3 + - Add new mime types + - deps: mime-db@~1.2.0 + +1.5.2 / 2014-09-28 +================== + + * deps: mime-types@~2.0.2 + - Add new mime types + - deps: mime-db@~1.1.0 + +1.5.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + * deps: media-typer@0.3.0 + * deps: mime-types@~2.0.1 + - Support Node.js 0.6 + +1.5.0 / 2014-09-05 +================== + + * fix `hasbody` to be true for `content-length: 0` + +1.4.0 / 2014-09-02 +================== + + * update mime-types + +1.3.2 / 2014-06-24 +================== + + * use `~` range on mime-types + +1.3.1 / 2014-06-19 +================== + + * fix global variable leak + +1.3.0 / 2014-06-19 +================== + + * improve type parsing + + - invalid media type never matches + - media type not case-sensitive + - extra LWS does not affect results + +1.2.2 / 2014-06-19 +================== + + * fix behavior on unknown type argument + +1.2.1 / 2014-06-03 +================== + + * switch dependency from `mime` to `mime-types@1.0.0` + +1.2.0 / 2014-05-11 +================== + + * support suffix matching: + + - `+json` matches `application/vnd+json` + - `*/vnd+json` matches `application/vnd+json` + - `application/*+json` matches `application/vnd+json` + +1.1.0 / 2014-04-12 +================== + + * add non-array values support + * expose internal utilities: + + - `.is()` + - `.hasBody()` + - `.normalize()` + - `.match()` + +1.0.1 / 2014-03-30 +================== + + * add `multipart` as a shorthand diff --git a/node_modules/type-is/LICENSE b/node_modules/type-is/LICENSE new file mode 100644 index 00000000..386b7b69 --- /dev/null +++ b/node_modules/type-is/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2014-2015 Douglas Christopher Wilson + +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/type-is/README.md b/node_modules/type-is/README.md new file mode 100644 index 00000000..70c47dae --- /dev/null +++ b/node_modules/type-is/README.md @@ -0,0 +1,146 @@ +# type-is + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Infer the content-type of a request. + +### Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install type-is +``` + +## API + +```js +var http = require('http') +var typeis = require('type-is') + +http.createServer(function (req, res) { + var istext = typeis(req, ['text/*']) + res.end('you ' + (istext ? 'sent' : 'did not send') + ' me text') +}) +``` + +### type = typeis(request, types) + +`request` is the node HTTP request. `types` is an array of types. + + + +```js +// req.headers.content-type = 'application/json' + +typeis(req, ['json']) // 'json' +typeis(req, ['html', 'json']) // 'json' +typeis(req, ['application/*']) // 'application/json' +typeis(req, ['application/json']) // 'application/json' + +typeis(req, ['html']) // false +``` + +### typeis.hasBody(request) + +Returns a Boolean if the given `request` has a body, regardless of the +`Content-Type` header. + +Having a body has no relation to how large the body is (it may be 0 bytes). +This is similar to how file existence works. If a body does exist, then this +indicates that there is data to read from the Node.js request stream. + + + +```js +if (typeis.hasBody(req)) { + // read the body, since there is one + + req.on('data', function (chunk) { + // ... + }) +} +``` + +### type = typeis.is(mediaType, types) + +`mediaType` is the [media type](https://tools.ietf.org/html/rfc6838) string. `types` is an array of types. + + + +```js +var mediaType = 'application/json' + +typeis.is(mediaType, ['json']) // 'json' +typeis.is(mediaType, ['html', 'json']) // 'json' +typeis.is(mediaType, ['application/*']) // 'application/json' +typeis.is(mediaType, ['application/json']) // 'application/json' + +typeis.is(mediaType, ['html']) // false +``` + +### Each type can be: + +- An extension name such as `json`. This name will be returned if matched. +- A mime type such as `application/json`. +- A mime type with a wildcard such as `*/*` or `*/json` or `application/*`. The full mime type will be returned if matched. +- A suffix such as `+json`. This can be combined with a wildcard such as `*/vnd+json` or `application/*+json`. The full mime type will be returned if matched. + +`false` will be returned if no type matches or the content type is invalid. + +`null` will be returned if the request does not have a body. + +## Examples + +### Example body parser + +```js +var express = require('express') +var typeis = require('type-is') + +var app = express() + +app.use(function bodyParser (req, res, next) { + if (!typeis.hasBody(req)) { + return next() + } + + switch (typeis(req, ['urlencoded', 'json', 'multipart'])) { + case 'urlencoded': + // parse urlencoded body + throw new Error('implement urlencoded body parsing') + case 'json': + // parse json body + throw new Error('implement json body parsing') + case 'multipart': + // parse multipart body + throw new Error('implement multipart body parsing') + default: + // 415 error code + res.statusCode = 415 + res.end() + break + } +}) +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/type-is.svg +[npm-url]: https://npmjs.org/package/type-is +[node-version-image]: https://img.shields.io/node/v/type-is.svg +[node-version-url]: https://nodejs.org/en/download/ +[travis-image]: https://img.shields.io/travis/jshttp/type-is/master.svg +[travis-url]: https://travis-ci.org/jshttp/type-is +[coveralls-image]: https://img.shields.io/coveralls/jshttp/type-is/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/type-is?branch=master +[downloads-image]: https://img.shields.io/npm/dm/type-is.svg +[downloads-url]: https://npmjs.org/package/type-is diff --git a/node_modules/type-is/index.js b/node_modules/type-is/index.js new file mode 100644 index 00000000..4da73011 --- /dev/null +++ b/node_modules/type-is/index.js @@ -0,0 +1,262 @@ +/*! + * type-is + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var typer = require('media-typer') +var mime = require('mime-types') + +/** + * Module exports. + * @public + */ + +module.exports = typeofrequest +module.exports.is = typeis +module.exports.hasBody = hasbody +module.exports.normalize = normalize +module.exports.match = mimeMatch + +/** + * Compare a `value` content-type with `types`. + * Each `type` can be an extension like `html`, + * a special shortcut like `multipart` or `urlencoded`, + * or a mime type. + * + * If no types match, `false` is returned. + * Otherwise, the first `type` that matches is returned. + * + * @param {String} value + * @param {Array} types + * @public + */ + +function typeis (value, types_) { + var i + var types = types_ + + // remove parameters and normalize + var val = tryNormalizeType(value) + + // no type or invalid + if (!val) { + return false + } + + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length - 1) + for (i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // no types, return the content type + if (!types || !types.length) { + return val + } + + var type + for (i = 0; i < types.length; i++) { + if (mimeMatch(normalize(type = types[i]), val)) { + return type[0] === '+' || type.indexOf('*') !== -1 + ? val + : type + } + } + + // no matches + return false +} + +/** + * Check if a request has a request body. + * A request with a body __must__ either have `transfer-encoding` + * or `content-length` headers set. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3 + * + * @param {Object} request + * @return {Boolean} + * @public + */ + +function hasbody (req) { + return req.headers['transfer-encoding'] !== undefined || + !isNaN(req.headers['content-length']) +} + +/** + * Check if the incoming request contains the "Content-Type" + * header field, and it contains any of the give mime `type`s. + * If there is no request body, `null` is returned. + * If there is no content type, `false` is returned. + * Otherwise, it returns the first `type` that matches. + * + * Examples: + * + * // With Content-Type: text/html; charset=utf-8 + * this.is('html'); // => 'html' + * this.is('text/html'); // => 'text/html' + * this.is('text/*', 'application/json'); // => 'text/html' + * + * // When Content-Type is application/json + * this.is('json', 'urlencoded'); // => 'json' + * this.is('application/json'); // => 'application/json' + * this.is('html', 'application/*'); // => 'application/json' + * + * this.is('html'); // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public + */ + +function typeofrequest (req, types_) { + var types = types_ + + // no body + if (!hasbody(req)) { + return null + } + + // support flattened arguments + if (arguments.length > 2) { + types = new Array(arguments.length - 1) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i + 1] + } + } + + // request content type + var value = req.headers['content-type'] + + return typeis(value, types) +} + +/** + * Normalize a mime type. + * If it's a shorthand, expand it to a valid mime type. + * + * In general, you probably want: + * + * var type = is(req, ['urlencoded', 'json', 'multipart']); + * + * Then use the appropriate body parsers. + * These three are the most common request body types + * and are thus ensured to work. + * + * @param {String} type + * @private + */ + +function normalize (type) { + if (typeof type !== 'string') { + // invalid type + return false + } + + switch (type) { + case 'urlencoded': + return 'application/x-www-form-urlencoded' + case 'multipart': + return 'multipart/*' + } + + if (type[0] === '+') { + // "+json" -> "*/*+json" expando + return '*/*' + type + } + + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} + +/** + * Check if `expected` mime type + * matches `actual` mime type with + * wildcard and +suffix support. + * + * @param {String} expected + * @param {String} actual + * @return {Boolean} + * @private + */ + +function mimeMatch (expected, actual) { + // invalid type + if (expected === false) { + return false + } + + // split types + var actualParts = actual.split('/') + var expectedParts = expected.split('/') + + // invalid format + if (actualParts.length !== 2 || expectedParts.length !== 2) { + return false + } + + // validate type + if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) { + return false + } + + // validate suffix wildcard + if (expectedParts[1].substr(0, 2) === '*+') { + return expectedParts[1].length <= actualParts[1].length + 1 && + expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length) + } + + // validate subtype + if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) { + return false + } + + return true +} + +/** + * Normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function normalizeType (value) { + // parse the type + var type = typer.parse(value) + + // remove the parameters + type.parameters = undefined + + // reformat it + return typer.format(type) +} + +/** + * Try to normalize a type and remove parameters. + * + * @param {string} value + * @return {string} + * @private + */ + +function tryNormalizeType (value) { + try { + return normalizeType(value) + } catch (err) { + return null + } +} diff --git a/node_modules/type-is/package.json b/node_modules/type-is/package.json new file mode 100644 index 00000000..4cd6707d --- /dev/null +++ b/node_modules/type-is/package.json @@ -0,0 +1,88 @@ +{ + "_args": [ + [ + "type-is@1.6.16", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "type-is@1.6.16", + "_id": "type-is@1.6.16", + "_inBundle": false, + "_integrity": "sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==", + "_location": "/type-is", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "type-is@1.6.16", + "name": "type-is", + "escapedName": "type-is", + "rawSpec": "1.6.16", + "saveSpec": null, + "fetchSpec": "1.6.16" + }, + "_requiredBy": [ + "/body-parser", + "/express" + ], + "_resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.16.tgz", + "_spec": "1.6.16", + "_where": "C:\\GitHub\\cis411_lab0", + "bugs": { + "url": "https://github.com/jshttp/type-is/issues" + }, + "contributors": [ + { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + { + "name": "Jonathan Ong", + "email": "me@jongleberry.com", + "url": "http://jongleberry.com" + } + ], + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.18" + }, + "description": "Infer the content-type of a request.", + "devDependencies": { + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.8.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.2.1", + "eslint-plugin-promise": "3.6.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "1.21.5" + }, + "engines": { + "node": ">= 0.6" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/type-is#readme", + "keywords": [ + "content", + "type", + "checking" + ], + "license": "MIT", + "name": "type-is", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/type-is.git" + }, + "scripts": { + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.6.16" +} diff --git a/node_modules/unpipe/HISTORY.md b/node_modules/unpipe/HISTORY.md new file mode 100644 index 00000000..85e0f8d7 --- /dev/null +++ b/node_modules/unpipe/HISTORY.md @@ -0,0 +1,4 @@ +1.0.0 / 2015-06-14 +================== + + * Initial release diff --git a/node_modules/unpipe/LICENSE b/node_modules/unpipe/LICENSE new file mode 100644 index 00000000..aed01382 --- /dev/null +++ b/node_modules/unpipe/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Douglas Christopher Wilson + +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/unpipe/README.md b/node_modules/unpipe/README.md new file mode 100644 index 00000000..e536ad2c --- /dev/null +++ b/node_modules/unpipe/README.md @@ -0,0 +1,43 @@ +# unpipe + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Unpipe a stream from all destinations. + +## Installation + +```sh +$ npm install unpipe +``` + +## API + +```js +var unpipe = require('unpipe') +``` + +### unpipe(stream) + +Unpipes all destinations from a given stream. With stream 2+, this is +equivalent to `stream.unpipe()`. When used with streams 1 style streams +(typically Node.js 0.8 and below), this module attempts to undo the +actions done in `stream.pipe(dest)`. + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/unpipe.svg +[npm-url]: https://npmjs.org/package/unpipe +[node-image]: https://img.shields.io/node/v/unpipe.svg +[node-url]: http://nodejs.org/download/ +[travis-image]: https://img.shields.io/travis/stream-utils/unpipe.svg +[travis-url]: https://travis-ci.org/stream-utils/unpipe +[coveralls-image]: https://img.shields.io/coveralls/stream-utils/unpipe.svg +[coveralls-url]: https://coveralls.io/r/stream-utils/unpipe?branch=master +[downloads-image]: https://img.shields.io/npm/dm/unpipe.svg +[downloads-url]: https://npmjs.org/package/unpipe diff --git a/node_modules/unpipe/index.js b/node_modules/unpipe/index.js new file mode 100644 index 00000000..15c3d97a --- /dev/null +++ b/node_modules/unpipe/index.js @@ -0,0 +1,69 @@ +/*! + * unpipe + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + * @public + */ + +module.exports = unpipe + +/** + * Determine if there are Node.js pipe-like data listeners. + * @private + */ + +function hasPipeDataListeners(stream) { + var listeners = stream.listeners('data') + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i].name === 'ondata') { + return true + } + } + + return false +} + +/** + * Unpipe a stream from all destinations. + * + * @param {object} stream + * @public + */ + +function unpipe(stream) { + if (!stream) { + throw new TypeError('argument stream is required') + } + + if (typeof stream.unpipe === 'function') { + // new-style + stream.unpipe() + return + } + + // Node.js 0.8 hack + if (!hasPipeDataListeners(stream)) { + return + } + + var listener + var listeners = stream.listeners('close') + + for (var i = 0; i < listeners.length; i++) { + listener = listeners[i] + + if (listener.name !== 'cleanup' && listener.name !== 'onclose') { + continue + } + + // invoke the listener + listener.call(stream) + } +} diff --git a/node_modules/unpipe/package.json b/node_modules/unpipe/package.json new file mode 100644 index 00000000..5b5be53c --- /dev/null +++ b/node_modules/unpipe/package.json @@ -0,0 +1,66 @@ +{ + "_args": [ + [ + "unpipe@1.0.0", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "unpipe@1.0.0", + "_id": "unpipe@1.0.0", + "_inBundle": false, + "_integrity": "sha1-sr9O6FFKrmFltIF4KdIbLvSZBOw=", + "_location": "/unpipe", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "unpipe@1.0.0", + "name": "unpipe", + "escapedName": "unpipe", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/finalhandler", + "/raw-body" + ], + "_resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/stream-utils/unpipe/issues" + }, + "description": "Unpipe a stream from all destinations", + "devDependencies": { + "istanbul": "0.3.15", + "mocha": "2.2.5", + "readable-stream": "1.1.13" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "homepage": "https://github.com/stream-utils/unpipe#readme", + "license": "MIT", + "name": "unpipe", + "repository": { + "type": "git", + "url": "git+https://github.com/stream-utils/unpipe.git" + }, + "scripts": { + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.0.0" +} diff --git a/node_modules/utils-merge/.npmignore b/node_modules/utils-merge/.npmignore new file mode 100644 index 00000000..3e538441 --- /dev/null +++ b/node_modules/utils-merge/.npmignore @@ -0,0 +1,9 @@ +CONTRIBUTING.md +Makefile +docs/ +examples/ +reports/ +test/ + +.jshintrc +.travis.yml diff --git a/node_modules/utils-merge/LICENSE b/node_modules/utils-merge/LICENSE new file mode 100644 index 00000000..76f6d083 --- /dev/null +++ b/node_modules/utils-merge/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2017 Jared Hanson + +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/utils-merge/README.md b/node_modules/utils-merge/README.md new file mode 100644 index 00000000..0cb71171 --- /dev/null +++ b/node_modules/utils-merge/README.md @@ -0,0 +1,34 @@ +# utils-merge + +[![Version](https://img.shields.io/npm/v/utils-merge.svg?label=version)](https://www.npmjs.com/package/utils-merge) +[![Build](https://img.shields.io/travis/jaredhanson/utils-merge.svg)](https://travis-ci.org/jaredhanson/utils-merge) +[![Quality](https://img.shields.io/codeclimate/github/jaredhanson/utils-merge.svg?label=quality)](https://codeclimate.com/github/jaredhanson/utils-merge) +[![Coverage](https://img.shields.io/coveralls/jaredhanson/utils-merge.svg)](https://coveralls.io/r/jaredhanson/utils-merge) +[![Dependencies](https://img.shields.io/david/jaredhanson/utils-merge.svg)](https://david-dm.org/jaredhanson/utils-merge) + + +Merges the properties from a source object into a destination object. + +## Install + +```bash +$ npm install utils-merge +``` + +## Usage + +```javascript +var a = { foo: 'bar' } + , b = { bar: 'baz' }; + +merge(a, b); +// => { foo: 'bar', bar: 'baz' } +``` + +## License + +[The MIT License](http://opensource.org/licenses/MIT) + +Copyright (c) 2013-2017 Jared Hanson <[http://jaredhanson.net/](http://jaredhanson.net/)> + + Sponsor diff --git a/node_modules/utils-merge/index.js b/node_modules/utils-merge/index.js new file mode 100644 index 00000000..4265c694 --- /dev/null +++ b/node_modules/utils-merge/index.js @@ -0,0 +1,23 @@ +/** + * Merge object b with object a. + * + * var a = { foo: 'bar' } + * , b = { bar: 'baz' }; + * + * merge(a, b); + * // => { foo: 'bar', bar: 'baz' } + * + * @param {Object} a + * @param {Object} b + * @return {Object} + * @api public + */ + +exports = module.exports = function(a, b){ + if (a && b) { + for (var key in b) { + a[key] = b[key]; + } + } + return a; +}; diff --git a/node_modules/utils-merge/package.json b/node_modules/utils-merge/package.json new file mode 100644 index 00000000..5d46044c --- /dev/null +++ b/node_modules/utils-merge/package.json @@ -0,0 +1,69 @@ +{ + "_args": [ + [ + "utils-merge@1.0.1", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "utils-merge@1.0.1", + "_id": "utils-merge@1.0.1", + "_inBundle": false, + "_integrity": "sha1-n5VxD1CiZ5R7LMwSR0HBAoQn5xM=", + "_location": "/utils-merge", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "utils-merge@1.0.1", + "name": "utils-merge", + "escapedName": "utils-merge", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "_spec": "1.0.1", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Jared Hanson", + "email": "jaredhanson@gmail.com", + "url": "http://www.jaredhanson.net/" + }, + "bugs": { + "url": "http://github.com/jaredhanson/utils-merge/issues" + }, + "dependencies": {}, + "description": "merge() utility function", + "devDependencies": { + "chai": "1.x.x", + "make-node": "0.3.x", + "mocha": "1.x.x" + }, + "engines": { + "node": ">= 0.4.0" + }, + "homepage": "https://github.com/jaredhanson/utils-merge#readme", + "keywords": [ + "util" + ], + "license": "MIT", + "licenses": [ + { + "type": "MIT", + "url": "http://opensource.org/licenses/MIT" + } + ], + "main": "./index", + "name": "utils-merge", + "repository": { + "type": "git", + "url": "git://github.com/jaredhanson/utils-merge.git" + }, + "scripts": { + "test": "mocha --reporter spec --require test/bootstrap/node test/*.test.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/uuid/.eslintrc.json b/node_modules/uuid/.eslintrc.json new file mode 100644 index 00000000..734a8e14 --- /dev/null +++ b/node_modules/uuid/.eslintrc.json @@ -0,0 +1,47 @@ +{ + "root": true, + "env": { + "browser": true, + "commonjs": true, + "node": true, + "mocha": true + }, + "extends": ["eslint:recommended"], + "rules": { + "array-bracket-spacing": ["warn", "never"], + "arrow-body-style": ["warn", "as-needed"], + "arrow-parens": ["warn", "as-needed"], + "arrow-spacing": "warn", + "brace-style": ["warn", "1tbs"], + "camelcase": "warn", + "comma-spacing": ["warn", {"after": true}], + "dot-notation": "warn", + "eqeqeq": ["warn", "smart"], + "indent": ["warn", 2, { + "SwitchCase": 1, + "FunctionDeclaration": {"parameters": 1}, + "MemberExpression": 1, + "CallExpression": {"arguments": 1} + }], + "key-spacing": ["warn", {"beforeColon": false, "afterColon": true, "mode": "minimum"}], + "keyword-spacing": "warn", + "no-console": "off", + "no-empty": "off", + "no-multi-spaces": "warn", + "no-redeclare": "off", + "no-restricted-globals": ["warn", "Promise"], + "no-trailing-spaces": "warn", + "no-undef": "error", + "no-unused-vars": ["warn", {"args": "none"}], + "one-var": ["warn", "never"], + "padded-blocks": ["warn", "never"], + "object-curly-spacing": ["warn", "never"], + "quotes": ["warn", "single"], + "react/prop-types": "off", + "react/jsx-no-bind": "off", + "semi": ["warn", "always"], + "space-before-blocks": ["warn", "always"], + "space-before-function-paren": ["warn", "never"], + "space-in-parens": ["warn", "never"] + } +} diff --git a/node_modules/uuid/AUTHORS b/node_modules/uuid/AUTHORS new file mode 100644 index 00000000..5a105230 --- /dev/null +++ b/node_modules/uuid/AUTHORS @@ -0,0 +1,5 @@ +Robert Kieffer +Christoph Tavan +AJ ONeal +Vincent Voyer +Roman Shtylman diff --git a/node_modules/uuid/CHANGELOG.md b/node_modules/uuid/CHANGELOG.md new file mode 100644 index 00000000..f29d3991 --- /dev/null +++ b/node_modules/uuid/CHANGELOG.md @@ -0,0 +1,110 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +## [3.3.2](https://github.com/kelektiv/node-uuid/compare/v3.3.1...v3.3.2) (2018-06-28) + + +### Bug Fixes + +* typo ([305d877](https://github.com/kelektiv/node-uuid/commit/305d877)) + + + + +## [3.3.1](https://github.com/kelektiv/node-uuid/compare/v3.3.0...v3.3.1) (2018-06-28) + + +### Bug Fixes + +* fix [#284](https://github.com/kelektiv/node-uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/kelektiv/node-uuid/commit/f2a60f2)) + + + + +# [3.3.0](https://github.com/kelektiv/node-uuid/compare/v3.2.1...v3.3.0) (2018-06-22) + + +### Bug Fixes + +* assignment to readonly property to allow running in strict mode ([#270](https://github.com/kelektiv/node-uuid/issues/270)) ([d062fdc](https://github.com/kelektiv/node-uuid/commit/d062fdc)) +* fix [#229](https://github.com/kelektiv/node-uuid/issues/229) ([c9684d4](https://github.com/kelektiv/node-uuid/commit/c9684d4)) +* Get correct version of IE11 crypto ([#274](https://github.com/kelektiv/node-uuid/issues/274)) ([153d331](https://github.com/kelektiv/node-uuid/commit/153d331)) +* mem issue when generating uuid ([#267](https://github.com/kelektiv/node-uuid/issues/267)) ([c47702c](https://github.com/kelektiv/node-uuid/commit/c47702c)) + +### Features + +* enforce Conventional Commit style commit messages ([#282](https://github.com/kelektiv/node-uuid/issues/282)) ([cc9a182](https://github.com/kelektiv/node-uuid/commit/cc9a182)) + + + +## [3.2.1](https://github.com/kelektiv/node-uuid/compare/v3.2.0...v3.2.1) (2018-01-16) + + +### Bug Fixes + +* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b)) + + + + +# [3.2.0](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.2.0) (2018-01-16) + + +### Bug Fixes + +* remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/kelektiv/node-uuid/commit/09fa824)) +* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b)) + + +### Features + +* Add v3 Support ([#217](https://github.com/kelektiv/node-uuid/issues/217)) ([d94f726](https://github.com/kelektiv/node-uuid/commit/d94f726)) + + +# [3.1.0](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.0.1) (2017-06-17) + +### Bug Fixes + +* (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183) +* Fix typo (#178) +* Simple typo fix (#165) + +### Features +* v5 support in CLI (#197) +* V5 support (#188) + + +# 3.0.1 (2016-11-28) + +* split uuid versions into separate files + + +# 3.0.0 (2016-11-17) + +* remove .parse and .unparse + + +# 2.0.0 + +* Removed uuid.BufferClass + + +# 1.4.0 + +* Improved module context detection +* Removed public RNG functions + + +# 1.3.2 + +* Improve tests and handling of v1() options (Issue #24) +* Expose RNG option to allow for perf testing with different generators + + +# 1.3.0 + +* Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)! +* Support for node.js crypto API +* De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code diff --git a/node_modules/uuid/LICENSE.md b/node_modules/uuid/LICENSE.md new file mode 100644 index 00000000..8c84e398 --- /dev/null +++ b/node_modules/uuid/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010-2016 Robert Kieffer and other 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/uuid/README.md b/node_modules/uuid/README.md new file mode 100644 index 00000000..9cbe1ac1 --- /dev/null +++ b/node_modules/uuid/README.md @@ -0,0 +1,293 @@ + + +# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) # + +Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS. + +Features: + +* Support for version 1, 3, 4 and 5 UUIDs +* Cross-platform +* Uses cryptographically-strong random number APIs (when available) +* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883)) + +[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be +supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.] + +## Quickstart - CommonJS (Recommended) + +```shell +npm install uuid +``` + +Then generate your uuid version of choice ... + +Version 1 (timestamp): + +```javascript +const uuidv1 = require('uuid/v1'); +uuidv1(); // ⇨ '45745c60-7b1a-11e8-9c9c-2d42b21b1a3e' + +``` + +Version 3 (namespace): + +```javascript +const uuidv3 = require('uuid/v3'); + +// ... using predefined DNS namespace (for domain names) +uuidv3('hello.example.com', uuidv3.DNS); // ⇨ '9125a8dc-52ee-365b-a5aa-81b0b3681cf6' + +// ... using predefined URL namespace (for, well, URLs) +uuidv3('http://example.com/hello', uuidv3.URL); // ⇨ 'c6235813-3ba4-3801-ae84-e0a6ebb7d138' + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv3('Hello, World!', MY_NAMESPACE); // ⇨ 'e8b5a51d-11c8-3310-a6ab-367563f20686' + +``` + +Version 4 (random): + +```javascript +const uuidv4 = require('uuid/v4'); +uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a' + +``` + +Version 5 (namespace): + +```javascript +const uuidv5 = require('uuid/v5'); + +// ... using predefined DNS namespace (for domain names) +uuidv5('hello.example.com', uuidv5.DNS); // ⇨ 'fdda765f-fc57-5604-a269-52a7df8164ec' + +// ... using predefined URL namespace (for, well, URLs) +uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ '3bbcee75-cecc-5b56-8031-b6641c1ed1f1' + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' + +``` + +## Quickstart - Browser-ready Versions + +Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in). + +For version 1 uuids: + +```html + + +``` + +For version 3 uuids: + +```html + + +``` + +For version 4 uuids: + +```html + + +``` + +For version 5 uuids: + +```html + + +``` + +## API + +### Version 1 + +```javascript +const uuidv1 = require('uuid/v1'); + +// Incantations +uuidv1(); +uuidv1(options); +uuidv1(options, buffer, offset); +``` + +Generate and return a RFC4122 v1 (timestamp-based) UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + + * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1. + * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. + * `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used. + * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. + +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Note: The id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.) + +Example: Generate string UUID with fully-specified options + +```javascript +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678 +}; +uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' + +``` + +Example: In-place generation of two binary IDs + +```javascript +// Generate two ids in an array +const arr = new Array(); +uuidv1(null, arr, 0); // ⇨ [ 69, 117, 109, 208, 123, 26, 17, 232, 146, 52, 45, 66, 178, 27, 26, 62 ] +uuidv1(null, arr, 16); // ⇨ [ 69, 117, 109, 208, 123, 26, 17, 232, 146, 52, 45, 66, 178, 27, 26, 62, 69, 117, 109, 209, 123, 26, 17, 232, 146, 52, 45, 66, 178, 27, 26, 62 ] + +``` + +### Version 3 + +```javascript +const uuidv3 = require('uuid/v3'); + +// Incantations +uuidv3(name, namespace); +uuidv3(name, namespace, buffer); +uuidv3(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v3 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript +uuidv3('hello world', MY_NAMESPACE); // ⇨ '042ffd34-d989-321c-ad06-f60826172424' + +``` + +### Version 4 + +```javascript +const uuidv4 = require('uuid/v4') + +// Incantations +uuidv4(); +uuidv4(options); +uuidv4(options, buffer, offset); +``` + +Generate and return a RFC4122 v4 UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values + * `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255) +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: Generate string UUID with predefined `random` values + +```javascript +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, + 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 + ] +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' + +``` + +Example: Generate two IDs in a single buffer + +```javascript +const buffer = new Array(); +uuidv4(null, buffer, 0); // ⇨ [ 54, 122, 218, 70, 45, 70, 65, 24, 171, 53, 95, 130, 83, 195, 242, 45 ] +uuidv4(null, buffer, 16); // ⇨ [ 54, 122, 218, 70, 45, 70, 65, 24, 171, 53, 95, 130, 83, 195, 242, 45, 108, 204, 255, 103, 171, 86, 76, 94, 178, 225, 188, 236, 150, 20, 151, 87 ] + +``` + +### Version 5 + +```javascript +const uuidv5 = require('uuid/v5'); + +// Incantations +uuidv5(name, namespace); +uuidv5(name, namespace, buffer); +uuidv5(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v5 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript +uuidv5('hello world', MY_NAMESPACE); // ⇨ '9f282611-e0fd-5650-8953-89c8e342da0b' + +``` + +## Command Line + +UUIDs can be generated from the command line with the `uuid` command. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 + +$ uuid v1 +02d37060-d446-11e7-a9fa-7bdae751ebe1 +``` + +Type `uuid --help` for usage details + +## Testing + +```shell +npm test +``` + +---- +Markdown generated from [README_js.md](README_js.md) by [![RunMD Logo](http://i.imgur.com/h0FVyzU.png)](https://github.com/broofa/runmd) \ No newline at end of file diff --git a/node_modules/uuid/README_js.md b/node_modules/uuid/README_js.md new file mode 100644 index 00000000..f34453be --- /dev/null +++ b/node_modules/uuid/README_js.md @@ -0,0 +1,280 @@ +```javascript --hide +runmd.onRequire = path => path.replace(/^uuid/, './'); +``` + +# uuid [![Build Status](https://secure.travis-ci.org/kelektiv/node-uuid.svg?branch=master)](http://travis-ci.org/kelektiv/node-uuid) # + +Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS. + +Features: + +* Support for version 1, 3, 4 and 5 UUIDs +* Cross-platform +* Uses cryptographically-strong random number APIs (when available) +* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883)) + +[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be +supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.] + +## Quickstart - CommonJS (Recommended) + +```shell +npm install uuid +``` + +Then generate your uuid version of choice ... + +Version 1 (timestamp): + +```javascript --run v1 +const uuidv1 = require('uuid/v1'); +uuidv1(); // RESULT +``` + +Version 3 (namespace): + +```javascript --run v3 +const uuidv3 = require('uuid/v3'); + +// ... using predefined DNS namespace (for domain names) +uuidv3('hello.example.com', uuidv3.DNS); // RESULT + +// ... using predefined URL namespace (for, well, URLs) +uuidv3('http://example.com/hello', uuidv3.URL); // RESULT + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv3('Hello, World!', MY_NAMESPACE); // RESULT +``` + +Version 4 (random): + +```javascript --run v4 +const uuidv4 = require('uuid/v4'); +uuidv4(); // RESULT +``` + +Version 5 (namespace): + +```javascript --run v5 +const uuidv5 = require('uuid/v5'); + +// ... using predefined DNS namespace (for domain names) +uuidv5('hello.example.com', uuidv5.DNS); // RESULT + +// ... using predefined URL namespace (for, well, URLs) +uuidv5('http://example.com/hello', uuidv5.URL); // RESULT + +// ... using a custom namespace +// +// Note: Custom namespaces should be a UUID string specific to your application! +// E.g. the one here was generated using this modules `uuid` CLI. +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; +uuidv5('Hello, World!', MY_NAMESPACE); // RESULT +``` + +## Quickstart - Browser-ready Versions + +Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in). + +For version 1 uuids: + +```html + + +``` + +For version 3 uuids: + +```html + + +``` + +For version 4 uuids: + +```html + + +``` + +For version 5 uuids: + +```html + + +``` + +## API + +### Version 1 + +```javascript +const uuidv1 = require('uuid/v1'); + +// Incantations +uuidv1(); +uuidv1(options); +uuidv1(options, buffer, offset); +``` + +Generate and return a RFC4122 v1 (timestamp-based) UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + + * `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1. + * `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used. + * `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used. + * `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2. + +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Note: The id is generated guaranteed to stay constant for the lifetime of the current JS runtime. (Future versions of this module may use persistent storage mechanisms to extend this guarantee.) + +Example: Generate string UUID with fully-specified options + +```javascript --run v1 +const v1options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678 +}; +uuidv1(v1options); // RESULT +``` + +Example: In-place generation of two binary IDs + +```javascript --run v1 +// Generate two ids in an array +const arr = new Array(); +uuidv1(null, arr, 0); // RESULT +uuidv1(null, arr, 16); // RESULT +``` + +### Version 3 + +```javascript +const uuidv3 = require('uuid/v3'); + +// Incantations +uuidv3(name, namespace); +uuidv3(name, namespace, buffer); +uuidv3(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v3 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript --run v3 +uuidv3('hello world', MY_NAMESPACE); // RESULT +``` + +### Version 4 + +```javascript +const uuidv4 = require('uuid/v4') + +// Incantations +uuidv4(); +uuidv4(options); +uuidv4(options, buffer, offset); +``` + +Generate and return a RFC4122 v4 UUID. + +* `options` - (Object) Optional uuid state to apply. Properties may include: + * `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values + * `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255) +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: Generate string UUID with predefined `random` values + +```javascript --run v4 +const v4options = { + random: [ + 0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, + 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36 + ] +}; +uuidv4(v4options); // RESULT +``` + +Example: Generate two IDs in a single buffer + +```javascript --run v4 +const buffer = new Array(); +uuidv4(null, buffer, 0); // RESULT +uuidv4(null, buffer, 16); // RESULT +``` + +### Version 5 + +```javascript +const uuidv5 = require('uuid/v5'); + +// Incantations +uuidv5(name, namespace); +uuidv5(name, namespace, buffer); +uuidv5(name, namespace, buffer, offset); +``` + +Generate and return a RFC4122 v5 UUID. + +* `name` - (String | Array[]) "name" to create UUID with +* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values +* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written. +* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0 + +Returns `buffer`, if specified, otherwise the string form of the UUID + +Example: + +```javascript --run v5 +uuidv5('hello world', MY_NAMESPACE); // RESULT +``` + +## Command Line + +UUIDs can be generated from the command line with the `uuid` command. + +```shell +$ uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 + +$ uuid v1 +02d37060-d446-11e7-a9fa-7bdae751ebe1 +``` + +Type `uuid --help` for usage details + +## Testing + +```shell +npm test +``` diff --git a/node_modules/uuid/bin/uuid b/node_modules/uuid/bin/uuid new file mode 100644 index 00000000..502626e6 --- /dev/null +++ b/node_modules/uuid/bin/uuid @@ -0,0 +1,65 @@ +#!/usr/bin/env node +var assert = require('assert'); + +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122'); +} + +var args = process.argv.slice(2); + +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +var version = args.shift() || 'v4'; + +switch (version) { + case 'v1': + var uuidV1 = require('../v1'); + console.log(uuidV1()); + break; + + case 'v3': + var uuidV3 = require('../v3'); + + var name = args.shift(); + var namespace = args.shift(); + assert(name != null, 'v3 name not specified'); + assert(namespace != null, 'v3 namespace not specified'); + + if (namespace == 'URL') namespace = uuidV3.URL; + if (namespace == 'DNS') namespace = uuidV3.DNS; + + console.log(uuidV3(name, namespace)); + break; + + case 'v4': + var uuidV4 = require('../v4'); + console.log(uuidV4()); + break; + + case 'v5': + var uuidV5 = require('../v5'); + + var name = args.shift(); + var namespace = args.shift(); + assert(name != null, 'v5 name not specified'); + assert(namespace != null, 'v5 namespace not specified'); + + if (namespace == 'URL') namespace = uuidV5.URL; + if (namespace == 'DNS') namespace = uuidV5.DNS; + + console.log(uuidV5(name, namespace)); + break; + + default: + usage(); + process.exit(1); +} diff --git a/node_modules/uuid/index.js b/node_modules/uuid/index.js new file mode 100644 index 00000000..e96791ab --- /dev/null +++ b/node_modules/uuid/index.js @@ -0,0 +1,8 @@ +var v1 = require('./v1'); +var v4 = require('./v4'); + +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; + +module.exports = uuid; diff --git a/node_modules/uuid/lib/bytesToUuid.js b/node_modules/uuid/lib/bytesToUuid.js new file mode 100644 index 00000000..847c4828 --- /dev/null +++ b/node_modules/uuid/lib/bytesToUuid.js @@ -0,0 +1,24 @@ +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} + +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4 + return ([bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], '-', + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]], + bth[buf[i++]], bth[buf[i++]]]).join(''); +} + +module.exports = bytesToUuid; diff --git a/node_modules/uuid/lib/md5-browser.js b/node_modules/uuid/lib/md5-browser.js new file mode 100644 index 00000000..9b3b6c7e --- /dev/null +++ b/node_modules/uuid/lib/md5-browser.js @@ -0,0 +1,216 @@ +/* + * Browser-compatible JavaScript MD5 + * + * Modification of JavaScript MD5 + * https://github.com/blueimp/JavaScript-MD5 + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * https://opensource.org/licenses/MIT + * + * Based on + * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message + * Digest Algorithm, as defined in RFC 1321. + * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 + * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet + * Distributed under the BSD License + * See http://pajhome.org.uk/crypt/md5 for more info. + */ + +'use strict'; + +function md5(bytes) { + if (typeof(bytes) == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + bytes = new Array(msg.length); + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); + } + + return md5ToHexEncodedArray( + wordsToMd5( + bytesToWords(bytes) + , bytes.length * 8) + ); +} + + +/* +* Convert an array of little-endian words to an array of bytes +*/ +function md5ToHexEncodedArray(input) { + var i; + var x; + var output = []; + var length32 = input.length * 32; + var hexTab = '0123456789abcdef'; + var hex; + + for (i = 0; i < length32; i += 8) { + x = (input[i >> 5] >>> (i % 32)) & 0xFF; + + hex = parseInt(hexTab.charAt((x >>> 4) & 0x0F) + hexTab.charAt(x & 0x0F), 16); + + output.push(hex); + } + return output; +} + +/* +* Calculate the MD5 of an array of little-endian words, and a bit length. +*/ +function wordsToMd5(x, len) { + /* append padding */ + x[len >> 5] |= 0x80 << (len % 32); + x[(((len + 64) >>> 9) << 4) + 14] = len; + + var i; + var olda; + var oldb; + var oldc; + var oldd; + var a = 1732584193; + var b = -271733879; + var c = -1732584194; + + var d = 271733878; + + for (i = 0; i < x.length; i += 16) { + olda = a; + oldb = b; + oldc = c; + oldd = d; + + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return [a, b, c, d]; +} + +/* +* Convert an array bytes to an array of little-endian words +* Characters >255 have their high-byte silently ignored. +*/ +function bytesToWords(input) { + var i; + var output = []; + output[(input.length >> 2) - 1] = undefined; + for (i = 0; i < output.length; i += 1) { + output[i] = 0; + } + var length8 = input.length * 8; + for (i = 0; i < length8; i += 8) { + output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32); + } + + return output; +} + +/* +* Add integers, wrapping at 2^32. This uses 16-bit operations internally +* to work around bugs in some JS interpreters. +*/ +function safeAdd(x, y) { + var lsw = (x & 0xFFFF) + (y & 0xFFFF); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xFFFF); +} + +/* +* Bitwise rotate a 32-bit number to the left. +*/ +function bitRotateLeft(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); +} + +/* +* These functions implement the four basic operations the algorithm uses. +*/ +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} +function md5ff(a, b, c, d, x, s, t) { + return md5cmn((b & c) | ((~b) & d), a, b, x, s, t); +} +function md5gg(a, b, c, d, x, s, t) { + return md5cmn((b & d) | (c & (~d)), a, b, x, s, t); +} +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | (~d)), a, b, x, s, t); +} + +module.exports = md5; diff --git a/node_modules/uuid/lib/md5.js b/node_modules/uuid/lib/md5.js new file mode 100644 index 00000000..7044b872 --- /dev/null +++ b/node_modules/uuid/lib/md5.js @@ -0,0 +1,25 @@ +'use strict'; + +var crypto = require('crypto'); + +function md5(bytes) { + if (typeof Buffer.from === 'function') { + // Modern Buffer API + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + } else { + // Pre-v4 Buffer API + if (Array.isArray(bytes)) { + bytes = new Buffer(bytes); + } else if (typeof bytes === 'string') { + bytes = new Buffer(bytes, 'utf8'); + } + } + + return crypto.createHash('md5').update(bytes).digest(); +} + +module.exports = md5; diff --git a/node_modules/uuid/lib/rng-browser.js b/node_modules/uuid/lib/rng-browser.js new file mode 100644 index 00000000..6361fb81 --- /dev/null +++ b/node_modules/uuid/lib/rng-browser.js @@ -0,0 +1,34 @@ +// Unique ID creation requires a high quality random # generator. In the +// browser this is a little complicated due to unknown quality of Math.random() +// and inconsistent support for the `crypto` API. We do the best we can via +// feature-detection + +// getRandomValues needs to be invoked in a context where "this" is a Crypto +// implementation. Also, find the complete implementation of crypto on IE11. +var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) || + (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto)); + +if (getRandomValues) { + // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto + var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef + + module.exports = function whatwgRNG() { + getRandomValues(rnds8); + return rnds8; + }; +} else { + // Math.random()-based (RNG) + // + // If all else fails, use Math.random(). It's fast, but is of unspecified + // quality. + var rnds = new Array(16); + + module.exports = function mathRNG() { + for (var i = 0, r; i < 16; i++) { + if ((i & 0x03) === 0) r = Math.random() * 0x100000000; + rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; + } + + return rnds; + }; +} diff --git a/node_modules/uuid/lib/rng.js b/node_modules/uuid/lib/rng.js new file mode 100644 index 00000000..58f0dc9c --- /dev/null +++ b/node_modules/uuid/lib/rng.js @@ -0,0 +1,8 @@ +// Unique ID creation requires a high quality random # generator. In node.js +// this is pretty straight-forward - we use the crypto API. + +var crypto = require('crypto'); + +module.exports = function nodeRNG() { + return crypto.randomBytes(16); +}; diff --git a/node_modules/uuid/lib/sha1-browser.js b/node_modules/uuid/lib/sha1-browser.js new file mode 100644 index 00000000..5758ed75 --- /dev/null +++ b/node_modules/uuid/lib/sha1-browser.js @@ -0,0 +1,89 @@ +// Adapted from Chris Veness' SHA1 code at +// http://www.movable-type.co.uk/scripts/sha1.html +'use strict'; + +function f(s, x, y, z) { + switch (s) { + case 0: return (x & y) ^ (~x & z); + case 1: return x ^ y ^ z; + case 2: return (x & y) ^ (x & z) ^ (y & z); + case 3: return x ^ y ^ z; + } +} + +function ROTL(x, n) { + return (x << n) | (x>>> (32 - n)); +} + +function sha1(bytes) { + var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + + if (typeof(bytes) == 'string') { + var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape + bytes = new Array(msg.length); + for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i); + } + + bytes.push(0x80); + + var l = bytes.length/4 + 2; + var N = Math.ceil(l/16); + var M = new Array(N); + + for (var i=0; i>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + + H[0] = (H[0] + a) >>> 0; + H[1] = (H[1] + b) >>> 0; + H[2] = (H[2] + c) >>> 0; + H[3] = (H[3] + d) >>> 0; + H[4] = (H[4] + e) >>> 0; + } + + return [ + H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, + H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, + H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, + H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, + H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff + ]; +} + +module.exports = sha1; diff --git a/node_modules/uuid/lib/sha1.js b/node_modules/uuid/lib/sha1.js new file mode 100644 index 00000000..0b54b250 --- /dev/null +++ b/node_modules/uuid/lib/sha1.js @@ -0,0 +1,25 @@ +'use strict'; + +var crypto = require('crypto'); + +function sha1(bytes) { + if (typeof Buffer.from === 'function') { + // Modern Buffer API + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + } else { + // Pre-v4 Buffer API + if (Array.isArray(bytes)) { + bytes = new Buffer(bytes); + } else if (typeof bytes === 'string') { + bytes = new Buffer(bytes, 'utf8'); + } + } + + return crypto.createHash('sha1').update(bytes).digest(); +} + +module.exports = sha1; diff --git a/node_modules/uuid/lib/v35.js b/node_modules/uuid/lib/v35.js new file mode 100644 index 00000000..8b066cc5 --- /dev/null +++ b/node_modules/uuid/lib/v35.js @@ -0,0 +1,57 @@ +var bytesToUuid = require('./bytesToUuid'); + +function uuidToBytes(uuid) { + // Note: We assume we're being passed a valid uuid string + var bytes = []; + uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) { + bytes.push(parseInt(hex, 16)); + }); + + return bytes; +} + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + var bytes = new Array(str.length); + for (var i = 0; i < str.length; i++) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} + +module.exports = function(name, version, hashfunc) { + var generateUUID = function(value, namespace, buf, offset) { + var off = buf && offset || 0; + + if (typeof(value) == 'string') value = stringToBytes(value); + if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace); + + if (!Array.isArray(value)) throw TypeError('value must be an array of bytes'); + if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values'); + + // Per 4.3 + var bytes = hashfunc(namespace.concat(value)); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + + if (buf) { + for (var idx = 0; idx < 16; ++idx) { + buf[off+idx] = bytes[idx]; + } + } + + return buf || bytesToUuid(bytes); + }; + + // Function#name is not settable on some platforms (#270) + try { + generateUUID.name = name; + } catch (err) { + } + + // Pre-defined namespaces, per Appendix C + generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; + generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; + + return generateUUID; +}; diff --git a/node_modules/uuid/package.json b/node_modules/uuid/package.json new file mode 100644 index 00000000..2a8b8520 --- /dev/null +++ b/node_modules/uuid/package.json @@ -0,0 +1,98 @@ +{ + "_args": [ + [ + "uuid@3.3.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "uuid@3.3.2", + "_id": "uuid@3.3.2", + "_inBundle": false, + "_integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", + "_location": "/uuid", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "uuid@3.3.2", + "name": "uuid", + "escapedName": "uuid", + "rawSpec": "3.3.2", + "saveSpec": null, + "fetchSpec": "3.3.2" + }, + "_requiredBy": [ + "/" + ], + "_resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", + "_spec": "3.3.2", + "_where": "C:\\GitHub\\cis411_lab0", + "bin": { + "uuid": "./bin/uuid" + }, + "browser": { + "./lib/rng.js": "./lib/rng-browser.js", + "./lib/sha1.js": "./lib/sha1-browser.js", + "./lib/md5.js": "./lib/md5-browser.js" + }, + "bugs": { + "url": "https://github.com/kelektiv/node-uuid/issues" + }, + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "contributors": [ + { + "name": "Robert Kieffer", + "email": "robert@broofa.com" + }, + { + "name": "Christoph Tavan", + "email": "dev@tavan.de" + }, + { + "name": "AJ ONeal", + "email": "coolaj86@gmail.com" + }, + { + "name": "Vincent Voyer", + "email": "vincent@zeroload.net" + }, + { + "name": "Roman Shtylman", + "email": "shtylman@gmail.com" + } + ], + "description": "RFC4122 (v1, v4, and v5) UUIDs", + "devDependencies": { + "@commitlint/cli": "7.0.0", + "@commitlint/config-conventional": "7.0.1", + "eslint": "4.19.1", + "husky": "0.14.3", + "mocha": "5.2.0", + "runmd": "1.0.1", + "standard-version": "4.4.0" + }, + "homepage": "https://github.com/kelektiv/node-uuid#readme", + "keywords": [ + "uuid", + "guid", + "rfc4122" + ], + "license": "MIT", + "name": "uuid", + "repository": { + "type": "git", + "url": "git+https://github.com/kelektiv/node-uuid.git" + }, + "scripts": { + "commitmsg": "commitlint -E GIT_PARAMS", + "md": "runmd --watch --output=README.md README_js.md", + "prepare": "runmd --output=README.md README_js.md", + "release": "standard-version", + "test": "mocha test/test.js" + }, + "version": "3.3.2" +} diff --git a/node_modules/uuid/v1.js b/node_modules/uuid/v1.js new file mode 100644 index 00000000..d84c0f45 --- /dev/null +++ b/node_modules/uuid/v1.js @@ -0,0 +1,109 @@ +var rng = require('./lib/rng'); +var bytesToUuid = require('./lib/bytesToUuid'); + +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +var _nodeId; +var _clockseq; + +// Previous uuid creation time +var _lastMSecs = 0; +var _lastNSecs = 0; + +// See https://github.com/broofa/node-uuid for API details +function v1(options, buf, offset) { + var i = buf && offset || 0; + var b = buf || []; + + options = options || {}; + var node = options.node || _nodeId; + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; + + // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + if (node == null || clockseq == null) { + var seedBytes = rng(); + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [ + seedBytes[0] | 0x01, + seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5] + ]; + } + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } + + // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); + } + + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (var n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + + return buf ? buf : bytesToUuid(b); +} + +module.exports = v1; diff --git a/node_modules/uuid/v3.js b/node_modules/uuid/v3.js new file mode 100644 index 00000000..ee7e14c0 --- /dev/null +++ b/node_modules/uuid/v3.js @@ -0,0 +1,4 @@ +var v35 = require('./lib/v35.js'); +var md5 = require('./lib/md5'); + +module.exports = v35('v3', 0x30, md5); \ No newline at end of file diff --git a/node_modules/uuid/v4.js b/node_modules/uuid/v4.js new file mode 100644 index 00000000..1f07be1c --- /dev/null +++ b/node_modules/uuid/v4.js @@ -0,0 +1,29 @@ +var rng = require('./lib/rng'); +var bytesToUuid = require('./lib/bytesToUuid'); + +function v4(options, buf, offset) { + var i = buf && offset || 0; + + if (typeof(options) == 'string') { + buf = options === 'binary' ? new Array(16) : null; + options = null; + } + options = options || {}; + + var rnds = options.random || (options.rng || rng)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + for (var ii = 0; ii < 16; ++ii) { + buf[i + ii] = rnds[ii]; + } + } + + return buf || bytesToUuid(rnds); +} + +module.exports = v4; diff --git a/node_modules/uuid/v5.js b/node_modules/uuid/v5.js new file mode 100644 index 00000000..4945baf3 --- /dev/null +++ b/node_modules/uuid/v5.js @@ -0,0 +1,3 @@ +var v35 = require('./lib/v35.js'); +var sha1 = require('./lib/sha1'); +module.exports = v35('v5', 0x50, sha1); diff --git a/node_modules/vary/HISTORY.md b/node_modules/vary/HISTORY.md new file mode 100644 index 00000000..f6cbcf7f --- /dev/null +++ b/node_modules/vary/HISTORY.md @@ -0,0 +1,39 @@ +1.1.2 / 2017-09-23 +================== + + * perf: improve header token parsing speed + +1.1.1 / 2017-03-20 +================== + + * perf: hoist regular expression + +1.1.0 / 2015-09-29 +================== + + * Only accept valid field names in the `field` argument + - Ensures the resulting string is a valid HTTP header value + +1.0.1 / 2015-07-08 +================== + + * Fix setting empty header from empty `field` + * perf: enable strict mode + * perf: remove argument reassignments + +1.0.0 / 2014-08-10 +================== + + * Accept valid `Vary` header string as `field` + * Add `vary.append` for low-level string manipulation + * Move to `jshttp` orgainzation + +0.1.0 / 2014-06-05 +================== + + * Support array of fields to set + +0.0.0 / 2014-06-04 +================== + + * Initial release diff --git a/node_modules/vary/LICENSE b/node_modules/vary/LICENSE new file mode 100644 index 00000000..84441fbb --- /dev/null +++ b/node_modules/vary/LICENSE @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2014-2017 Douglas Christopher Wilson + +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/vary/README.md b/node_modules/vary/README.md new file mode 100644 index 00000000..cc000b34 --- /dev/null +++ b/node_modules/vary/README.md @@ -0,0 +1,101 @@ +# vary + +[![NPM Version][npm-image]][npm-url] +[![NPM Downloads][downloads-image]][downloads-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][travis-image]][travis-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +Manipulate the HTTP Vary header + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install vary +``` + +## API + + + +```js +var vary = require('vary') +``` + +### vary(res, field) + +Adds the given header `field` to the `Vary` response header of `res`. +This can be a string of a single field, a string of a valid `Vary` +header, or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. + + + +```js +// Append "Origin" to the Vary header of the response +vary(res, 'Origin') +``` + +### vary.append(header, field) + +Adds the given header `field` to the `Vary` response header string `header`. +This can be a string of a single field, a string of a valid `Vary` header, +or an array of multiple fields. + +This will append the header if not already listed, otherwise leaves +it listed in the current location. The new header string is returned. + + + +```js +// Get header string appending "Origin" to "Accept, User-Agent" +vary.append('Accept, User-Agent', 'Origin') +``` + +## Examples + +### Updating the Vary header when content is based on it + +```js +var http = require('http') +var vary = require('vary') + +http.createServer(function onRequest (req, res) { + // about to user-agent sniff + vary(res, 'User-Agent') + + var ua = req.headers['user-agent'] || '' + var isMobile = /mobi|android|touch|mini/i.test(ua) + + // serve site, depending on isMobile + res.setHeader('Content-Type', 'text/html') + res.end('You are (probably) ' + (isMobile ? '' : 'not ') + 'a mobile user') +}) +``` + +## Testing + +```sh +$ npm test +``` + +## License + +[MIT](LICENSE) + +[npm-image]: https://img.shields.io/npm/v/vary.svg +[npm-url]: https://npmjs.org/package/vary +[node-version-image]: https://img.shields.io/node/v/vary.svg +[node-version-url]: https://nodejs.org/en/download +[travis-image]: https://img.shields.io/travis/jshttp/vary/master.svg +[travis-url]: https://travis-ci.org/jshttp/vary +[coveralls-image]: https://img.shields.io/coveralls/jshttp/vary/master.svg +[coveralls-url]: https://coveralls.io/r/jshttp/vary +[downloads-image]: https://img.shields.io/npm/dm/vary.svg +[downloads-url]: https://npmjs.org/package/vary diff --git a/node_modules/vary/index.js b/node_modules/vary/index.js new file mode 100644 index 00000000..5b5e7412 --- /dev/null +++ b/node_modules/vary/index.js @@ -0,0 +1,149 @@ +/*! + * vary + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module exports. + */ + +module.exports = vary +module.exports.append = append + +/** + * RegExp to match field-name in RFC 7230 sec 3.2 + * + * field-name = token + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + */ + +var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/ + +/** + * Append a field to a vary header. + * + * @param {String} header + * @param {String|Array} field + * @return {String} + * @public + */ + +function append (header, field) { + if (typeof header !== 'string') { + throw new TypeError('header argument is required') + } + + if (!field) { + throw new TypeError('field argument is required') + } + + // get fields array + var fields = !Array.isArray(field) + ? parse(String(field)) + : field + + // assert on invalid field names + for (var j = 0; j < fields.length; j++) { + if (!FIELD_NAME_REGEXP.test(fields[j])) { + throw new TypeError('field argument contains an invalid header name') + } + } + + // existing, unspecified vary + if (header === '*') { + return header + } + + // enumerate current values + var val = header + var vals = parse(header.toLowerCase()) + + // unspecified vary + if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) { + return '*' + } + + for (var i = 0; i < fields.length; i++) { + var fld = fields[i].toLowerCase() + + // append value (case-preserving) + if (vals.indexOf(fld) === -1) { + vals.push(fld) + val = val + ? val + ', ' + fields[i] + : fields[i] + } + } + + return val +} + +/** + * Parse a vary header into an array. + * + * @param {String} header + * @return {Array} + * @private + */ + +function parse (header) { + var end = 0 + var list = [] + var start = 0 + + // gather tokens + for (var i = 0, len = header.length; i < len; i++) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(header.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break + } + } + + // final token + list.push(header.substring(start, end)) + + return list +} + +/** + * Mark that a request is varied on a header field. + * + * @param {Object} res + * @param {String|Array} field + * @public + */ + +function vary (res, field) { + if (!res || !res.getHeader || !res.setHeader) { + // quack quack + throw new TypeError('res argument is required') + } + + // get existing header + var val = res.getHeader('Vary') || '' + var header = Array.isArray(val) + ? val.join(', ') + : String(val) + + // set new header + if ((val = append(header, field))) { + res.setHeader('Vary', val) + } +} diff --git a/node_modules/vary/package.json b/node_modules/vary/package.json new file mode 100644 index 00000000..f8fe63b8 --- /dev/null +++ b/node_modules/vary/package.json @@ -0,0 +1,81 @@ +{ + "_args": [ + [ + "vary@1.1.2", + "C:\\GitHub\\cis411_lab0" + ] + ], + "_from": "vary@1.1.2", + "_id": "vary@1.1.2", + "_inBundle": false, + "_integrity": "sha1-IpnwLG3tMNSllhsLn3RSShj2NPw=", + "_location": "/vary", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "vary@1.1.2", + "name": "vary", + "escapedName": "vary", + "rawSpec": "1.1.2", + "saveSpec": null, + "fetchSpec": "1.1.2" + }, + "_requiredBy": [ + "/express" + ], + "_resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "_spec": "1.1.2", + "_where": "C:\\GitHub\\cis411_lab0", + "author": { + "name": "Douglas Christopher Wilson", + "email": "doug@somethingdoug.com" + }, + "bugs": { + "url": "https://github.com/jshttp/vary/issues" + }, + "description": "Manipulate the HTTP Vary header", + "devDependencies": { + "beautify-benchmark": "0.2.4", + "benchmark": "2.1.4", + "eslint": "3.19.0", + "eslint-config-standard": "10.2.1", + "eslint-plugin-import": "2.7.0", + "eslint-plugin-markdown": "1.0.0-beta.6", + "eslint-plugin-node": "5.1.1", + "eslint-plugin-promise": "3.5.0", + "eslint-plugin-standard": "3.0.1", + "istanbul": "0.4.5", + "mocha": "2.5.3", + "supertest": "1.1.0" + }, + "engines": { + "node": ">= 0.8" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "index.js" + ], + "homepage": "https://github.com/jshttp/vary#readme", + "keywords": [ + "http", + "res", + "vary" + ], + "license": "MIT", + "name": "vary", + "repository": { + "type": "git", + "url": "git+https://github.com/jshttp/vary.git" + }, + "scripts": { + "bench": "node benchmark/index.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/", + "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/" + }, + "version": "1.1.2" +} diff --git a/test.json b/test.json new file mode 100644 index 00000000..4b3d00da --- /dev/null +++ b/test.json @@ -0,0 +1 @@ +{"filename":"test.json","collections":[{"name":"orders","data":[],"idIndex":[],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"orders","dirty":false,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableMeta":false,"disableChangesApi":true,"disableDeltaChangesApi":true,"autoupdate":false,"serializableIndices":true,"ttl":null,"maxId":0,"DynamicViews":[],"events":{"insert":[],"update":[],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]},{"name":"accounts","data":[{"email":"wn1154@messiah.edu","name":"Will Newcomb","mutation":"add","id":"9e6928b4-cadf-4d1b-b927-836234b913af","meta":{"revision":0,"created":1582686314115,"version":0},"$loki":1}],"idIndex":[1],"binaryIndices":{},"constraints":null,"uniqueNames":[],"transforms":{},"objType":"accounts","dirty":false,"cachedIndex":null,"cachedBinaryIndex":null,"cachedData":null,"adaptiveBinaryIndices":true,"transactional":false,"cloneObjects":false,"cloneMethod":"parse-stringify","asyncListeners":false,"disableMeta":false,"disableChangesApi":true,"disableDeltaChangesApi":true,"autoupdate":false,"serializableIndices":true,"ttl":null,"maxId":1,"DynamicViews":[],"events":{"insert":[],"update":[],"pre-insert":[],"pre-update":[],"close":[],"flushbuffer":[],"error":[],"delete":[null],"warning":[null]},"changes":[]}],"databaseVersion":1.5,"engineVersion":1.5,"autosave":true,"autosaveInterval":4000,"autosaveHandle":null,"throttledSaves":true,"options":{"autoload":true,"autosave":true,"autosaveInterval":4000,"serializationMethod":"normal","destructureDelimiter":"$<\n","recursiveWait":true,"recursiveWaitLimit":false,"recursiveWaitLimitDuration":2000,"started":1582686279108},"persistenceMethod":"fs","persistenceAdapter":null,"verbose":false,"events":{"init":[null],"loaded":[],"flushChanges":[],"close":[],"changes":[],"warning":[]},"ENV":"NODEJS"} \ No newline at end of file