flow like the river

This commit is contained in:
root 2025-11-07 00:06:12 +01:00
commit 013fe673f3
42435 changed files with 5764238 additions and 0 deletions

21
VISUALIZACION/node_modules/express-graphql/LICENSE generated vendored Executable file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) GraphQL 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.

369
VISUALIZACION/node_modules/express-graphql/README.md generated vendored Executable file
View file

@ -0,0 +1,369 @@
# GraphQL HTTP Server Middleware
[![npm version](https://badge.fury.io/js/express-graphql.svg)](https://badge.fury.io/js/express-graphql)
[![Build Status](https://github.com/graphql/express-graphql/workflows/CI/badge.svg?branch=master)](https://github.com/graphql/express-graphql/actions?query=branch%3Amaster)
[![Coverage Status](https://codecov.io/gh/graphql/express-graphql/branch/master/graph/badge.svg)](https://codecov.io/gh/graphql/express-graphql)
Create a GraphQL HTTP server with any HTTP web framework that supports connect styled middleware, including [Connect](https://github.com/senchalabs/connect) itself, [Express](https://expressjs.com) and [Restify](http://restify.com/).
## Installation
```sh
npm install --save express-graphql
```
### TypeScript
This module includes a [TypeScript](https://www.typescriptlang.org/)
declaration file to enable auto complete in compatible editors and type
information for TypeScript projects.
## 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.
Alternatively, instead of `true` you can pass in an options object:
- **`defaultQuery`**: An optional GraphQL string to use when no query
is provided and no stored query exists from a previous session.
If undefined is provided, GraphiQL will use its own default query.
- **`headerEditorEnabled`**: An optional boolean which enables the header editor when true.
Defaults to false.
- **`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#L119).
- **`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#L120). If `context` is not provided, the
`request` object is passed as the context.
- **`pretty`**: If `true`, any JSON response will be pretty-printed.
- **`extensions`**: An optional function for adding additional metadata to the
GraphQL response as a key-value object. The result will be added to the
`"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, context }`.
- **`validationRules`**: Optional additional validation rules queries must
satisfy in addition to those defined by the GraphQL spec.
- **`customValidateFn`**: An optional function which will be used to validate
instead of default `validate` from `graphql-js`.
- **`customExecuteFn`**: An optional function which will be used to execute
instead of default `execute` from `graphql-js`.
- **`customFormatErrorFn`**: 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.
- **`customParseFn`**: An optional function which will be used to create a document
instead of the default `parse` from `graphql-js`.
- **`formatError`**: is deprecated and replaced by `customFormatErrorFn`. It will be
removed in version 1.0.0.
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 query string of a URL:
```
/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, context }`
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 } }));
const extensions = ({
document,
variables,
operationName,
result,
context,
}) => {
return {
runTime: Date.now() - context.startTime,
};
};
app.use(
'/graphql',
graphqlHTTP((request) => {
return {
schema: MyGraphQLSchema,
context: { startTime: Date.now() },
graphiql: true,
extensions,
};
}),
);
```
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://graphql.github.io/graphql-spec/#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 field name `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`,
),
);
}
},
};
}
```
### Disabling introspection
Disabling introspection does not reflect best practices and does not necessarily make your
application any more secure. Nevertheless, disabling introspection is possible by utilizing the
`NoSchemaIntrospectionCustomRule` provided by the [graphql-js](https://github.com/graphql/graphql-js)
package.
```js
import { specifiedRules, NoSchemaIntrospectionCustomRule } from 'graphql';
app.use(
'/graphql',
graphqlHTTP((request) => {
return {
schema: MyGraphQLSchema,
validationRules: [...specifiedRules, NoSchemaIntrospectionCustomRule],
};
}),
);
```
## Other Exports
**`getGraphQLParams(request: Request): Promise<GraphQLParams>`**
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 { getGraphQLParams } = require('express-graphql');
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 `customFormatErrorFn` enables this:
```js
customFormatErrorFn: (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

146
VISUALIZACION/node_modules/express-graphql/index.d.ts generated vendored Executable file
View file

@ -0,0 +1,146 @@
/// <reference types="node" />
import type { IncomingMessage, ServerResponse } from 'http';
import type { ASTVisitor, DocumentNode, ValidationRule, ValidationContext, ExecutionArgs, ExecutionResult, FormattedExecutionResult, GraphQLSchema, GraphQLFieldResolver, GraphQLTypeResolver, GraphQLFormattedError } from 'graphql';
import { Source, GraphQLError } from 'graphql';
import type { GraphiQLOptions } from './renderGraphiQL';
declare type Request = IncomingMessage & {
url: string;
};
declare type Response = ServerResponse & {
json?: (data: unknown) => void;
};
declare type MaybePromise<T> = Promise<T> | T;
/**
* 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 declare type Options = ((request: Request, response: Response, params?: GraphQLParams) => MaybePromise<OptionsData>) | MaybePromise<OptionsData>;
export interface OptionsData {
/**
* A GraphQL schema from graphql-js.
*/
schema: GraphQLSchema;
/**
* A value to pass as the context to this middleware.
*/
context?: unknown;
/**
* An object to pass as the rootValue to the graphql() function.
*/
rootValue?: unknown;
/**
* A boolean to configure whether the output should be pretty-printed.
*/
pretty?: boolean;
/**
* An optional array of validation rules that will be applied on the document
* in additional to those defined by the GraphQL spec.
*/
validationRules?: ReadonlyArray<(ctx: ValidationContext) => ASTVisitor>;
/**
* An optional function which will be used to validate instead of default `validate`
* from `graphql-js`.
*/
customValidateFn?: (schema: GraphQLSchema, documentAST: DocumentNode, rules: ReadonlyArray<ValidationRule>) => ReadonlyArray<GraphQLError>;
/**
* An optional function which will be used to execute instead of default `execute`
* from `graphql-js`.
*/
customExecuteFn?: (args: ExecutionArgs) => MaybePromise<ExecutionResult>;
/**
* 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.
*/
customFormatErrorFn?: (error: GraphQLError) => GraphQLFormattedError;
/**
* An optional function which will be used to create a document instead of
* the default `parse` from `graphql-js`.
*/
customParseFn?: (source: Source) => DocumentNode;
/**
* `formatError` is deprecated and replaced by `customFormatErrorFn`. It will
* be removed in version 1.0.0.
*/
formatError?: (error: GraphQLError) => GraphQLFormattedError;
/**
* 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) => MaybePromise<undefined | {
[key: string]: unknown;
}>;
/**
* A boolean to optionally enable GraphiQL mode.
* Alternatively, instead of `true` you can pass in an options object.
*/
graphiql?: boolean | GraphiQLOptions;
/**
* 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).
*/
fieldResolver?: GraphQLFieldResolver<unknown, unknown>;
/**
* A type resolver function to use when none is provided by the schema.
* If not provided, the default type resolver is used (which looks for a
* `__typename` field or alternatively calls the `isTypeOf` method).
*/
typeResolver?: GraphQLTypeResolver<unknown, unknown>;
}
/**
* All information about a GraphQL request.
*/
export interface RequestInfo {
/**
* The parsed GraphQL document.
*/
document: DocumentNode;
/**
* The variable values used at runtime.
*/
variables: {
readonly [name: string]: unknown;
} | null;
/**
* The (optional) operation name requested.
*/
operationName: string | null;
/**
* The result of executing the operation.
*/
result: FormattedExecutionResult;
/**
* A value to pass as the context to the graphql() function.
*/
context?: unknown;
}
declare type Middleware = (request: Request, response: Response) => Promise<void>;
/**
* Middleware for express; takes an options object or function as input to
* configure behavior, and returns an express middleware.
*/
export declare function graphqlHTTP(options: Options): Middleware;
export interface GraphQLParams {
query: string | null;
variables: {
readonly [name: string]: unknown;
} | null;
operationName: string | null;
raw: boolean;
}
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the GraphQL request parameters.
*/
export declare function getGraphQLParams(request: Request): Promise<GraphQLParams>;
export {};

285
VISUALIZACION/node_modules/express-graphql/index.js generated vendored Executable file
View file

@ -0,0 +1,285 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getGraphQLParams = exports.graphqlHTTP = void 0;
const accepts_1 = __importDefault(require("accepts"));
const http_errors_1 = __importDefault(require("http-errors"));
const graphql_1 = require("graphql");
const parseBody_1 = require("./parseBody");
const renderGraphiQL_1 = require("./renderGraphiQL");
/**
* Middleware for express; takes an options object or function as input to
* configure behavior, and returns an express middleware.
*/
function graphqlHTTP(options) {
devAssert(options != null, 'GraphQL middleware requires options.');
return async function graphqlMiddleware(request, response) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
// Higher scoped variables are referred to at various stages in the asynchronous state machine below.
let params;
let showGraphiQL = false;
let graphiqlOptions;
let formatErrorFn = graphql_1.formatError;
let pretty = false;
let result;
try {
// Parse the Request to get GraphQL request parameters.
try {
params = await getGraphQLParams(request);
}
catch (error) {
// When we failed to parse the GraphQL parameters, we still need to get
// the options object, so make an options call to resolve just that.
const optionsData = await resolveOptions();
pretty = (_a = optionsData.pretty) !== null && _a !== void 0 ? _a : false;
formatErrorFn = (_c = (_b = optionsData.customFormatErrorFn) !== null && _b !== void 0 ? _b : optionsData.formatError) !== null && _c !== void 0 ? _c : formatErrorFn;
throw error;
}
// Then, resolve the Options to get OptionsData.
const optionsData = await resolveOptions(params);
// Collect information from the options data object.
const schema = optionsData.schema;
const rootValue = optionsData.rootValue;
const validationRules = (_d = optionsData.validationRules) !== null && _d !== void 0 ? _d : [];
const fieldResolver = optionsData.fieldResolver;
const typeResolver = optionsData.typeResolver;
const graphiql = (_e = optionsData.graphiql) !== null && _e !== void 0 ? _e : false;
const extensionsFn = optionsData.extensions;
const context = (_f = optionsData.context) !== null && _f !== void 0 ? _f : request;
const parseFn = (_g = optionsData.customParseFn) !== null && _g !== void 0 ? _g : graphql_1.parse;
const executeFn = (_h = optionsData.customExecuteFn) !== null && _h !== void 0 ? _h : graphql_1.execute;
const validateFn = (_j = optionsData.customValidateFn) !== null && _j !== void 0 ? _j : graphql_1.validate;
pretty = (_k = optionsData.pretty) !== null && _k !== void 0 ? _k : false;
formatErrorFn = (_m = (_l = optionsData.customFormatErrorFn) !== null && _l !== void 0 ? _l : optionsData.formatError) !== null && _m !== void 0 ? _m : formatErrorFn;
// Assert that schema is required.
devAssert(schema != null, 'GraphQL middleware options must contain a schema.');
// GraphQL HTTP only supports GET and POST methods.
if (request.method !== 'GET' && request.method !== 'POST') {
throw http_errors_1.default(405, 'GraphQL only supports GET and POST requests.', {
headers: { Allow: 'GET, POST' },
});
}
// Get GraphQL params from the request and POST body data.
const { query, variables, operationName } = params;
showGraphiQL = canDisplayGraphiQL(request, params) && graphiql !== false;
if (typeof graphiql !== 'boolean') {
graphiqlOptions = graphiql;
}
// If there is no query, but GraphiQL will be displayed, do not produce
// a result, otherwise return a 400: Bad Request.
if (query == null) {
if (showGraphiQL) {
return respondWithGraphiQL(response, graphiqlOptions);
}
throw http_errors_1.default(400, 'Must provide query string.');
}
// Validate Schema
const schemaValidationErrors = graphql_1.validateSchema(schema);
if (schemaValidationErrors.length > 0) {
// Return 500: Internal Server Error if invalid schema.
throw http_errors_1.default(500, 'GraphQL schema validation error.', {
graphqlErrors: schemaValidationErrors,
});
}
// Parse source to AST, reporting any syntax error.
let documentAST;
try {
documentAST = parseFn(new graphql_1.Source(query, 'GraphQL request'));
}
catch (syntaxError) {
// Return 400: Bad Request if any syntax errors errors exist.
throw http_errors_1.default(400, 'GraphQL syntax error.', {
graphqlErrors: [syntaxError],
});
}
// Validate AST, reporting any errors.
const validationErrors = validateFn(schema, documentAST, [
...graphql_1.specifiedRules,
...validationRules,
]);
if (validationErrors.length > 0) {
// Return 400: Bad Request if any validation errors exist.
throw http_errors_1.default(400, 'GraphQL validation error.', {
graphqlErrors: 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 = graphql_1.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 respondWithGraphiQL(response, graphiqlOptions, params);
}
// Otherwise, report a 405: Method Not Allowed error.
throw http_errors_1.default(405, `Can only perform a ${operationAST.operation} operation from a POST request.`, { headers: { Allow: 'POST' } });
}
}
// Perform the execution, reporting any errors creating the context.
try {
result = await executeFn({
schema,
document: documentAST,
rootValue,
contextValue: context,
variableValues: variables,
operationName,
fieldResolver,
typeResolver,
});
}
catch (contextError) {
// Return 400: Bad Request if any execution context errors exist.
throw http_errors_1.default(400, 'GraphQL execution context error.', {
graphqlErrors: [contextError],
});
}
// Collect and apply any metadata extensions if a function was provided.
// https://graphql.github.io/graphql-spec/#sec-Response-Format
if (extensionsFn) {
const extensions = await extensionsFn({
document: documentAST,
variables,
operationName,
result,
context,
});
if (extensions != null) {
result = { ...result, extensions };
}
}
}
catch (rawError) {
// If an error was caught, report the httpError status, or 500.
const error = http_errors_1.default(500,
/* istanbul ignore next: Thrown by underlying library. */
rawError instanceof Error ? rawError : String(rawError));
response.statusCode = error.status;
const { headers } = error;
if (headers != null) {
for (const [key, value] of Object.entries(headers)) {
response.setHeader(key, String(value));
}
}
if (error.graphqlErrors == null) {
const graphqlError = new graphql_1.GraphQLError(error.message, undefined, undefined, undefined, undefined, error);
result = { data: undefined, errors: [graphqlError] };
}
else {
result = { data: undefined, errors: error.graphqlErrors };
}
}
// 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.
// https://graphql.github.io/graphql-spec/#sec-Data
if (response.statusCode === 200 && result.data == null) {
response.statusCode = 500;
}
// Format any encountered errors.
const formattedResult = {
...result,
errors: (_o = result.errors) === null || _o === void 0 ? void 0 : _o.map(formatErrorFn),
};
// If allowed to show GraphiQL, present it instead of JSON.
if (showGraphiQL) {
return respondWithGraphiQL(response, graphiqlOptions, params, formattedResult);
}
// 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(formattedResult);
}
else {
const payload = JSON.stringify(formattedResult, null, pretty ? 2 : 0);
sendResponse(response, 'application/json', payload);
}
async function resolveOptions(requestParams) {
const optionsResult = await Promise.resolve(typeof options === 'function'
? options(request, response, requestParams)
: options);
devAssert(optionsResult != null && typeof optionsResult === 'object', 'GraphQL middleware option function must return an options object or a promise which will be resolved to an options object.');
if (optionsResult.formatError) {
// eslint-disable-next-line no-console
console.warn('`formatError` is deprecated and replaced by `customFormatErrorFn`. It will be removed in version 1.0.0.');
}
return optionsResult;
}
};
}
exports.graphqlHTTP = graphqlHTTP;
function respondWithGraphiQL(response, options, params, result) {
const data = {
query: params === null || params === void 0 ? void 0 : params.query,
variables: params === null || params === void 0 ? void 0 : params.variables,
operationName: params === null || params === void 0 ? void 0 : params.operationName,
result,
};
const payload = renderGraphiQL_1.renderGraphiQL(data, options);
return sendResponse(response, 'text/html', payload);
}
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the GraphQL request parameters.
*/
async function getGraphQLParams(request) {
var _a, _b, _c;
const urlData = new URLSearchParams(request.url.split('?')[1]);
const bodyData = await parseBody_1.parseBody(request);
// GraphQL Query string.
let query = (_a = urlData.get('query')) !== null && _a !== void 0 ? _a : bodyData.query;
if (typeof query !== 'string') {
query = null;
}
// Parse the variables if needed.
let variables = ((_b = urlData.get('variables')) !== null && _b !== void 0 ? _b : bodyData.variables);
if (typeof variables === 'string') {
try {
variables = JSON.parse(variables);
}
catch (_d) {
throw http_errors_1.default(400, 'Variables are invalid JSON.');
}
}
else if (typeof variables !== 'object') {
variables = null;
}
// Name of GraphQL operation to execute.
let operationName = (_c = urlData.get('operationName')) !== null && _c !== void 0 ? _c : bodyData.operationName;
if (typeof operationName !== 'string') {
operationName = null;
}
const raw = urlData.get('raw') != null || bodyData.raw !== undefined;
return { query, variables, operationName, raw };
}
exports.getGraphQLParams = getGraphQLParams;
/**
* Helper function to determine if GraphiQL can be displayed.
*/
function canDisplayGraphiQL(request, params) {
// If `raw` false, 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_1.default(request).types(['json', 'html']) === 'html';
}
/**
* Helper function for sending a response using only the core Node server APIs.
*/
function sendResponse(response, type, data) {
const chunk = Buffer.from(data, 'utf8');
response.setHeader('Content-Type', type + '; charset=utf-8');
response.setHeader('Content-Length', String(chunk.length));
response.end(chunk);
}
function devAssert(condition, message) {
const booleanCondition = Boolean(condition);
if (!booleanCondition) {
throw new Error(message);
}
}

View file

@ -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

View file

@ -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.

View file

@ -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
<!-- eslint-disable no-unused-vars -->
```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.<anonymous> ([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/

View file

@ -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() || '<anonymous>'
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 = '<anonymous@' + formatLocation(site) + '>'
}
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
}

View file

@ -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')
}
}

View file

@ -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 || '<anonymous>')
}
} else if (isConstructor) {
line += 'new ' + (functionName || '<anonymous>')
} 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
}

View file

@ -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
}

View file

@ -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()
}

View file

@ -0,0 +1,41 @@
{
"name": "depd",
"description": "Deprecate all the things",
"version": "1.1.2",
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
"license": "MIT",
"keywords": [
"deprecate",
"deprecated"
],
"repository": "dougwilson/nodejs-depd",
"browser": "lib/browser/index.js",
"devDependencies": {
"benchmark": "2.1.4",
"beautify-benchmark": "0.2.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"
},
"files": [
"lib/",
"History.md",
"LICENSE",
"index.js",
"Readme.md"
],
"engines": {
"node": ">= 0.6"
},
"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/"
}
}

View file

@ -0,0 +1,160 @@
2020-06-29 / 1.8.0
==================
* Add `isHttpError` export to determine if value is an HTTP error
* deps: setprototypeof@1.2.0
2019-06-24 / 1.7.3
==================
* deps: inherits@2.0.4
2019-02-18 / 1.7.2
==================
* deps: setprototypeof@1.1.1
2018-09-08 / 1.7.1
==================
* Fix error creating objects in some environments
2018-07-30 / 1.7.0
==================
* Set constructor name when possible
* Use `toidentifier` module to make class names
* deps: statuses@'>= 1.5.0 < 2'
2018-03-29 / 1.6.3
==================
* deps: depd@~1.1.2
- perf: remove argument reassignment
* deps: setprototypeof@1.1.0
* deps: statuses@'>= 1.4.0 < 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

View file

@ -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.

View file

@ -0,0 +1,171 @@
# http-errors
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][node-url]
[![Node.js Version][node-image]][node-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.
### 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])
Create a new error object with the given message `msg`.
The error object inherits from `createError.HttpError`.
<!-- eslint-disable no-undef, no-unused-vars -->
```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
### createError([status], [error], [properties])
Extend the given `error` object with `createError.HttpError`
properties. This will not alter the inheritance of the given
`error` object, and the modified `error` object is the
return value.
<!-- eslint-disable no-redeclare, no-undef, no-unused-vars -->
```js
fs.readFile('foo.txt', function (err, buf) {
if (err) {
if (err.code === 'ENOENT') {
var httpError = createError(404, err, { expose: false })
} else {
var httpError = createError(500, err)
}
}
})
```
- `status` - the status code as a number
- `error` - the error object to extend
- `properties` - custom properties to attach to the object
### createError.isHttpError(val)
Determine if the provided `val` is an `HttpError`. This will return `true`
if the error inherits from the `HttpError` constructor of this module or
matches the "duck type" for an error this module creates. All outputs from
the `createError` factory will return `true` for this function, including
if an non-`HttpError` was passed into the factory.
### new createError\[code || name\](\[msg]\))
Create a new error object with the given message `msg`.
The error object inherits from `createError.HttpError`.
<!-- eslint-disable no-undef, no-unused-vars -->
```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)
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/http-errors/master
[coveralls-url]: https://coveralls.io/r/jshttp/http-errors?branch=master
[node-image]: https://badgen.net/npm/node/http-errors
[node-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/http-errors
[npm-url]: https://npmjs.org/package/http-errors
[npm-version-image]: https://badgen.net/npm/v/http-errors
[travis-image]: https://badgen.net/travis/jshttp/http-errors/master
[travis-url]: https://travis-ci.org/jshttp/http-errors

View file

@ -0,0 +1,299 @@
/*!
* 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')
var toIdentifier = require('toidentifier')
/**
* Module exports.
* @public
*/
module.exports = createError
module.exports.HttpError = createHttpErrorConstructor()
module.exports.isHttpError = createIsHttpErrorFunction(module.exports.HttpError)
// 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 = toClassName(name)
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)
nameFunc(ClientError, className)
ClientError.prototype.status = code
ClientError.prototype.statusCode = code
ClientError.prototype.expose = true
return ClientError
}
/**
* Create function to test is a value is a HttpError.
* @private
*/
function createIsHttpErrorFunction (HttpError) {
return function isHttpError (val) {
if (!val || typeof val !== 'object') {
return false
}
if (val instanceof HttpError) {
return true
}
return val instanceof Error &&
typeof val.expose === 'boolean' &&
typeof val.statusCode === 'number' && val.status === val.statusCode
}
}
/**
* Create a constructor for a server error.
* @private
*/
function createServerErrorConstructor (HttpError, name, code) {
var className = toClassName(name)
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)
nameFunc(ServerError, className)
ServerError.prototype.status = code
ServerError.prototype.statusCode = code
ServerError.prototype.expose = false
return ServerError
}
/**
* Set the name of a function, if possible.
* @private
*/
function nameFunc (func, name) {
var desc = Object.getOwnPropertyDescriptor(func, 'name')
if (desc && desc.configurable) {
desc.value = name
Object.defineProperty(func, 'name', desc)
}
}
/**
* 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')
}
/**
* Get a class name from a name identifier.
* @private
*/
function toClassName (name) {
return name.substr(-5) !== 'Error'
? name + 'Error'
: name
}

View file

@ -0,0 +1,49 @@
{
"name": "http-errors",
"description": "Create HTTP error objects",
"version": "1.8.0",
"author": "Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)",
"contributors": [
"Alan Plum <me@pluma.io>",
"Douglas Christopher Wilson <doug@somethingdoug.com>"
],
"license": "MIT",
"repository": "jshttp/http-errors",
"dependencies": {
"depd": "~1.1.2",
"inherits": "2.0.4",
"setprototypeof": "1.2.0",
"statuses": ">= 1.5.0 < 2",
"toidentifier": "1.0.0"
},
"devDependencies": {
"eslint": "6.8.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.22.0",
"eslint-plugin-markdown": "1.0.2",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "4.2.1",
"eslint-plugin-standard": "4.0.1",
"mocha": "8.0.1",
"nyc": "15.1.0"
},
"engines": {
"node": ">= 0.6"
},
"scripts": {
"lint": "eslint --plugin markdown --ext js,md . && node ./scripts/lint-readme-list.js",
"test": "mocha --reporter spec --bail",
"test-ci": "nyc --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
},
"keywords": [
"http",
"error"
],
"files": [
"index.js",
"HISTORY.md",
"LICENSE",
"README.md"
]
}

View file

@ -0,0 +1,65 @@
1.5.0 / 2018-03-27
==================
* Add `103 Early Hints`
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

View file

@ -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.

View file

@ -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
<!-- eslint-disable no-unused-vars -->
```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.
<!-- eslint-disable no-undef -->
```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.
<!-- eslint-disable no-undef, no-unused-expressions -->
```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.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status['not found'] // => 404
status['Not Found'] // => 404
```
### status.redirect[code]
Returns `true` if a status code is a valid redirect status.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status.redirect[200] // => undefined
status.redirect[301] // => true
```
### status.empty[code]
Returns `true` if a status code expects an empty body.
<!-- eslint-disable no-undef, no-unused-expressions -->
```js
status.empty[200] // => undefined
status.empty[204] // => true
status.empty[304] // => true
```
### status.retry[code]
Returns `true` if you should retry the rest.
<!-- eslint-disable no-undef, no-unused-expressions -->
```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

View file

@ -0,0 +1,66 @@
{
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"103": "Early Hints",
"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"
}

View file

@ -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
}

View file

@ -0,0 +1,48 @@
{
"name": "statuses",
"description": "HTTP status utility",
"version": "1.5.0",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
],
"repository": "jshttp/statuses",
"license": "MIT",
"keywords": [
"http",
"status",
"code"
],
"files": [
"HISTORY.md",
"index.js",
"codes.json",
"LICENSE"
],
"devDependencies": {
"csv-parse": "1.2.4",
"eslint": "4.19.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.7.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"
},
"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"
}
}

View file

@ -0,0 +1,21 @@
MIT License
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.

View file

@ -0,0 +1,61 @@
# toidentifier
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][codecov-image]][codecov-url]
> Convert a string of words to a JavaScript identifier
## 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 toidentifier
```
## Example
```js
var toIdentifier = require('toidentifier')
console.log(toIdentifier('Bad Request'))
// => "BadRequest"
```
## API
This CommonJS module exports a single default function: `toIdentifier`.
### toIdentifier(string)
Given a string as the argument, it will be transformed according to
the following rules and the new string will be returned:
1. Split into words separated by space characters (`0x20`).
2. Upper case the first character of each word.
3. Join the words together with no separator.
4. Remove all non-word (`[0-9a-z_]`) characters.
## License
[MIT](LICENSE)
[codecov-image]: https://img.shields.io/codecov/c/github/component/toidentifier.svg
[codecov-url]: https://codecov.io/gh/component/toidentifier
[downloads-image]: https://img.shields.io/npm/dm/toidentifier.svg
[downloads-url]: https://npmjs.org/package/toidentifier
[npm-image]: https://img.shields.io/npm/v/toidentifier.svg
[npm-url]: https://npmjs.org/package/toidentifier
[travis-image]: https://img.shields.io/travis/component/toidentifier/master.svg
[travis-url]: https://travis-ci.org/component/toidentifier
##
[npm]: https://www.npmjs.com/
[yarn]: https://yarnpkg.com/

View file

@ -0,0 +1,30 @@
/*!
* toidentifier
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module exports.
* @public
*/
module.exports = toIdentifier
/**
* Trasform the given string into a JavaScript identifier
*
* @param {string} str
* @returns {string}
* @public
*/
function toIdentifier (str) {
return str
.split(' ')
.map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
})
.join('')
.replace(/[^ _0-9a-z]/gi, '')
}

View file

@ -0,0 +1,34 @@
{
"name": "toidentifier",
"description": "Convert a string of words to a JavaScript identifier",
"version": "1.0.0",
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Nick Baugh <niftylettuce@gmail.com> (http://niftylettuce.com/)"
],
"repository": "component/toidentifier",
"devDependencies": {
"eslint": "4.19.1",
"eslint-config-standard": "11.0.0",
"eslint-plugin-import": "2.11.0",
"eslint-plugin-markdown": "1.0.0-beta.6",
"eslint-plugin-node": "6.0.1",
"eslint-plugin-promise": "3.7.0",
"eslint-plugin-standard": "3.1.0",
"mocha": "1.21.5",
"nyc": "11.8.0"
},
"engines": {
"node": ">=0.6"
},
"license": "MIT",
"files": [
"index.js"
],
"scripts": {
"lint": "eslint --plugin markdown --ext js,md .",
"test": "mocha --reporter spec --bail --check-leaks test/",
"test-cov": "nyc --reporter=html --reporter=text npm test"
}
}

45
VISUALIZACION/node_modules/express-graphql/package.json generated vendored Executable file
View file

@ -0,0 +1,45 @@
{
"name": "express-graphql",
"version": "0.12.0",
"description": "Production ready GraphQL HTTP middleware.",
"license": "MIT",
"main": "index.js",
"types": "index.d.ts",
"typesVersions": {
"<3.8": {
"*": [
"ts3.4/*"
]
}
},
"sideEffects": false,
"homepage": "https://github.com/graphql/express-graphql",
"bugs": {
"url": "https://github.com/graphql/express-graphql/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/graphql/express-graphql.git"
},
"keywords": [
"express",
"restify",
"connect",
"http",
"graphql",
"middleware",
"api"
],
"engines": {
"node": ">= 10.x"
},
"dependencies": {
"accepts": "^1.3.7",
"content-type": "^1.0.4",
"http-errors": "1.8.0",
"raw-body": "^2.4.1"
},
"peerDependencies": {
"graphql": "^14.7.0 || ^15.3.0"
}
}

13
VISUALIZACION/node_modules/express-graphql/parseBody.d.ts generated vendored Executable file
View file

@ -0,0 +1,13 @@
/// <reference types="node" />
import type { IncomingMessage } from 'http';
declare type Request = IncomingMessage & {
body?: unknown;
};
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the body data contained.
*/
export declare function parseBody(req: Request): Promise<{
[param: string]: unknown;
}>;
export {};

110
VISUALIZACION/node_modules/express-graphql/parseBody.js generated vendored Executable file
View file

@ -0,0 +1,110 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseBody = void 0;
const zlib_1 = __importDefault(require("zlib"));
const querystring_1 = __importDefault(require("querystring"));
const raw_body_1 = __importDefault(require("raw-body"));
const http_errors_1 = __importDefault(require("http-errors"));
const content_type_1 = __importDefault(require("content-type"));
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the body data contained.
*/
async function parseBody(req) {
const { body } = req;
// If express has already parsed a body as a keyed object, use it.
if (typeof body === 'object' && !(body instanceof Buffer)) {
return body;
}
// Skip requests without content types.
if (req.headers['content-type'] === undefined) {
return {};
}
const typeInfo = content_type_1.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 { query: body };
}
// Already parsed body we didn't recognise? Parse nothing.
if (body != null) {
return {};
}
const rawBody = await readBody(req, typeInfo);
// Use the correct body parser based on Content-Type header.
switch (typeInfo.type) {
case 'application/graphql':
return { query: rawBody };
case 'application/json':
if (jsonObjRegex.test(rawBody)) {
try {
return JSON.parse(rawBody);
}
catch (_a) {
// Do nothing
}
}
throw http_errors_1.default(400, 'POST body sent invalid JSON.');
case 'application/x-www-form-urlencoded':
return querystring_1.default.parse(rawBody);
}
// If no Content-Type header matches, parse nothing.
return {};
}
exports.parseBody = parseBody;
/**
* RegExp to match an Object-opening brace "{" as the first non-space
* in a string. Allowed whitespace is defined in RFC 7159:
*
* ' ' Space
* '\t' Horizontal tab
* '\n' Line feed or New line
* '\r' Carriage return
*/
const jsonObjRegex = /^[ \t\n\r]*\{/;
// Read and parse a request body.
async function readBody(req, typeInfo) {
var _a, _b;
const charset = (_b = (_a = typeInfo.parameters.charset) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'utf-8';
// Assert charset encoding per JSON RFC 7159 sec 8.1
if (!charset.startsWith('utf-')) {
throw http_errors_1.default(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.
try {
return await raw_body_1.default(stream, { encoding: charset, length, limit });
}
catch (rawError) {
const error = http_errors_1.default(400,
/* istanbul ignore next: Thrown by underlying library. */
rawError instanceof Error ? rawError : String(rawError));
error.message =
error.type === 'encoding.unsupported'
? `Unsupported charset "${charset.toUpperCase()}".`
: `Invalid body: ${error.message}.`;
throw error;
}
}
// Return a decompressed stream, given an encoding.
function decompressed(req, encoding) {
switch (encoding) {
case 'identity':
return req;
case 'deflate':
return req.pipe(zlib_1.default.createInflate());
case 'gzip':
return req.pipe(zlib_1.default.createGunzip());
}
throw http_errors_1.default(415, `Unsupported content-encoding "${encoding}".`);
}

View file

@ -0,0 +1,30 @@
import type { FormattedExecutionResult } from 'graphql';
export interface GraphiQLData {
query?: string | null;
variables?: {
readonly [name: string]: unknown;
} | null;
operationName?: string | null;
result?: FormattedExecutionResult;
}
export interface GraphiQLOptions {
/**
* An optional GraphQL string to use when no query is provided and no stored
* query exists from a previous session. If undefined is provided, GraphiQL
* will use its own default query.
*/
defaultQuery?: string;
/**
* An optional boolean which enables the header editor when true.
* Defaults to false.
*/
headerEditorEnabled?: boolean;
}
/**
* When express-graphql receives a request which does not Accept JSON, but does
* Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
*
* When shown, it will be pre-populated with the result of having executed the
* requested query.
*/
export declare function renderGraphiQL(data: GraphiQLData, options?: GraphiQLOptions): string;

171
VISUALIZACION/node_modules/express-graphql/renderGraphiQL.js generated vendored Executable file

File diff suppressed because one or more lines are too long

146
VISUALIZACION/node_modules/express-graphql/ts3.4/index.d.ts generated vendored Executable file
View file

@ -0,0 +1,146 @@
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http';
import { ASTVisitor, DocumentNode, ValidationRule, ValidationContext, ExecutionArgs, ExecutionResult, FormattedExecutionResult, GraphQLSchema, GraphQLFieldResolver, GraphQLTypeResolver, GraphQLFormattedError } from 'graphql';
import { Source, GraphQLError } from 'graphql';
import { GraphiQLOptions } from './renderGraphiQL';
declare type Request = IncomingMessage & {
url: string;
};
declare type Response = ServerResponse & {
json?: (data: unknown) => void;
};
declare type MaybePromise<T> = Promise<T> | T;
/**
* 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 declare type Options = ((request: Request, response: Response, params?: GraphQLParams) => MaybePromise<OptionsData>) | MaybePromise<OptionsData>;
export interface OptionsData {
/**
* A GraphQL schema from graphql-js.
*/
schema: GraphQLSchema;
/**
* A value to pass as the context to this middleware.
*/
context?: unknown;
/**
* An object to pass as the rootValue to the graphql() function.
*/
rootValue?: unknown;
/**
* A boolean to configure whether the output should be pretty-printed.
*/
pretty?: boolean;
/**
* An optional array of validation rules that will be applied on the document
* in additional to those defined by the GraphQL spec.
*/
validationRules?: ReadonlyArray<(ctx: ValidationContext) => ASTVisitor>;
/**
* An optional function which will be used to validate instead of default `validate`
* from `graphql-js`.
*/
customValidateFn?: (schema: GraphQLSchema, documentAST: DocumentNode, rules: ReadonlyArray<ValidationRule>) => ReadonlyArray<GraphQLError>;
/**
* An optional function which will be used to execute instead of default `execute`
* from `graphql-js`.
*/
customExecuteFn?: (args: ExecutionArgs) => MaybePromise<ExecutionResult>;
/**
* 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.
*/
customFormatErrorFn?: (error: GraphQLError) => GraphQLFormattedError;
/**
* An optional function which will be used to create a document instead of
* the default `parse` from `graphql-js`.
*/
customParseFn?: (source: Source) => DocumentNode;
/**
* `formatError` is deprecated and replaced by `customFormatErrorFn`. It will
* be removed in version 1.0.0.
*/
formatError?: (error: GraphQLError) => GraphQLFormattedError;
/**
* 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) => MaybePromise<undefined | {
[key: string]: unknown;
}>;
/**
* A boolean to optionally enable GraphiQL mode.
* Alternatively, instead of `true` you can pass in an options object.
*/
graphiql?: boolean | GraphiQLOptions;
/**
* 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).
*/
fieldResolver?: GraphQLFieldResolver<unknown, unknown>;
/**
* A type resolver function to use when none is provided by the schema.
* If not provided, the default type resolver is used (which looks for a
* `__typename` field or alternatively calls the `isTypeOf` method).
*/
typeResolver?: GraphQLTypeResolver<unknown, unknown>;
}
/**
* All information about a GraphQL request.
*/
export interface RequestInfo {
/**
* The parsed GraphQL document.
*/
document: DocumentNode;
/**
* The variable values used at runtime.
*/
variables: {
readonly [name: string]: unknown;
} | null;
/**
* The (optional) operation name requested.
*/
operationName: string | null;
/**
* The result of executing the operation.
*/
result: FormattedExecutionResult;
/**
* A value to pass as the context to the graphql() function.
*/
context?: unknown;
}
declare type Middleware = (request: Request, response: Response) => Promise<void>;
/**
* Middleware for express; takes an options object or function as input to
* configure behavior, and returns an express middleware.
*/
export declare function graphqlHTTP(options: Options): Middleware;
export interface GraphQLParams {
query: string | null;
variables: {
readonly [name: string]: unknown;
} | null;
operationName: string | null;
raw: boolean;
}
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the GraphQL request parameters.
*/
export declare function getGraphQLParams(request: Request): Promise<GraphQLParams>;
export {};

View file

@ -0,0 +1,13 @@
/// <reference types="node" />
import { IncomingMessage } from 'http';
declare type Request = IncomingMessage & {
body?: unknown;
};
/**
* Provided a "Request" provided by express or connect (typically a node style
* HTTPClientRequest), Promise the body data contained.
*/
export declare function parseBody(req: Request): Promise<{
[param: string]: unknown;
}>;
export {};

View file

@ -0,0 +1,30 @@
import { FormattedExecutionResult } from 'graphql';
export interface GraphiQLData {
query?: string | null;
variables?: {
readonly [name: string]: unknown;
} | null;
operationName?: string | null;
result?: FormattedExecutionResult;
}
export interface GraphiQLOptions {
/**
* An optional GraphQL string to use when no query is provided and no stored
* query exists from a previous session. If undefined is provided, GraphiQL
* will use its own default query.
*/
defaultQuery?: string;
/**
* An optional boolean which enables the header editor when true.
* Defaults to false.
*/
headerEditorEnabled?: boolean;
}
/**
* When express-graphql receives a request which does not Accept JSON, but does
* Accept HTML, it may present GraphiQL, the in-browser GraphQL explorer IDE.
*
* When shown, it will be pre-populated with the result of having executed the
* requested query.
*/
export declare function renderGraphiQL(data: GraphiQLData, options?: GraphiQLOptions): string;