id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
1,200
function (fork: Fork) { var types = fork.use(typesPlugin); var Type = types.Type; var def = Type.def; var or = Type.or; var shared = fork.use(sharedPlugin); var defaults = shared.defaults; var geq = shared.geq; const { BinaryOperators, AssignmentOperators, LogicalOperators, } = fork.use(coreOpsDef); // Abstract supertype of all syntactic entities that are allowed to have a // .loc field. def("Printable") .field("loc", or( def("SourceLocation"), null ), defaults["null"], true); def("Node") .bases("Printable") .field("type", String) .field("comments", or( [def("Comment")], null ), defaults["null"], true); def("SourceLocation") .field("start", def("Position")) .field("end", def("Position")) .field("source", or(String, null), defaults["null"]); def("Position") .field("line", geq(1)) .field("column", geq(0)); def("File") .bases("Node") .build("program", "name") .field("program", def("Program")) .field("name", or(String, null), defaults["null"]); def("Program") .bases("Node") .build("body") .field("body", [def("Statement")]); def("Function") .bases("Node") .field("id", or(def("Identifier"), null), defaults["null"]) .field("params", [def("Pattern")]) .field("body", def("BlockStatement")) .field("generator", Boolean, defaults["false"]) .field("async", Boolean, defaults["false"]); def("Statement").bases("Node"); // The empty .build() here means that an EmptyStatement can be constructed // (i.e. it's not abstract) but that it needs no arguments. def("EmptyStatement").bases("Statement").build(); def("BlockStatement") .bases("Statement") .build("body") .field("body", [def("Statement")]); // TODO Figure out how to silently coerce Expressions to // ExpressionStatements where a Statement was expected. def("ExpressionStatement") .bases("Statement") .build("expression") .field("expression", def("Expression")); def("IfStatement") .bases("Statement") .build("test", "consequent", "alternate") .field("test", def("Expression")) .field("consequent", def("Statement")) .field("alternate", or(def("Statement"), null), defaults["null"]); def("LabeledStatement") .bases("Statement") .build("label", "body") .field("label", def("Identifier")) .field("body", def("Statement")); def("BreakStatement") .bases("Statement") .build("label") .field("label", or(def("Identifier"), null), defaults["null"]); def("ContinueStatement") .bases("Statement") .build("label") .field("label", or(def("Identifier"), null), defaults["null"]); def("WithStatement") .bases("Statement") .build("object", "body") .field("object", def("Expression")) .field("body", def("Statement")); def("SwitchStatement") .bases("Statement") .build("discriminant", "cases", "lexical") .field("discriminant", def("Expression")) .field("cases", [def("SwitchCase")]) .field("lexical", Boolean, defaults["false"]); def("ReturnStatement") .bases("Statement") .build("argument") .field("argument", or(def("Expression"), null)); def("ThrowStatement") .bases("Statement") .build("argument") .field("argument", def("Expression")); def("TryStatement") .bases("Statement") .build("block", "handler", "finalizer") .field("block", def("BlockStatement")) .field("handler", or(def("CatchClause"), null), function (this: N.TryStatement) { return this.handlers && this.handlers[0] || null; }) .field("handlers", [def("CatchClause")], function (this: N.TryStatement) { return this.handler ? [this.handler] : []; }, true) // Indicates this field is hidden from eachField iteration. .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray) .field("finalizer", or(def("BlockStatement"), null), defaults["null"]); def("CatchClause") .bases("Node") .build("param", "guard", "body") .field("param", def("Pattern")) .field("guard", or(def("Expression"), null), defaults["null"]) .field("body", def("BlockStatement")); def("WhileStatement") .bases("Statement") .build("test", "body") .field("test", def("Expression")) .field("body", def("Statement")); def("DoWhileStatement") .bases("Statement") .build("body", "test") .field("body", def("Statement")) .field("test", def("Expression")); def("ForStatement") .bases("Statement") .build("init", "test", "update", "body") .field("init", or( def("VariableDeclaration"), def("Expression"), null)) .field("test", or(def("Expression"), null)) .field("update", or(def("Expression"), null)) .field("body", def("Statement")); def("ForInStatement") .bases("Statement") .build("left", "right", "body") .field("left", or( def("VariableDeclaration"), def("Expression"))) .field("right", def("Expression")) .field("body", def("Statement")); def("DebuggerStatement").bases("Statement").build(); def("Declaration").bases("Statement"); def("FunctionDeclaration") .bases("Function", "Declaration") .build("id", "params", "body") .field("id", def("Identifier")); def("FunctionExpression") .bases("Function", "Expression") .build("id", "params", "body"); def("VariableDeclaration") .bases("Declaration") .build("kind", "declarations") .field("kind", or("var", "let", "const")) .field("declarations", [def("VariableDeclarator")]); def("VariableDeclarator") .bases("Node") .build("id", "init") .field("id", def("Pattern")) .field("init", or(def("Expression"), null), defaults["null"]); def("Expression").bases("Node"); def("ThisExpression").bases("Expression").build(); def("ArrayExpression") .bases("Expression") .build("elements") .field("elements", [or(def("Expression"), null)]); def("ObjectExpression") .bases("Expression") .build("properties") .field("properties", [def("Property")]); // TODO Not in the Mozilla Parser API, but used by Esprima. def("Property") .bases("Node") // Want to be able to visit Property Nodes. .build("kind", "key", "value") .field("kind", or("init", "get", "set")) .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Expression")); def("SequenceExpression") .bases("Expression") .build("expressions") .field("expressions", [def("Expression")]); var UnaryOperator = or( "-", "+", "!", "~", "typeof", "void", "delete"); def("UnaryExpression") .bases("Expression") .build("operator", "argument", "prefix") .field("operator", UnaryOperator) .field("argument", def("Expression")) // Esprima doesn't bother with this field, presumably because it's // always true for unary operators. .field("prefix", Boolean, defaults["true"]); const BinaryOperator = or(...BinaryOperators); def("BinaryExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", BinaryOperator) .field("left", def("Expression")) .field("right", def("Expression")); const AssignmentOperator = or(...AssignmentOperators); def("AssignmentExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", AssignmentOperator) .field("left", or(def("Pattern"), def("MemberExpression"))) .field("right", def("Expression")); var UpdateOperator = or("++", "--"); def("UpdateExpression") .bases("Expression") .build("operator", "argument", "prefix") .field("operator", UpdateOperator) .field("argument", def("Expression")) .field("prefix", Boolean); var LogicalOperator = or(...LogicalOperators); def("LogicalExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", LogicalOperator) .field("left", def("Expression")) .field("right", def("Expression")); def("ConditionalExpression") .bases("Expression") .build("test", "consequent", "alternate") .field("test", def("Expression")) .field("consequent", def("Expression")) .field("alternate", def("Expression")); def("NewExpression") .bases("Expression") .build("callee", "arguments") .field("callee", def("Expression")) // The Mozilla Parser API gives this type as [or(def("Expression"), // null)], but null values don't really make sense at the call site. // TODO Report this nonsense. .field("arguments", [def("Expression")]); def("CallExpression") .bases("Expression") .build("callee", "arguments") .field("callee", def("Expression")) // See comment for NewExpression above. .field("arguments", [def("Expression")]); def("MemberExpression") .bases("Expression") .build("object", "property", "computed") .field("object", def("Expression")) .field("property", or(def("Identifier"), def("Expression"))) .field("computed", Boolean, function (this: N.MemberExpression) { var type = this.property.type; if (type === 'Literal' || type === 'MemberExpression' || type === 'BinaryExpression') { return true; } return false; }); def("Pattern").bases("Node"); def("SwitchCase") .bases("Node") .build("test", "consequent") .field("test", or(def("Expression"), null)) .field("consequent", [def("Statement")]); def("Identifier") .bases("Expression", "Pattern") .build("name") .field("name", String) .field("optional", Boolean, defaults["false"]); def("Literal") .bases("Expression") .build("value") .field("value", or(String, Boolean, null, Number, RegExp, BigInt)); // Abstract (non-buildable) comment supertype. Not a Node. def("Comment") .bases("Printable") .field("value", String) // A .leading comment comes before the node, whereas a .trailing // comment comes after it. These two fields should not both be true, // but they might both be false when the comment falls inside a node // and the node has no children for the comment to lead or trail, // e.g. { /*dangling*/ }. .field("leading", Boolean, defaults["true"]) .field("trailing", Boolean, defaults["false"]); }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,201
function (fork: Fork) { fork.use(es2018Def); const types = fork.use(typesPlugin); const def = types.Type.def; const or = types.Type.or; const defaults = fork.use(sharedPlugin).defaults; def("CatchClause") .field("param", or(def("Pattern"), null), defaults["null"]); }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,202
function (fork: Fork) { fork.use(es2021Def); const types = fork.use(typesPlugin); const def = types.Type.def; def("StaticBlock") .bases("Declaration") .build("body") .field("body", [def("Statement")]); }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,203
function (fork: Fork) { fork.use(es2022Def); const types = fork.use(typesPlugin); const Type = types.Type; const def = types.Type.def; const or = Type.or; const shared = fork.use(sharedPlugin); const defaults = shared.defaults; def("AwaitExpression") .build("argument", "all") .field("argument", or(def("Expression"), null)) .field("all", Boolean, defaults["false"]); // Decorators def("Decorator") .bases("Node") .build("expression") .field("expression", def("Expression")); def("Property") .field("decorators", or([def("Decorator")], null), defaults["null"]); def("MethodDefinition") .field("decorators", or([def("Decorator")], null), defaults["null"]); // Private names def("PrivateName") .bases("Expression", "Pattern") .build("id") .field("id", def("Identifier")); def("ClassPrivateProperty") .bases("ClassProperty") .build("key", "value") .field("key", def("PrivateName")) .field("value", or(def("Expression"), null), defaults["null"]); // https://github.com/tc39/proposal-import-assertions def("ImportAttribute") .bases("Node") .build("key", "value") .field("key", or(def("Identifier"), def("Literal"))) .field("value", def("Expression")); [ "ImportDeclaration", "ExportAllDeclaration", "ExportNamedDeclaration", ].forEach(decl => { def(decl).field( "assertions", [def("ImportAttribute")], defaults.emptyArray, ); }); // https://github.com/tc39/proposal-record-tuple // https://github.com/babel/babel/pull/10865 def("RecordExpression") .bases("Expression") .build("properties") .field("properties", [or( def("ObjectProperty"), def("ObjectMethod"), def("SpreadElement"), )]); def("TupleExpression") .bases("Expression") .build("elements") .field("elements", [or( def("Expression"), def("SpreadElement"), null, )]); // https://github.com/tc39/proposal-js-module-blocks // https://github.com/babel/babel/pull/12469 def("ModuleExpression") .bases("Node") .build("body") .field("body", def("Program")); }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,204
function (fork: Fork) { fork.use(es2016Def); const types = fork.use(typesPlugin); const def = types.Type.def; const defaults = fork.use(sharedPlugin).defaults; def("Function") .field("async", Boolean, defaults["false"]); def("AwaitExpression") .bases("Expression") .build("argument") .field("argument", def("Expression")); }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,205
function (fork: Fork) { var types = fork.use(typesPlugin); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(sharedPlugin).defaults; var TypeAnnotation = or( def("TypeAnnotation"), def("TSTypeAnnotation"), null ); var TypeParamDecl = or( def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null ); def("Identifier") .field("typeAnnotation", TypeAnnotation, defaults["null"]); def("ObjectPattern") .field("typeAnnotation", TypeAnnotation, defaults["null"]); def("Function") .field("returnType", TypeAnnotation, defaults["null"]) .field("typeParameters", TypeParamDecl, defaults["null"]); def("ClassProperty") .build("key", "value", "typeAnnotation", "static") .field("value", or(def("Expression"), null)) .field("static", Boolean, defaults["false"]) .field("typeAnnotation", TypeAnnotation, defaults["null"]); ["ClassDeclaration", "ClassExpression", ].forEach(typeName => { def(typeName) .field("typeParameters", TypeParamDecl, defaults["null"]) .field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"]) .field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray); }); }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,206
function (fork: import("../../types").Fork) { const result = fork.use(coreOpsDef); // Exponentiation operators. Must run before BinaryOperators or // AssignmentOperators are used (hence before fork.use(es6Def)). // https://github.com/tc39/proposal-exponentiation-operator if (result.BinaryOperators.indexOf("**") < 0) { result.BinaryOperators.push("**"); } if (result.AssignmentOperators.indexOf("**=") < 0) { result.AssignmentOperators.push("**="); } return result; }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,207
function (fork: import("../../types").Fork) { const result = fork.use(es2016OpsDef); // Nullish coalescing. Must run before LogicalOperators is used. // https://github.com/tc39/proposal-nullish-coalescing if (result.LogicalOperators.indexOf("??") < 0) { result.LogicalOperators.push("??"); } return result; }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,208
function (fork: import("../../types").Fork) { const result = fork.use(es2020OpsDef); // Logical assignment operators. Must run before AssignmentOperators is used. // https://github.com/tc39/proposal-logical-assignment result.LogicalOperators.forEach(op => { const assignOp = op + "="; if (result.AssignmentOperators.indexOf(assignOp) < 0) { result.AssignmentOperators.push(assignOp); } }); return result; }
type Fork = { use<T>(plugin: Plugin<T>): T; };
1,209
(req: Request, res: Response, next?: NextFunction): void | Promise<void>
type Response<T = http.ServerResponse> = T;
1,210
(req: Request, res: Response, next?: NextFunction): void | Promise<void>
type NextFunction<T = (err?: any) => void> = T;
1,211
(req: Request, res: Response, next?: NextFunction): void | Promise<void>
type Request<T = http.IncomingMessage> = T;
1,212
(req: Request, socket: net.Socket, head: any) => void
type Request<T = http.IncomingMessage> = T;
1,213
(proxyServer: httpProxy, options: Options) => void
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,214
(req: Request) => httpProxy.ServerOptions['target']
type Request<T = http.IncomingMessage> = T;
1,215
(req: Request) => Promise<httpProxy.ServerOptions['target']>
type Request<T = http.IncomingMessage> = T;
1,216
function createProxyMiddleware(options: Options): RequestHandler { const { middleware } = new HttpProxyMiddleware(options); return middleware; }
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,217
constructor(options: Options) { verifyConfig(options); this.proxyOptions = options; debug(`create proxy server`); this.proxy = httpProxy.createProxyServer({}); this.registerPlugins(this.proxy, this.proxyOptions); this.pathRewriter = PathRewriter.createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided // https://github.com/chimurai/http-proxy-middleware/issues/19 // expose function to upgrade externally this.middleware.upgrade = (req, socket, head) => { if (!this.wsInternalSubscribed) { this.handleUpgrade(req, socket, head); } }; }
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,218
private registerPlugins(proxy: httpProxy, options: Options) { const plugins = getPlugins(options); plugins.forEach((plugin) => { debug(`register plugin: "${getFunctionName(plugin)}"`); plugin(proxy, options); }); }
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,219
async (req: Request, socket, head) => { if (this.shouldProxy(this.proxyOptions.pathFilter, req)) { const activeProxyOptions = await this.prepareProxyRequest(req); this.proxy.ws(req, socket, head, activeProxyOptions); debug('server upgrade event received. Proxying WebSocket'); } }
type Request<T = http.IncomingMessage> = T;
1,220
(pathFilter: Filter, req: Request): boolean => { return matchPathFilter(pathFilter, req.url, req); }
type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
1,221
(pathFilter: Filter, req: Request): boolean => { return matchPathFilter(pathFilter, req.url, req); }
type Request<T = http.IncomingMessage> = T;
1,222
async (req: Request) => { /** * Incorrect usage confirmed: https://github.com/expressjs/express/issues/4854#issuecomment-1066171160 * Temporary restore req.url patch for {@link src/legacy/create-proxy-middleware.ts legacyCreateProxyMiddleware()} * FIXME: remove this patch in future release */ if ((this.middleware as unknown as any).__LEGACY_HTTP_PROXY_MIDDLEWARE__) { req.url = (req as unknown as any).originalUrl || req.url; } const newProxyOptions = Object.assign({}, this.proxyOptions); // Apply in order: // 1. option.router // 2. option.pathRewrite await this.applyRouter(req, newProxyOptions); await this.applyPathRewrite(req, this.pathRewriter); return newProxyOptions; }
type Request<T = http.IncomingMessage> = T;
1,223
async (req: Request, options) => { let newTarget; if (options.router) { newTarget = await Router.getTarget(req, options); if (newTarget) { debug('router new target: "%s"', newTarget); options.target = newTarget; } } }
type Request<T = http.IncomingMessage> = T;
1,224
async (req: Request, pathRewriter) => { if (pathRewriter) { const path = await pathRewriter(req.url, req); if (typeof path === 'string') { debug('pathRewrite new path: %s', req.url); req.url = path; } else { debug('pathRewrite: no rewritten path found: %s', req.url); } } }
type Request<T = http.IncomingMessage> = T;
1,225
function verifyConfig(options: Options): void { if (!options.target && !options.router) { throw new Error(ERRORS.ERR_CONFIG_FACTORY_TARGET_MISSING); } }
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,226
function matchPathFilter(pathFilter: Filter = '/', uri: string, req: Request): boolean { // single path if (isStringPath(pathFilter as string)) { return matchSingleStringPath(pathFilter as string, uri); } // single glob path if (isGlobPath(pathFilter as string)) { return matchSingleGlobPath(pathFilter as unknown as string[], uri); } // multi path if (Array.isArray(pathFilter)) { if (pathFilter.every(isStringPath)) { return matchMultiPath(pathFilter, uri); } if (pathFilter.every(isGlobPath)) { return matchMultiGlobPath(pathFilter as string[], uri); } throw new Error(ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY); } // custom matching if (typeof pathFilter === 'function') { const pathname = getUrlPathName(uri); return pathFilter(pathname, req); } throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC); }
type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
1,227
function matchPathFilter(pathFilter: Filter = '/', uri: string, req: Request): boolean { // single path if (isStringPath(pathFilter as string)) { return matchSingleStringPath(pathFilter as string, uri); } // single glob path if (isGlobPath(pathFilter as string)) { return matchSingleGlobPath(pathFilter as unknown as string[], uri); } // multi path if (Array.isArray(pathFilter)) { if (pathFilter.every(isStringPath)) { return matchMultiPath(pathFilter, uri); } if (pathFilter.every(isGlobPath)) { return matchMultiGlobPath(pathFilter as string[], uri); } throw new Error(ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY); } // custom matching if (typeof pathFilter === 'function') { const pathname = getUrlPathName(uri); return pathFilter(pathname, req); } throw new Error(ERRORS.ERR_CONTEXT_MATCHER_GENERIC); }
type Request<T = http.IncomingMessage> = T;
1,228
function getLogger(options: Options): Logger { return (options.logger as Logger) || noopLogger; }
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,229
function getPlugins(options: Options): Plugin[] { // don't load default errorResponsePlugin if user has specified their own const maybeErrorResponsePlugin = !!options.on?.error ? [] : [errorResponsePlugin]; const defaultPlugins: Plugin[] = !!options.ejectPlugins ? [] // no default plugins when ejecting : [debugProxyErrorsPlugin, proxyEventsPlugin, loggerPlugin, ...maybeErrorResponsePlugin]; const userPlugins: Plugin[] = options.plugins ?? []; return [...defaultPlugins, ...userPlugins]; }
interface Options extends httpProxy.ServerOptions { /** * Narrow down requests to proxy or not. * Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server. * Or use the {@link http.IncomingMessage `req`} object for more complex filtering. */ pathFilter?: Filter; pathRewrite?: | { [regexp: string]: string } | ((path: string, req: Request) => string) | ((path: string, req: Request) => Promise<string>); /** * Access the internal http-proxy server instance to customize behavior * * @example * ```js * createProxyMiddleware({ * plugins: [(proxyServer, options) => { * proxyServer.on('error', (error, req, res) => { * console.error(error); * }); * }] * }); * ``` */ plugins?: Plugin[]; /** * Eject pre-configured plugins. * NOTE: register your own error handlers to prevent server from crashing. * * @since v3.0.0 */ ejectPlugins?: boolean; /** * Listen to http-proxy events * @see {@link OnProxyEvent} for available events * @example * ```js * createProxyMiddleware({ * on: { * error: (error, req, res, target) => { * console.error(error); * } * } * }); * ``` */ on?: OnProxyEvent; router?: | { [hostOrPath: string]: httpProxy.ServerOptions['target'] } | ((req: Request) => httpProxy.ServerOptions['target']) | ((req: Request) => Promise<httpProxy.ServerOptions['target']>); /** * Log information from http-proxy-middleware * @example * ```js * createProxyMiddleware({ * logger: console * }); * ``` */ logger?: Logger | any; }
1,230
function responseInterceptor(interceptor: Interceptor) { return async function proxyResResponseInterceptor( proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse ): Promise<void> { debug('intercept proxy response'); const originalProxyRes = proxyRes; let buffer = Buffer.from('', 'utf8'); // decompress proxy response const _proxyRes = decompress(proxyRes, proxyRes.headers['content-encoding']); // concat data stream _proxyRes.on('data', (chunk) => (buffer = Buffer.concat([buffer, chunk]))); _proxyRes.on('end', async () => { // copy original headers copyHeaders(proxyRes, res); // call interceptor with intercepted response (buffer) debug('call interceptor function: %s', getFunctionName(interceptor)); const interceptedBuffer = Buffer.from(await interceptor(buffer, originalProxyRes, req, res)); // set correct content-length (with double byte character support) debug('set content-length: %s', Buffer.byteLength(interceptedBuffer, 'utf8')); res.setHeader('content-length', Buffer.byteLength(interceptedBuffer, 'utf8')); debug('write intercepted response'); res.write(interceptedBuffer); res.end(); }); _proxyRes.on('error', (error) => { res.end(`Error fetching proxied request: ${error.message}`); }); }; }
type Interceptor = ( buffer: Buffer, proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse ) => Promise<Buffer | string>;
1,231
function legacyCreateProxyMiddleware(legacyOptions: LegacyOptions): RequestHandler;
interface LegacyOptions extends Options { /** * @deprecated * Use `on.error` instead. * * @example * ```js * { * on: { * error: () => {} * } * ``` */ onError?: (...args: any[]) => void; //httpProxy.ErrorCallback; /** * @deprecated * Use `on.proxyRes` instead. * * @example * ```js * { * on: { * proxyRes: () => {} * } * ``` */ onProxyRes?: (...args: any[]) => void; //httpProxy.ProxyResCallback; /** * @deprecated * Use `on.proxyReq` instead. * * @example * ```js * { * on: { * proxyReq: () => {} * } * ``` */ onProxyReq?: (...args: any[]) => void; //httpProxy.ProxyReqCallback; /** * @deprecated * Use `on.proxyReqWs` instead. * * @example * ```js * { * on: { * proxyReqWs: () => {} * } * ``` */ onProxyReqWs?: (...args: any[]) => void; //httpProxy.ProxyReqWsCallback; /** * @deprecated * Use `on.open` instead. * * @example * ```js * { * on: { * open: () => {} * } * ``` */ onOpen?: (...args: any[]) => void; //httpProxy.OpenCallback; /** * @deprecated * Use `on.close` instead. * * @example * ```js * { * on: { * close: () => {} * } * ``` */ onClose?: (...args: any[]) => void; //httpProxy.CloseCallback; /** * @deprecated * Use `logger` instead. * * @example * ```js * { * logger: console * } * ``` */ logProvider?: any; /** * @deprecated * Use `logger` instead. * * @example * ```js * { * logger: console * } * ``` */ logLevel?: any; }
1,232
function legacyCreateProxyMiddleware( legacyContext: Filter, legacyOptions: LegacyOptions ): RequestHandler;
type Filter = string | string[] | ((pathname: string, req: Request) => boolean);
1,233
function legacyCreateProxyMiddleware( legacyContext: Filter, legacyOptions: LegacyOptions ): RequestHandler;
interface LegacyOptions extends Options { /** * @deprecated * Use `on.error` instead. * * @example * ```js * { * on: { * error: () => {} * } * ``` */ onError?: (...args: any[]) => void; //httpProxy.ErrorCallback; /** * @deprecated * Use `on.proxyRes` instead. * * @example * ```js * { * on: { * proxyRes: () => {} * } * ``` */ onProxyRes?: (...args: any[]) => void; //httpProxy.ProxyResCallback; /** * @deprecated * Use `on.proxyReq` instead. * * @example * ```js * { * on: { * proxyReq: () => {} * } * ``` */ onProxyReq?: (...args: any[]) => void; //httpProxy.ProxyReqCallback; /** * @deprecated * Use `on.proxyReqWs` instead. * * @example * ```js * { * on: { * proxyReqWs: () => {} * } * ``` */ onProxyReqWs?: (...args: any[]) => void; //httpProxy.ProxyReqWsCallback; /** * @deprecated * Use `on.open` instead. * * @example * ```js * { * on: { * open: () => {} * } * ``` */ onOpen?: (...args: any[]) => void; //httpProxy.OpenCallback; /** * @deprecated * Use `on.close` instead. * * @example * ```js * { * on: { * close: () => {} * } * ``` */ onClose?: (...args: any[]) => void; //httpProxy.CloseCallback; /** * @deprecated * Use `logger` instead. * * @example * ```js * { * logger: console * } * ``` */ logProvider?: any; /** * @deprecated * Use `logger` instead. * * @example * ```js * { * logger: console * } * ``` */ logLevel?: any; }
1,234
function isTraversal(selector: Selector): selector is Traversal { switch (selector.type) { case SelectorType.Adjacent: case SelectorType.Child: case SelectorType.Descendant: case SelectorType.Parent: case SelectorType.Sibling: case SelectorType.ColumnCombinator: return true; default: return false; } }
type Selector = | PseudoSelector | PseudoElement | AttributeSelector | TagSelector | UniversalSelector | Traversal;
1,235
function addTraversal(type: TraversalType) { if ( tokens.length > 0 && tokens[tokens.length - 1].type === SelectorType.Descendant ) { tokens[tokens.length - 1].type = type; return; } ensureNotTraversal(); tokens.push({ type }); }
type TraversalType = | SelectorType.Adjacent | SelectorType.Child | SelectorType.Descendant | SelectorType.Parent | SelectorType.Sibling | SelectorType.ColumnCombinator;
1,236
function stringifyToken( token: Selector, index: number, arr: Selector[] ): string { switch (token.type) { // Simple types case SelectorType.Child: return index === 0 ? "> " : " > "; case SelectorType.Parent: return index === 0 ? "< " : " < "; case SelectorType.Sibling: return index === 0 ? "~ " : " ~ "; case SelectorType.Adjacent: return index === 0 ? "+ " : " + "; case SelectorType.Descendant: return " "; case SelectorType.ColumnCombinator: return index === 0 ? "|| " : " || "; case SelectorType.Universal: // Return an empty string if the selector isn't needed. return token.namespace === "*" && index + 1 < arr.length && "name" in arr[index + 1] ? "" : `${getNamespace(token.namespace)}*`; case SelectorType.Tag: return getNamespacedName(token); case SelectorType.PseudoElement: return `::${escapeName(token.name, charsToEscapeInName)}${ token.data === null ? "" : `(${escapeName(token.data, charsToEscapeInPseudoValue)})` }`; case SelectorType.Pseudo: return `:${escapeName(token.name, charsToEscapeInName)}${ token.data === null ? "" : `(${ typeof token.data === "string" ? escapeName( token.data, charsToEscapeInPseudoValue ) : stringify(token.data) })` }`; case SelectorType.Attribute: { if ( token.name === "id" && token.action === AttributeAction.Equals && token.ignoreCase === "quirks" && !token.namespace ) { return `#${escapeName(token.value, charsToEscapeInName)}`; } if ( token.name === "class" && token.action === AttributeAction.Element && token.ignoreCase === "quirks" && !token.namespace ) { return `.${escapeName(token.value, charsToEscapeInName)}`; } const name = getNamespacedName(token); if (token.action === AttributeAction.Exists) { return `[${name}]`; } return `[${name}${getActionValue(token.action)}="${escapeName( token.value, charsToEscapeInAttributeValue )}"${ token.ignoreCase === null ? "" : token.ignoreCase ? " i" : " s" }]`; } } }
type Selector = | PseudoSelector | PseudoElement | AttributeSelector | TagSelector | UniversalSelector | Traversal;
1,237
(entry: EntryInfo) => boolean
interface EntryInfo { path: string; fullPath: string; basename: string; stats?: fs.Stats; dirent?: fs.Dirent; }
1,238
function errorMessage(options: ErrorMessageOptions): CodeKeywordDefinition { return { keyword, schemaType: ["string", "object"], post: true, code(cxt: KeywordCxt) { const {gen, data, schema, schemaValue, it} = cxt if (it.createErrors === false) return const sch: ErrorMessageSchema | string = schema const instancePath = strConcat(N.instancePath, it.errorPath) gen.if(_`${N.errors} > 0`, () => { if (typeof sch == "object") { const [kwdPropErrors, kwdErrors] = keywordErrorsConfig(sch) if (kwdErrors) processKeywordErrors(kwdErrors) if (kwdPropErrors) processKeywordPropErrors(kwdPropErrors) processChildErrors(childErrorsConfig(sch)) } const schMessage = typeof sch == "string" ? sch : sch._ if (schMessage) processAllErrors(schMessage) if (!options.keepErrors) removeUsedErrors() }) function childErrorsConfig({properties, items}: ErrorMessageSchema): ChildErrors { const errors: ChildErrors = {} if (properties) { errors.props = {} for (const p in properties) errors.props[p] = [] } if (items) { errors.items = {} for (let i = 0; i < items.length; i++) errors.items[i] = [] } return errors } function keywordErrorsConfig( emSchema: ErrorMessageSchema ): [{[K in string]?: ErrorsMap<string>} | undefined, ErrorsMap<string> | undefined] { let propErrors: {[K in string]?: ErrorsMap<string>} | undefined let errors: ErrorsMap<string> | undefined for (const k in emSchema) { if (k === "properties" || k === "items") continue const kwdSch = emSchema[k] if (typeof kwdSch == "object") { propErrors ||= {} const errMap: ErrorsMap<string> = (propErrors[k] = {}) for (const p in kwdSch) errMap[p] = [] } else { errors ||= {} errors[k] = [] } } return [propErrors, errors] } function processKeywordErrors(kwdErrors: ErrorsMap<string>): void { const kwdErrs = gen.const("emErrors", stringify(kwdErrors)) const templates = gen.const("templates", getTemplatesCode(kwdErrors, schema)) gen.forOf("err", N.vErrors, (err) => gen.if(matchKeywordError(err, kwdErrs), () => gen.code(_`${kwdErrs}[${err}.keyword].push(${err})`).assign(_`${err}.${used}`, true) ) ) const {singleError} = options if (singleError) { const message = gen.let("message", _`""`) const paramsErrors = gen.let("paramsErrors", _`[]`) loopErrors((key) => { gen.if(message, () => gen.code(_`${message} += ${typeof singleError == "string" ? singleError : ";"}`) ) gen.code(_`${message} += ${errMessage(key)}`) gen.assign(paramsErrors, _`${paramsErrors}.concat(${kwdErrs}[${key}])`) }) reportError(cxt, {message, params: _`{errors: ${paramsErrors}}`}) } else { loopErrors((key) => reportError(cxt, { message: errMessage(key), params: _`{errors: ${kwdErrs}[${key}]}`, }) ) } function loopErrors(body: (key: Name) => void): void { gen.forIn("key", kwdErrs, (key) => gen.if(_`${kwdErrs}[${key}].length`, () => body(key))) } function errMessage(key: Name): Code { return _`${key} in ${templates} ? ${templates}[${key}]() : ${schemaValue}[${key}]` } } function processKeywordPropErrors(kwdPropErrors: {[K in string]?: ErrorsMap<string>}): void { const kwdErrs = gen.const("emErrors", stringify(kwdPropErrors)) const templatesCode: [string, Code][] = [] for (const k in kwdPropErrors) { templatesCode.push([ k, getTemplatesCode(kwdPropErrors[k] as ErrorsMap<string>, schema[k]), ]) } const templates = gen.const("templates", gen.object(...templatesCode)) const kwdPropParams = gen.scopeValue("obj", { ref: KEYWORD_PROPERTY_PARAMS, code: stringify(KEYWORD_PROPERTY_PARAMS), }) const propParam = gen.let("emPropParams") const paramsErrors = gen.let("emParamsErrors") gen.forOf("err", N.vErrors, (err) => gen.if(matchKeywordError(err, kwdErrs), () => { gen.assign(propParam, _`${kwdPropParams}[${err}.keyword]`) gen.assign(paramsErrors, _`${kwdErrs}[${err}.keyword][${err}.params[${propParam}]]`) gen.if(paramsErrors, () => gen.code(_`${paramsErrors}.push(${err})`).assign(_`${err}.${used}`, true) ) }) ) gen.forIn("key", kwdErrs, (key) => gen.forIn("keyProp", _`${kwdErrs}[${key}]`, (keyProp) => { gen.assign(paramsErrors, _`${kwdErrs}[${key}][${keyProp}]`) gen.if(_`${paramsErrors}.length`, () => { const tmpl = gen.const( "tmpl", _`${templates}[${key}] && ${templates}[${key}][${keyProp}]` ) reportError(cxt, { message: _`${tmpl} ? ${tmpl}() : ${schemaValue}[${key}][${keyProp}]`, params: _`{errors: ${paramsErrors}}`, }) }) }) ) } function processChildErrors(childErrors: ChildErrors): void { const {props, items} = childErrors if (!props && !items) return const isObj = _`typeof ${data} == "object"` const isArr = _`Array.isArray(${data})` const childErrs = gen.let("emErrors") let childKwd: Name let childProp: Code const templates = gen.let("templates") if (props && items) { childKwd = gen.let("emChildKwd") gen.if(isObj) gen.if( isArr, () => { init(items, schema.items) gen.assign(childKwd, str`items`) }, () => { init(props, schema.properties) gen.assign(childKwd, str`properties`) } ) childProp = _`[${childKwd}]` } else if (items) { gen.if(isArr) init(items, schema.items) childProp = _`.items` } else if (props) { gen.if(and(isObj, not(isArr))) init(props, schema.properties) childProp = _`.properties` } gen.forOf("err", N.vErrors, (err) => ifMatchesChildError(err, childErrs, (child) => gen.code(_`${childErrs}[${child}].push(${err})`).assign(_`${err}.${used}`, true) ) ) gen.forIn("key", childErrs, (key) => gen.if(_`${childErrs}[${key}].length`, () => { reportError(cxt, { message: _`${key} in ${templates} ? ${templates}[${key}]() : ${schemaValue}${childProp}[${key}]`, params: _`{errors: ${childErrs}[${key}]}`, }) gen.assign( _`${N.vErrors}[${N.errors}-1].instancePath`, _`${instancePath} + "/" + ${key}.replace(/~/g, "~0").replace(/\\//g, "~1")` ) }) ) gen.endIf() function init<T extends string | number>( children: ErrorsMap<T>, msgs: {[K in string]?: string} ): void { gen.assign(childErrs, stringify(children)) gen.assign(templates, getTemplatesCode(children, msgs)) } } function processAllErrors(schMessage: string): void { const errs = gen.const("emErrs", _`[]`) gen.forOf("err", N.vErrors, (err) => gen.if(matchAnyError(err), () => gen.code(_`${errs}.push(${err})`).assign(_`${err}.${used}`, true) ) ) gen.if(_`${errs}.length`, () => reportError(cxt, { message: templateExpr(schMessage), params: _`{errors: ${errs}}`, }) ) } function removeUsedErrors(): void { const errs = gen.const("emErrs", _`[]`) gen.forOf("err", N.vErrors, (err) => gen.if(_`!${err}.${used}`, () => gen.code(_`${errs}.push(${err})`)) ) gen.assign(N.vErrors, errs).assign(N.errors, _`${errs}.length`) } function matchKeywordError(err: Name, kwdErrs: Name): Code { return and( _`${err}.keyword !== ${keyword}`, _`!${err}.${used}`, _`${err}.instancePath === ${instancePath}`, _`${err}.keyword in ${kwdErrs}`, // TODO match the end of the string? _`${err}.schemaPath.indexOf(${it.errSchemaPath}) === 0`, _`/^\\/[^\\/]*$/.test(${err}.schemaPath.slice(${it.errSchemaPath.length}))` ) } function ifMatchesChildError( err: Name, childErrs: Name, thenBody: (child: Name) => void ): void { gen.if( and( _`${err}.keyword !== ${keyword}`, _`!${err}.${used}`, _`${err}.instancePath.indexOf(${instancePath}) === 0` ), () => { const childRegex = gen.scopeValue("pattern", { ref: /^\/([^/]*)(?:\/|$)/, code: _`new RegExp("^\\\/([^/]*)(?:\\\/|$)")`, }) const matches = gen.const( "emMatches", _`${childRegex}.exec(${err}.instancePath.slice(${instancePath}.length))` ) const child = gen.const( "emChild", _`${matches} && ${matches}[1].replace(/~1/g, "/").replace(/~0/g, "~")` ) gen.if(_`${child} !== undefined && ${child} in ${childErrs}`, () => thenBody(child)) } ) } function matchAnyError(err: Name): Code { return and( _`${err}.keyword !== ${keyword}`, _`!${err}.${used}`, or( _`${err}.instancePath === ${instancePath}`, and( _`${err}.instancePath.indexOf(${instancePath}) === 0`, _`${err}.instancePath[${instancePath}.length] === "/"` ) ), _`${err}.schemaPath.indexOf(${it.errSchemaPath}) === 0`, _`${err}.schemaPath[${it.errSchemaPath}.length] === "/"` ) } function getTemplatesCode(keys: Record<string, any>, msgs: {[K in string]?: string}): Code { const templatesCode: [string, Code][] = [] for (const k in keys) { const msg = msgs[k] as string if (INTERPOLATION.test(msg)) templatesCode.push([k, templateFunc(msg)]) } return gen.object(...templatesCode) } function templateExpr(msg: string): Code { if (!INTERPOLATION.test(msg)) return stringify(msg) return new _Code( safeStringify(msg) .replace( INTERPOLATION_REPLACE, (_s, ptr) => `" + JSON.stringify(${getData(ptr, it)}) + "` ) .replace(EMPTY_STR, "") ) } function templateFunc(msg: string): Code { return _`function(){return ${templateExpr(msg)}}` } }, metaSchema: { anyOf: [ {type: "string"}, { type: "object", properties: { properties: {$ref: "#/$defs/stringMap"}, items: {$ref: "#/$defs/stringList"}, required: {$ref: "#/$defs/stringOrMap"}, dependencies: {$ref: "#/$defs/stringOrMap"}, }, additionalProperties: {type: "string"}, }, ], $defs: { stringMap: { type: "object", additionalProperties: {type: "string"}, }, stringOrMap: { anyOf: [{type: "string"}, {$ref: "#/$defs/stringMap"}], }, stringList: {type: "array", items: {type: "string"}}, }, }, } }
interface ErrorMessageOptions { keepErrors?: boolean singleError?: boolean | string }
1,239
function childErrorsConfig({properties, items}: ErrorMessageSchema): ChildErrors { const errors: ChildErrors = {} if (properties) { errors.props = {} for (const p in properties) errors.props[p] = [] } if (items) { errors.items = {} for (let i = 0; i < items.length; i++) errors.items[i] = [] } return errors }
type ErrorMessageSchema = { properties?: StringMap items?: string[] required?: string | StringMap dependencies?: string | StringMap _?: string } & {[K in string]?: string | StringMap}
1,240
function keywordErrorsConfig( emSchema: ErrorMessageSchema ): [{[K in string]?: ErrorsMap<string>} | undefined, ErrorsMap<string> | undefined] { let propErrors: {[K in string]?: ErrorsMap<string>} | undefined let errors: ErrorsMap<string> | undefined for (const k in emSchema) { if (k === "properties" || k === "items") continue const kwdSch = emSchema[k] if (typeof kwdSch == "object") { propErrors ||= {} const errMap: ErrorsMap<string> = (propErrors[k] = {}) for (const p in kwdSch) errMap[p] = [] } else { errors ||= {} errors[k] = [] } } return [propErrors, errors] }
type ErrorMessageSchema = { properties?: StringMap items?: string[] required?: string | StringMap dependencies?: string | StringMap _?: string } & {[K in string]?: string | StringMap}
1,241
function processChildErrors(childErrors: ChildErrors): void { const {props, items} = childErrors if (!props && !items) return const isObj = _`typeof ${data} == "object"` const isArr = _`Array.isArray(${data})` const childErrs = gen.let("emErrors") let childKwd: Name let childProp: Code const templates = gen.let("templates") if (props && items) { childKwd = gen.let("emChildKwd") gen.if(isObj) gen.if( isArr, () => { init(items, schema.items) gen.assign(childKwd, str`items`) }, () => { init(props, schema.properties) gen.assign(childKwd, str`properties`) } ) childProp = _`[${childKwd}]` } else if (items) { gen.if(isArr) init(items, schema.items) childProp = _`.items` } else if (props) { gen.if(and(isObj, not(isArr))) init(props, schema.properties) childProp = _`.properties` } gen.forOf("err", N.vErrors, (err) => ifMatchesChildError(err, childErrs, (child) => gen.code(_`${childErrs}[${child}].push(${err})`).assign(_`${err}.${used}`, true) ) ) gen.forIn("key", childErrs, (key) => gen.if(_`${childErrs}[${key}].length`, () => { reportError(cxt, { message: _`${key} in ${templates} ? ${templates}[${key}]() : ${schemaValue}${childProp}[${key}]`, params: _`{errors: ${childErrs}[${key}]}`, }) gen.assign( _`${N.vErrors}[${N.errors}-1].instancePath`, _`${instancePath} + "/" + ${key}.replace(/~/g, "~0").replace(/\\//g, "~1")` ) }) ) gen.endIf() function init<T extends string | number>( children: ErrorsMap<T>, msgs: {[K in string]?: string} ): void { gen.assign(childErrs, stringify(children)) gen.assign(templates, getTemplatesCode(children, msgs)) } }
interface ChildErrors { props?: ErrorsMap<string> items?: ErrorsMap<number> }
1,242
( ajv: Ajv, options: ErrorMessageOptions = {} ): Ajv => { if (!ajv.opts.allErrors) throw new Error("ajv-errors: Ajv option allErrors must be true") if (ajv.opts.jsPropertySyntax) { throw new Error("ajv-errors: ajv option jsPropertySyntax is not supported") } return ajv.addKeyword(errorMessage(options)) }
interface ErrorMessageOptions { keepErrors?: boolean singleError?: boolean | string }
1,243
async callback( req: HttpProxyAgentClientRequest, opts: RequestOptions ): Promise<net.Socket> { const { proxy, secureProxy } = this; const parsed = url.parse(req.path); if (!parsed.protocol) { parsed.protocol = 'http:'; } if (!parsed.hostname) { parsed.hostname = opts.hostname || opts.host || null; } if (parsed.port == null && typeof opts.port) { parsed.port = String(opts.port); } if (parsed.port === '80') { // if port is 80, then we can remove the port so that the // ":80" portion is not on the produced URL parsed.port = ''; } // Change the `http.ClientRequest` instance's "path" field // to the absolute path of the URL that will be requested. req.path = url.format(parsed); // Inject the `Proxy-Authorization` header if necessary. if (proxy.auth) { req.setHeader( 'Proxy-Authorization', `Basic ${Buffer.from(proxy.auth).toString('base64')}` ); } // Create a socket connection to the proxy server. let socket: net.Socket; if (secureProxy) { debug('Creating `tls.Socket`: %o', proxy); socket = tls.connect(proxy as tls.ConnectionOptions); } else { debug('Creating `net.Socket`: %o', proxy); socket = net.connect(proxy as net.NetConnectOpts); } // At this point, the http ClientRequest's internal `_header` field // might have already been set. If this is the case then we'll need // to re-generate the string since we just changed the `req.path`. if (req._header) { let first: string; let endOfHeaders: number; debug('Regenerating stored HTTP header string for request'); req._header = null; req._implicitHeader(); if (req.output && req.output.length > 0) { // Node < 12 debug( 'Patching connection write() output buffer with updated header' ); first = req.output[0]; endOfHeaders = first.indexOf('\r\n\r\n') + 4; req.output[0] = req._header + first.substring(endOfHeaders); debug('Output buffer: %o', req.output); } else if (req.outputData && req.outputData.length > 0) { // Node >= 12 debug( 'Patching connection write() output buffer with updated header' ); first = req.outputData[0].data; endOfHeaders = first.indexOf('\r\n\r\n') + 4; req.outputData[0].data = req._header + first.substring(endOfHeaders); debug('Output buffer: %o', req.outputData[0].data); } } // Wait for the socket's `connect` event, so that this `callback()` // function throws instead of the `http` request machinery. This is // important for i.e. `PacProxyAgent` which determines a failed proxy // connection via the `callback()` function throwing. await once(socket, 'connect'); return socket; }
interface HttpProxyAgentClientRequest extends ClientRequest { path: string; output?: string[]; outputData?: { data: string; }[]; _header?: string | null; _implicitHeader(): void; }
1,244
formatSchema( schema: Schema, logic?: boolean, prevSchemas?: Array<Object> ): string
type Schema = import
1,245
formatSchema( schema: Schema, logic?: boolean, prevSchemas?: Array<Object> ): string
type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend;
1,246
formatSchema( schema: Schema, logic?: boolean, prevSchemas?: Array<Object> ): string
type Schema = import
1,247
formatValidationError(error: SchemaUtilErrorObject): string
type SchemaUtilErrorObject = import
1,248
formatValidationError(error: SchemaUtilErrorObject): string
type SchemaUtilErrorObject = ErrorObject & { children?: Array<ErrorObject>; };
1,249
formatValidationError(error: SchemaUtilErrorObject): string
type SchemaUtilErrorObject = import
1,250
function validate( schema: Schema, options: Array<object> | object, configuration?: ValidationErrorConfiguration | undefined ): void;
type Schema = import
1,251
function validate( schema: Schema, options: Array<object> | object, configuration?: ValidationErrorConfiguration | undefined ): void;
type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend;
1,252
function validate( schema: Schema, options: Array<object> | object, configuration?: ValidationErrorConfiguration | undefined ): void;
type Schema = import
1,253
function addAbsolutePathKeyword(ajv: Ajv): Ajv;
type Ajv = import
1,254
function stringHints(schema: Schema, logic: boolean): string[];
type Schema = import
1,255
function stringHints(schema: Schema, logic: boolean): string[];
type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend;
1,256
function stringHints(schema: Schema, logic: boolean): string[];
type Schema = import
1,257
function numberHints(schema: Schema, logic: boolean): string[];
type Schema = import
1,258
function numberHints(schema: Schema, logic: boolean): string[];
type Schema = (JSONSchema4 | JSONSchema6 | JSONSchema7) & Extend;
1,259
function numberHints(schema: Schema, logic: boolean): string[];
type Schema = import
1,260
(rangeValue: RangeValue) => boolean
type RangeValue = [number, boolean];
1,261
compile(schema: DefaultSchema, _parentSchema, it: SchemaCxt) { if (!it.opts.useDefaults || it.compositeRule) return () => true const fs: Record<string, () => any> = {} for (const key in schema) fs[key] = getDefault(schema[key]) const empty = it.opts.useDefaults === "empty" return (data: Record<string, any>) => { for (const prop in schema) { if (data[prop] === undefined || (empty && (data[prop] === null || data[prop] === ""))) { data[prop] = fs[prop]() } } return true } }
type DefaultSchema = Record<string, string | PropertyDefaultSchema | undefined>
1,262
function getObjDefault({func, args}: PropertyDefaultSchema): () => any { const def = DEFAULTS[func] assertDefined(func, def) return def(args) }
interface PropertyDefaultSchema { func: string args: Record<string, any> }
1,263
function ajvKeywords(opts?: DefinitionOptions): Vocabulary { return definitions.map((d) => d(opts)).concat(selectDef(opts)) }
interface DefinitionOptions { defaultMeta?: string | boolean }
1,264
function getRequiredDef( keyword: RequiredKwd ): GetDefinition<MacroKeywordDefinition> { return () => ({ keyword, type: "object", schemaType: "array", macro(schema: string[]) { if (schema.length === 0) return true if (schema.length === 1) return {required: schema} const comb = keyword === "anyRequired" ? "anyOf" : "oneOf" return {[comb]: schema.map((p) => ({required: [p]}))} }, metaSchema: { type: "array", items: {type: "string"}, }, }) }
type RequiredKwd = "anyRequired" | "oneRequired"
1,265
function getDef(opts?: DefinitionOptions): MacroKeywordDefinition { return { keyword: "deepProperties", type: "object", schemaType: "object", macro: function (schema: Record<string, SchemaObject>) { const allOf = [] for (const pointer in schema) allOf.push(getSchema(pointer, schema[pointer])) return {allOf} }, metaSchema: { type: "object", propertyNames: {type: "string", format: "json-pointer"}, additionalProperties: metaSchemaRef(opts), }, } }
interface DefinitionOptions { defaultMeta?: string | boolean }
1,266
function metaSchemaRef({defaultMeta}: DefinitionOptions = {}): SchemaObject { return defaultMeta === false ? {} : {$ref: defaultMeta || META_SCHEMA_ID} }
interface DefinitionOptions { defaultMeta?: string | boolean }
1,267
function getRangeDef(keyword: RangeKwd): GetDefinition<MacroKeywordDefinition> { return () => ({ keyword, type: "number", schemaType: "array", macro: function ([min, max]: [number, number]) { validateRangeSchema(min, max) return keyword === "range" ? {minimum: min, maximum: max} : {exclusiveMinimum: min, exclusiveMaximum: max} }, metaSchema: { type: "array", minItems: 2, maxItems: 2, items: {type: "number"}, }, }) function validateRangeSchema(min: number, max: number): void { if (min > max || (keyword === "exclusiveRange" && min === max)) { throw new Error("There are no numbers in range") } } }
type RangeKwd = "range" | "exclusiveRange"
1,268
function getDef(opts?: DefinitionOptions): KeywordDefinition[] { const metaSchema = metaSchemaRef(opts) return [ { keyword: "select", schemaType: ["string", "number", "boolean", "null"], $data: true, error, dependencies: ["selectCases"], code(cxt: KeywordCxt) { const {gen, schemaCode, parentSchema} = cxt cxt.block$data(nil, () => { const valid = gen.let("valid", true) const schValid = gen.name("_valid") const value = gen.const("value", _`${schemaCode} === null ? "null" : ${schemaCode}`) gen.if(false) // optimizer should remove it from generated code for (const schemaProp in parentSchema.selectCases) { cxt.setParams({schemaProp}) gen.elseIf(_`"" + ${value} == ${schemaProp}`) // intentional ==, to match numbers and booleans const schCxt = cxt.subschema({keyword: "selectCases", schemaProp}, schValid) cxt.mergeEvaluated(schCxt, Name) gen.assign(valid, schValid) } gen.else() if (parentSchema.selectDefault !== undefined) { cxt.setParams({schemaProp: undefined}) const schCxt = cxt.subschema({keyword: "selectDefault"}, schValid) cxt.mergeEvaluated(schCxt, Name) gen.assign(valid, schValid) } gen.endIf() cxt.pass(valid) }) }, }, { keyword: "selectCases", dependencies: ["select"], metaSchema: { type: "object", additionalProperties: metaSchema, }, }, { keyword: "selectDefault", dependencies: ["select", "selectCases"], metaSchema, }, ] }
interface DefinitionOptions { defaultMeta?: string | boolean }
1,269
(opts?: DefinitionOptions) => T
interface DefinitionOptions { defaultMeta?: string | boolean }
1,270
addRequest(req: ClientRequest, _opts: RequestOptions): void { const opts: RequestOptions = { ..._opts }; if (typeof opts.secureEndpoint !== 'boolean') { opts.secureEndpoint = isSecureEndpoint(); } if (opts.host == null) { opts.host = 'localhost'; } if (opts.port == null) { opts.port = opts.secureEndpoint ? 443 : 80; } if (opts.protocol == null) { opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; } if (opts.host && opts.path) { // If both a `host` and `path` are specified then it's most // likely the result of a `url.parse()` call... we need to // remove the `path` portion so that `net.connect()` doesn't // attempt to open that as a unix socket file. delete opts.path; } delete opts.agent; delete opts.hostname; delete opts._defaultAgent; delete opts.defaultPort; delete opts.createConnection; // Hint to use "Connection: close" // XXX: non-documented `http` module API :( req._last = true; req.shouldKeepAlive = false; let timedOut = false; let timeoutId: ReturnType<typeof setTimeout> | null = null; const timeoutMs = opts.timeout || this.timeout; const onerror = (err: NodeJS.ErrnoException) => { if (req._hadError) return; req.emit('error', err); // For Safety. Some additional errors might fire later on // and we need to make sure we don't double-fire the error event. req._hadError = true; }; const ontimeout = () => { timeoutId = null; timedOut = true; const err: NodeJS.ErrnoException = new Error( `A "socket" was not created for HTTP request before ${timeoutMs}ms` ); err.code = 'ETIMEOUT'; onerror(err); }; const callbackError = (err: NodeJS.ErrnoException) => { if (timedOut) return; if (timeoutId !== null) { clearTimeout(timeoutId); timeoutId = null; } onerror(err); }; const onsocket = (socket: AgentCallbackReturn) => { if (timedOut) return; if (timeoutId != null) { clearTimeout(timeoutId); timeoutId = null; } if (isAgent(socket)) { // `socket` is actually an `http.Agent` instance, so // relinquish responsibility for this `req` to the Agent // from here on debug( 'Callback returned another Agent instance %o', socket.constructor.name ); (socket as createAgent.Agent).addRequest(req, opts); return; } if (socket) { socket.once('free', () => { this.freeSocket(socket as net.Socket, opts); }); req.onSocket(socket as net.Socket); return; } const err = new Error( `no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\`` ); onerror(err); }; if (typeof this.callback !== 'function') { onerror(new Error('`callback` is not defined')); return; } if (!this.promisifiedCallback) { if (this.callback.length >= 3) { debug('Converting legacy callback function to promise'); this.promisifiedCallback = promisify(this.callback); } else { this.promisifiedCallback = this.callback; } } if (typeof timeoutMs === 'number' && timeoutMs > 0) { timeoutId = setTimeout(ontimeout, timeoutMs); } if ('port' in opts && typeof opts.port !== 'number') { opts.port = Number(opts.port); } try { debug( 'Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}` ); Promise.resolve(this.promisifiedCallback(req, opts)).then( onsocket, callbackError ); } catch (err) { Promise.reject(err).catch(callbackError); } }
interface ClientRequest extends http.ClientRequest { _last?: boolean; _hadError?: boolean; method: string; }
1,271
( req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback ) => void
interface ClientRequest extends http.ClientRequest { _last?: boolean; _hadError?: boolean; method: string; }
1,272
function promisify(fn: LegacyCallback): AgentCallbackPromise { return function(this: Agent, req: ClientRequest, opts: RequestOptions) { return new Promise((resolve, reject) => { fn.call( this, req, opts, (err: Error | null | undefined, rtn?: AgentCallbackReturn) => { if (err) { reject(err); } else { resolve(rtn!); } } ); }); }; }
type LegacyCallback = ( req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback ) => void;
1,273
function(this: Agent, req: ClientRequest, opts: RequestOptions) { return new Promise((resolve, reject) => { fn.call( this, req, opts, (err: Error | null | undefined, rtn?: AgentCallbackReturn) => { if (err) { reject(err); } else { resolve(rtn!); } } ); }); }
interface ClientRequest extends http.ClientRequest { _last?: boolean; _hadError?: boolean; method: string; }
1,274
(this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean
class AxiosHeaders { constructor( headers?: RawAxiosHeaders | AxiosHeaders ); [key: string]: any; set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; set(headers?: RawAxiosHeaders | AxiosHeaders, rewrite?: boolean): AxiosHeaders; get(headerName: string, parser: RegExp): RegExpExecArray | null; get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue; has(header: string, matcher?: true | AxiosHeaderMatcher): boolean; delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean; clear(matcher?: AxiosHeaderMatcher): boolean; normalize(format: boolean): AxiosHeaders; concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders; toJSON(asStrings?: boolean): RawAxiosHeaders; static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders; static accessor(header: string | string[]): AxiosHeaders; static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders; setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentType(parser?: RegExp): RegExpExecArray | null; getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentType(matcher?: AxiosHeaderMatcher): boolean; setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentLength(parser?: RegExp): RegExpExecArray | null; getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentLength(matcher?: AxiosHeaderMatcher): boolean; setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getAccept(parser?: RegExp): RegExpExecArray | null; getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasAccept(matcher?: AxiosHeaderMatcher): boolean; setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getUserAgent(parser?: RegExp): RegExpExecArray | null; getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasUserAgent(matcher?: AxiosHeaderMatcher): boolean; setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getContentEncoding(parser?: RegExp): RegExpExecArray | null; getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean; setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders; getAuthorization(parser?: RegExp): RegExpExecArray | null; getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue; hasAuthorization(matcher?: AxiosHeaderMatcher): boolean; [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>; }
1,275
(this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean
interface RawAxiosHeaders { [key: string]: AxiosHeaderValue; }
1,276
clear(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,277
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders
type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
1,278
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,279
hasContentType(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,280
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
1,281
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,282
hasContentLength(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,283
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
1,284
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,285
hasAccept(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,286
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
1,287
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,288
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,289
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
1,290
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,291
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,292
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
1,293
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,294
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
1,295
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any
type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
1,296
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> { headers: AxiosRequestHeaders; }
1,297
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any
type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
1,298
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> { headers: AxiosRequestHeaders; }
1,299
(config: InternalAxiosRequestConfig): AxiosPromise
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> { headers: AxiosRequestHeaders; }