updated action to work with slack
main.yml / A job to say hello (push) Failing after 2s
main.yml / A job to say hello (push) Failing after 2s
This commit is contained in:
@@ -10,6 +10,12 @@ jobs:
|
||||
uses: actions/[email protected]
|
||||
with:
|
||||
who-to-greet: 'Steve'
|
||||
channel-id: 'CTAAHRA79'
|
||||
message: 'posting from a github action!'
|
||||
env:
|
||||
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
|
||||
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
|
||||
|
||||
# Use the output from the `hello` step
|
||||
- name: Get the output time
|
||||
run: echo "The time was ${{ steps.hello.outputs.time }}"
|
||||
-104
@@ -1,104 +0,0 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and *not* Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
@@ -5,6 +5,12 @@ inputs:
|
||||
description: 'Who to greet'
|
||||
required: true
|
||||
default: 'World'
|
||||
channel-id: # channel id to post message when using bot token
|
||||
description: 'Slack channel ID where message will be posted. Needed if using bot token'
|
||||
required: false
|
||||
message: # message to post when using bot token
|
||||
description: 'Message to post into Slack. Needed if using bot token'
|
||||
required: false
|
||||
outputs:
|
||||
time: # id of output
|
||||
description: 'The time we greeted you'
|
||||
|
||||
@@ -1,15 +1,65 @@
|
||||
const core = require('@actions/core');
|
||||
const github = require('@actions/github');
|
||||
const { WebClient } = require('@slack/web-api');
|
||||
const flatten = require('flat');
|
||||
const axios = require('axios');
|
||||
|
||||
|
||||
|
||||
try {
|
||||
// `who-to-greet` input defined in action metadata file
|
||||
const nameToGreet = core.getInput('who-to-greet');
|
||||
console.log(`Hello ${nameToGreet}!`);
|
||||
const time = (new Date()).toTimeString();
|
||||
core.setOutput("time", time);
|
||||
// Get the JSON webhook payload for the event that triggered the workflow
|
||||
const payload = JSON.stringify(github.context.payload, undefined, 2)
|
||||
console.log(`The event payload: ${payload}`);
|
||||
} catch (error) {
|
||||
core.setFailed(error.message);
|
||||
// `who-to-greet` input defined in action metadata file
|
||||
const nameToGreet = core.getInput('who-to-greet');
|
||||
|
||||
const botToken = process.env.SLACK_BOT_TOKEN;
|
||||
const webhookUrl = process.env.SLACK_WEBHOOK_URL;
|
||||
|
||||
console.log('botToken', botToken)
|
||||
console.log('webhookUrl', webhookUrl)
|
||||
|
||||
// Get the JSON webhook payload for the event that triggered the workflow
|
||||
const payload = github.context.payload;
|
||||
console.log(`The event payload: ${JSON.stringify(payload, undefined, 2)}`);
|
||||
|
||||
if (botToken) {
|
||||
const message = core.getInput('slack-message');
|
||||
const channelId = core.getInput('channel-id');
|
||||
console.log('message', message)
|
||||
console.log('channelId', channelId)
|
||||
|
||||
const web = new WebClient(botToken);
|
||||
|
||||
if(channelId === undefined) {
|
||||
console.log('no channel ID error')
|
||||
throw 'no channel Id supplied';
|
||||
}
|
||||
|
||||
// post message
|
||||
web.chat.postMessage({text: message, channel: channelId})
|
||||
} else if (webhookUrl) {
|
||||
// send flat payload to webhookUrl
|
||||
const flatPayload = flatten(payload);
|
||||
|
||||
// workflow builder requires values to be strings
|
||||
// iterate over every value and convert it to string
|
||||
Object.keys(flatPayload).forEach((key) => {
|
||||
flatPayload[key] = '' + flatPayload[key];
|
||||
})
|
||||
|
||||
// console.log(flatPayload);
|
||||
// console.log(req.path);
|
||||
|
||||
axios.post(webhookUrl, flatPayload)
|
||||
} else {
|
||||
console.log('should throw error');
|
||||
throw 'could not post';
|
||||
}
|
||||
|
||||
|
||||
|
||||
console.log(`Hello ${nameToGreet}!`);
|
||||
const time = (new Date()).toTimeString();
|
||||
core.setOutput("time", time);
|
||||
|
||||
} catch (error) {
|
||||
core.setFailed(error.message);
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../flat/cli.js
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2014-2019 Slack Technologies, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* Severity levels for log entries
|
||||
*/
|
||||
export declare enum LogLevel {
|
||||
ERROR = "error",
|
||||
WARN = "warn",
|
||||
INFO = "info",
|
||||
DEBUG = "debug"
|
||||
}
|
||||
/**
|
||||
* Interface for objects where objects in this package's logs can be sent (can be used as `logger` option).
|
||||
*/
|
||||
export interface Logger {
|
||||
/**
|
||||
* Output debug message
|
||||
*
|
||||
* @param msg any data to log
|
||||
*/
|
||||
debug(...msg: any[]): void;
|
||||
/**
|
||||
* Output info message
|
||||
*
|
||||
* @param msg any data to log
|
||||
*/
|
||||
info(...msg: any[]): void;
|
||||
/**
|
||||
* Output warn message
|
||||
*
|
||||
* @param msg any data to log
|
||||
*/
|
||||
warn(...msg: any[]): void;
|
||||
/**
|
||||
* Output error message
|
||||
*
|
||||
* @param msg any data to log
|
||||
*/
|
||||
error(...msg: any[]): void;
|
||||
/**
|
||||
* This disables all logging below the given level, so that after a log.setLevel("warn") call log.warn("something")
|
||||
* or log.error("something") will output messages, but log.info("something") will not.
|
||||
*
|
||||
* @param level as a string, like 'error' (case-insensitive)
|
||||
*/
|
||||
setLevel(level: LogLevel): void;
|
||||
/**
|
||||
* Return the current LogLevel.
|
||||
*/
|
||||
getLevel(): LogLevel;
|
||||
/**
|
||||
* This allows the instance to be named so that they can easily be filtered when many loggers are sending output
|
||||
* to the same destination.
|
||||
*
|
||||
* @param name as a string, will be output with every log after the level
|
||||
*/
|
||||
setName(name: string): void;
|
||||
}
|
||||
/**
|
||||
* Default logger which logs to stdout and stderr
|
||||
*/
|
||||
export declare class ConsoleLogger implements Logger {
|
||||
/** Setting for level */
|
||||
private level;
|
||||
/** Name */
|
||||
private name;
|
||||
/** Map of labels for each log level */
|
||||
private static labels;
|
||||
/** Map of severity as comparable numbers for each log level */
|
||||
private static severity;
|
||||
constructor();
|
||||
getLevel(): LogLevel;
|
||||
/**
|
||||
* Sets the instance's log level so that only messages which are equal or more severe are output to the console.
|
||||
*/
|
||||
setLevel(level: LogLevel): void;
|
||||
/**
|
||||
* Set the instance's name, which will appear on each log line before the message.
|
||||
*/
|
||||
setName(name: string): void;
|
||||
/**
|
||||
* Log a debug message
|
||||
*/
|
||||
debug(...msg: any[]): void;
|
||||
/**
|
||||
* Log an info message
|
||||
*/
|
||||
info(...msg: any[]): void;
|
||||
/**
|
||||
* Log a warning message
|
||||
*/
|
||||
warn(...msg: any[]): void;
|
||||
/**
|
||||
* Log an error message
|
||||
*/
|
||||
error(...msg: any[]): void;
|
||||
/**
|
||||
* Helper to compare two log levels and determine if a is equal or more severe than b
|
||||
*/
|
||||
private static isMoreOrEqualSevere;
|
||||
}
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,QAAQ;IAClB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,IAAI,SAAS;IACb,KAAK,UAAU;CAChB;AAED;;GAEG;AACH,MAAM,WAAW,MAAM;IACrB;;;;OAIG;IACH,KAAK,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAE3B;;;;OAIG;IACH,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAE1B;;;;OAIG;IACH,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAE1B;;;;OAIG;IACH,KAAK,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;IAE3B;;;;;OAKG;IACH,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,CAAC;IAEhC;;OAEG;IACH,QAAQ,IAAI,QAAQ,CAAC;IAErB;;;;;OAKG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED;;GAEG;AACH,qBAAa,aAAc,YAAW,MAAM;IAC1C,wBAAwB;IACxB,OAAO,CAAC,KAAK,CAAW;IACxB,WAAW;IACX,OAAO,CAAC,IAAI,CAAS;IACrB,uCAAuC;IACvC,OAAO,CAAC,MAAM,CAAC,MAAM,CAMhB;IACL,+DAA+D;IAC/D,OAAO,CAAC,MAAM,CAAC,QAAQ,CAKrB;;IAOK,QAAQ,IAAI,QAAQ;IAI3B;;OAEG;IACI,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI;IAItC;;OAEG;IACI,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI;IAIlC;;OAEG;IACI,KAAK,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;IAKjC;;OAEG;IACI,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;IAKhC;;OAEG;IACI,IAAI,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;IAKhC;;OAEG;IACI,KAAK,CAAC,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;IAMjC;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,mBAAmB;CAGnC"}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/**
|
||||
* Severity levels for log entries
|
||||
*/
|
||||
var LogLevel;
|
||||
(function (LogLevel) {
|
||||
LogLevel["ERROR"] = "error";
|
||||
LogLevel["WARN"] = "warn";
|
||||
LogLevel["INFO"] = "info";
|
||||
LogLevel["DEBUG"] = "debug";
|
||||
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
|
||||
/**
|
||||
* Default logger which logs to stdout and stderr
|
||||
*/
|
||||
class ConsoleLogger {
|
||||
constructor() {
|
||||
this.level = LogLevel.INFO;
|
||||
this.name = '';
|
||||
}
|
||||
getLevel() {
|
||||
return this.level;
|
||||
}
|
||||
/**
|
||||
* Sets the instance's log level so that only messages which are equal or more severe are output to the console.
|
||||
*/
|
||||
setLevel(level) {
|
||||
this.level = level;
|
||||
}
|
||||
/**
|
||||
* Set the instance's name, which will appear on each log line before the message.
|
||||
*/
|
||||
setName(name) {
|
||||
this.name = name;
|
||||
}
|
||||
/**
|
||||
* Log a debug message
|
||||
*/
|
||||
debug(...msg) {
|
||||
if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.DEBUG, this.level)) {
|
||||
console.debug(ConsoleLogger.labels.get(LogLevel.DEBUG), this.name, ...msg);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Log an info message
|
||||
*/
|
||||
info(...msg) {
|
||||
if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.INFO, this.level)) {
|
||||
console.info(ConsoleLogger.labels.get(LogLevel.INFO), this.name, ...msg);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Log a warning message
|
||||
*/
|
||||
warn(...msg) {
|
||||
if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.WARN, this.level)) {
|
||||
console.warn(ConsoleLogger.labels.get(LogLevel.WARN), this.name, ...msg);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Log an error message
|
||||
*/
|
||||
error(...msg) {
|
||||
if (ConsoleLogger.isMoreOrEqualSevere(LogLevel.ERROR, this.level)) {
|
||||
console.error(ConsoleLogger.labels.get(LogLevel.ERROR), this.name, ...msg);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Helper to compare two log levels and determine if a is equal or more severe than b
|
||||
*/
|
||||
static isMoreOrEqualSevere(a, b) {
|
||||
return ConsoleLogger.severity[a] >= ConsoleLogger.severity[b];
|
||||
}
|
||||
}
|
||||
/** Map of labels for each log level */
|
||||
ConsoleLogger.labels = (() => {
|
||||
const entries = Object.entries(LogLevel);
|
||||
const map = entries.map(([key, value]) => {
|
||||
return [value, `[${key}] `];
|
||||
});
|
||||
return new Map(map);
|
||||
})();
|
||||
/** Map of severity as comparable numbers for each log level */
|
||||
ConsoleLogger.severity = {
|
||||
[LogLevel.ERROR]: 400,
|
||||
[LogLevel.WARN]: 300,
|
||||
[LogLevel.INFO]: 200,
|
||||
[LogLevel.DEBUG]: 100,
|
||||
};
|
||||
exports.ConsoleLogger = ConsoleLogger;
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;AAAA;;GAEG;AACH,IAAY,QAKX;AALD,WAAY,QAAQ;IAClB,2BAAe,CAAA;IACf,yBAAa,CAAA;IACb,yBAAa,CAAA;IACb,2BAAe,CAAA;AACjB,CAAC,EALW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAKnB;AAwDD;;GAEG;AACH,MAAa,aAAa;IAqBxB;QACE,IAAI,CAAC,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC;IACjB,CAAC;IAEM,QAAQ;QACb,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,QAAQ,CAAC,KAAe;QAC7B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED;;OAEG;IACI,OAAO,CAAC,IAAY;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,GAAG,GAAU;QACxB,IAAI,aAAa,CAAC,mBAAmB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE;YACjE,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC;SAC5E;IACH,CAAC;IACD;;OAEG;IACI,IAAI,CAAC,GAAG,GAAU;QACvB,IAAI,aAAa,CAAC,mBAAmB,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE;YAChE,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC;SAC1E;IACH,CAAC;IACD;;OAEG;IACI,IAAI,CAAC,GAAG,GAAU;QACvB,IAAI,aAAa,CAAC,mBAAmB,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE;YAChE,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC;SAC1E;IACH,CAAC;IACD;;OAEG;IACI,KAAK,CAAC,GAAG,GAAU;QACxB,IAAI,aAAa,CAAC,mBAAmB,CAAC,QAAQ,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE;YACjE,OAAO,CAAC,KAAK,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,GAAG,CAAC,CAAC;SAC5E;IACH,CAAC;IAED;;OAEG;IACK,MAAM,CAAC,mBAAmB,CAAC,CAAW,EAAE,CAAW;QACzD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAChE,CAAC;;AA7ED,uCAAuC;AACxB,oBAAM,GAA0B,CAAC,GAAG,EAAE;IACnD,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,QAAQ,CAA2B,CAAC;IACnE,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QACvC,OAAO,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,CAAuB,CAAC;IACpD,CAAC,CAAC,CAAC;IACH,OAAO,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC,CAAC,EAAE,CAAC;AACL,+DAA+D;AAChD,sBAAQ,GAAkC;IACvD,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,GAAG;IACrB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,GAAG;IACpB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,GAAG;IACpB,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,GAAG;CACtB,CAAC;AAnBJ,sCAmFC"}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"_from": "@slack/logger@>=1.0.0 <3.0.0",
|
||||
"_id": "@slack/[email protected]",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-OkIJpiU2fz6HOJujhlhfIGrc8hB4ibqtf7nnbJQDerG0BqwZCfmgtK5sWzZ0TkXVRBKD5MpLrTmCYyMxoMCgPw==",
|
||||
"_location": "/@slack/logger",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "@slack/logger@>=1.0.0 <3.0.0",
|
||||
"name": "@slack/logger",
|
||||
"escapedName": "@slack%2flogger",
|
||||
"scope": "@slack",
|
||||
"rawSpec": ">=1.0.0 <3.0.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": ">=1.0.0 <3.0.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/@slack/web-api"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/@slack/logger/-/logger-2.0.0.tgz",
|
||||
"_shasum": "6a4e1c755849bc0f66dac08a8be54ce790ec0e6b",
|
||||
"_spec": "@slack/logger@>=1.0.0 <3.0.0",
|
||||
"_where": "/Users/stevengill/repo/slack-github-action/node_modules/@slack/web-api",
|
||||
"author": {
|
||||
"name": "Slack Technologies, Inc."
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/slackapi/node-slack-sdk/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"@types/node": ">=8.9.0"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Logging utility used by Node Slack SDK",
|
||||
"devDependencies": {
|
||||
"@types/chai": "^4.1.7",
|
||||
"@types/mocha": "^5.2.6",
|
||||
"chai": "^4.2.0",
|
||||
"mocha": "^6.1.4",
|
||||
"nyc": "^14.1.1",
|
||||
"shx": "^0.3.2",
|
||||
"ts-node": "^8.2.0",
|
||||
"tslint": "^5.13.1",
|
||||
"tslint-config-airbnb": "^5.11.1",
|
||||
"typescript": "^3.3.3333"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.9.0",
|
||||
"npm": ">= 5.5.1"
|
||||
},
|
||||
"files": [
|
||||
"dist/**/*"
|
||||
],
|
||||
"gitHead": "60a33b5de096255c4c1b714d3ff1c820e1b50e33",
|
||||
"homepage": "https://slack.dev/node-slack-sdk",
|
||||
"keywords": [
|
||||
"slack",
|
||||
"logging"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "dist/index.js",
|
||||
"name": "@slack/logger",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/slackapi/node-slack-sdk.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:clean && tsc",
|
||||
"build:clean": "shx rm -rf ./dist",
|
||||
"lint": "tslint --project .",
|
||||
"prepare": "npm run build",
|
||||
"test": "npm run build && nyc mocha --config .mocharc.json src/*.spec.js"
|
||||
},
|
||||
"types": "dist/index.d.ts",
|
||||
"version": "2.0.0"
|
||||
}
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
export interface Dialog {
|
||||
title: string;
|
||||
callback_id: string;
|
||||
elements: {
|
||||
type: 'text' | 'textarea' | 'select';
|
||||
name: string;
|
||||
label: string;
|
||||
optional?: boolean;
|
||||
placeholder?: string;
|
||||
value?: string;
|
||||
max_length?: number;
|
||||
min_length?: number;
|
||||
hint?: string;
|
||||
subtype?: 'email' | 'number' | 'tel' | 'url';
|
||||
data_source?: 'users' | 'channels' | 'conversations' | 'external';
|
||||
selected_options?: SelectOption[];
|
||||
options?: SelectOption[];
|
||||
option_groups?: {
|
||||
label: string;
|
||||
options: SelectOption[];
|
||||
}[];
|
||||
min_query_length?: number;
|
||||
}[];
|
||||
submit_label?: string;
|
||||
notify_on_cancel?: boolean;
|
||||
state?: string;
|
||||
}
|
||||
export interface View {
|
||||
title?: PlainTextElement;
|
||||
type: 'home' | 'modal' | 'workflow_step';
|
||||
blocks: (KnownBlock | Block)[];
|
||||
callback_id?: string;
|
||||
close?: PlainTextElement;
|
||||
submit?: PlainTextElement;
|
||||
private_metadata?: string;
|
||||
clear_on_close?: boolean;
|
||||
notify_on_close?: boolean;
|
||||
submit_disabled?: boolean;
|
||||
external_id?: string;
|
||||
}
|
||||
export interface ImageElement {
|
||||
type: 'image';
|
||||
image_url: string;
|
||||
alt_text: string;
|
||||
}
|
||||
export interface PlainTextElement {
|
||||
type: 'plain_text';
|
||||
text: string;
|
||||
emoji?: boolean;
|
||||
}
|
||||
export interface MrkdwnElement {
|
||||
type: 'mrkdwn';
|
||||
text: string;
|
||||
verbatim?: boolean;
|
||||
}
|
||||
export interface Option {
|
||||
text: PlainTextElement | MrkdwnElement;
|
||||
value?: string;
|
||||
url?: string;
|
||||
description?: PlainTextElement;
|
||||
}
|
||||
export interface Confirm {
|
||||
title?: PlainTextElement;
|
||||
text: PlainTextElement | MrkdwnElement;
|
||||
confirm?: PlainTextElement;
|
||||
deny?: PlainTextElement;
|
||||
style?: 'primary' | 'danger';
|
||||
}
|
||||
export declare type Select = UsersSelect | StaticSelect | ConversationsSelect | ChannelsSelect | ExternalSelect;
|
||||
export declare type MultiSelect = MultiUsersSelect | MultiStaticSelect | MultiConversationsSelect | MultiChannelsSelect | MultiExternalSelect;
|
||||
export interface Action {
|
||||
type: string;
|
||||
action_id?: string;
|
||||
}
|
||||
export interface UsersSelect extends Action {
|
||||
type: 'users_select';
|
||||
initial_user?: string;
|
||||
placeholder?: PlainTextElement;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface MultiUsersSelect extends Action {
|
||||
type: 'multi_users_select';
|
||||
initial_users?: string[];
|
||||
placeholder?: PlainTextElement;
|
||||
max_selected_items?: number;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface StaticSelect extends Action {
|
||||
type: 'static_select';
|
||||
placeholder?: PlainTextElement;
|
||||
initial_option?: Option;
|
||||
options?: Option[];
|
||||
option_groups?: {
|
||||
label: PlainTextElement;
|
||||
options: Option[];
|
||||
}[];
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface MultiStaticSelect extends Action {
|
||||
type: 'multi_static_select';
|
||||
placeholder?: PlainTextElement;
|
||||
initial_options?: Option[];
|
||||
options?: Option[];
|
||||
option_groups?: {
|
||||
label: PlainTextElement;
|
||||
options: Option[];
|
||||
}[];
|
||||
max_selected_items?: number;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface ConversationsSelect extends Action {
|
||||
type: 'conversations_select';
|
||||
initial_conversation?: string;
|
||||
placeholder?: PlainTextElement;
|
||||
confirm?: Confirm;
|
||||
response_url_enabled?: boolean;
|
||||
default_to_current_conversation?: boolean;
|
||||
filter?: {
|
||||
include?: ('im' | 'mpim' | 'private' | 'public')[];
|
||||
exclude_external_shared_channels?: boolean;
|
||||
exclude_bot_users?: boolean;
|
||||
};
|
||||
}
|
||||
export interface MultiConversationsSelect extends Action {
|
||||
type: 'multi_conversations_select';
|
||||
initial_conversations?: string[];
|
||||
placeholder?: PlainTextElement;
|
||||
max_selected_items?: number;
|
||||
confirm?: Confirm;
|
||||
default_to_current_conversation?: boolean;
|
||||
filter?: {
|
||||
include?: ('im' | 'mpim' | 'private' | 'public')[];
|
||||
exclude_external_shared_channels?: boolean;
|
||||
exclude_bot_users?: boolean;
|
||||
};
|
||||
}
|
||||
export interface ChannelsSelect extends Action {
|
||||
type: 'channels_select';
|
||||
initial_channel?: string;
|
||||
placeholder?: PlainTextElement;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface MultiChannelsSelect extends Action {
|
||||
type: 'multi_channels_select';
|
||||
initial_channels?: string[];
|
||||
placeholder?: PlainTextElement;
|
||||
max_selected_items?: number;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface ExternalSelect extends Action {
|
||||
type: 'external_select';
|
||||
initial_option?: Option;
|
||||
placeholder?: PlainTextElement;
|
||||
min_query_length?: number;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface MultiExternalSelect extends Action {
|
||||
type: 'multi_external_select';
|
||||
initial_options?: Option[];
|
||||
placeholder?: PlainTextElement;
|
||||
min_query_length?: number;
|
||||
max_selected_items?: number;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface Button extends Action {
|
||||
type: 'button';
|
||||
text: PlainTextElement;
|
||||
value?: string;
|
||||
url?: string;
|
||||
style?: 'danger' | 'primary';
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface Overflow extends Action {
|
||||
type: 'overflow';
|
||||
options: Option[];
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface Datepicker extends Action {
|
||||
type: 'datepicker';
|
||||
initial_date?: string;
|
||||
placeholder?: PlainTextElement;
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface RadioButtons extends Action {
|
||||
type: 'radio_buttons';
|
||||
initial_option?: Option;
|
||||
options: Option[];
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface Checkboxes extends Action {
|
||||
type: 'checkboxes';
|
||||
initial_options?: Option[];
|
||||
options: Option[];
|
||||
confirm?: Confirm;
|
||||
}
|
||||
export interface PlainTextInput extends Action {
|
||||
type: 'plain_text_input';
|
||||
placeholder?: PlainTextElement;
|
||||
initial_value?: string;
|
||||
multiline?: boolean;
|
||||
min_length?: number;
|
||||
max_length?: number;
|
||||
dispatch_action_config?: DispatchActionConfig;
|
||||
}
|
||||
export interface DispatchActionConfig {
|
||||
trigger_actions_on?: ('on_enter_pressed' | 'on_character_entered')[];
|
||||
}
|
||||
export declare type KnownBlock = ImageBlock | ContextBlock | ActionsBlock | DividerBlock | SectionBlock | InputBlock | FileBlock | HeaderBlock;
|
||||
export interface Block {
|
||||
type: string;
|
||||
block_id?: string;
|
||||
}
|
||||
export interface ImageBlock extends Block {
|
||||
type: 'image';
|
||||
image_url: string;
|
||||
alt_text: string;
|
||||
title?: PlainTextElement;
|
||||
}
|
||||
export interface ContextBlock extends Block {
|
||||
type: 'context';
|
||||
elements: (ImageElement | PlainTextElement | MrkdwnElement)[];
|
||||
}
|
||||
export interface ActionsBlock extends Block {
|
||||
type: 'actions';
|
||||
elements: (Button | Overflow | Datepicker | Select | RadioButtons | Checkboxes | Action)[];
|
||||
}
|
||||
export interface DividerBlock extends Block {
|
||||
type: 'divider';
|
||||
}
|
||||
export interface SectionBlock extends Block {
|
||||
type: 'section';
|
||||
text?: PlainTextElement | MrkdwnElement;
|
||||
fields?: (PlainTextElement | MrkdwnElement)[];
|
||||
accessory?: Button | Overflow | Datepicker | Select | MultiSelect | Action | ImageElement | RadioButtons | Checkboxes;
|
||||
}
|
||||
export interface FileBlock extends Block {
|
||||
type: 'file';
|
||||
source: string;
|
||||
external_id: string;
|
||||
}
|
||||
export interface HeaderBlock extends Block {
|
||||
type: 'header';
|
||||
text: PlainTextElement;
|
||||
}
|
||||
export interface InputBlock extends Block {
|
||||
type: 'input';
|
||||
label: PlainTextElement;
|
||||
hint?: PlainTextElement;
|
||||
optional?: boolean;
|
||||
element: Select | MultiSelect | Datepicker | PlainTextInput | RadioButtons | Checkboxes;
|
||||
dispatch_action?: boolean;
|
||||
}
|
||||
export interface MessageAttachment {
|
||||
blocks?: (KnownBlock | Block)[];
|
||||
fallback?: string;
|
||||
color?: 'good' | 'warning' | 'danger' | string;
|
||||
pretext?: string;
|
||||
author_name?: string;
|
||||
author_link?: string;
|
||||
author_icon?: string;
|
||||
title?: string;
|
||||
title_link?: string;
|
||||
text?: string;
|
||||
fields?: {
|
||||
title: string;
|
||||
value: string;
|
||||
short?: boolean;
|
||||
}[];
|
||||
image_url?: string;
|
||||
thumb_url?: string;
|
||||
footer?: string;
|
||||
footer_icon?: string;
|
||||
ts?: string;
|
||||
actions?: AttachmentAction[];
|
||||
callback_id?: string;
|
||||
mrkdwn_in?: ('pretext' | 'text' | 'fields')[];
|
||||
}
|
||||
export interface AttachmentAction {
|
||||
id?: string;
|
||||
confirm?: Confirmation;
|
||||
data_source?: 'static' | 'channels' | 'conversations' | 'users' | 'external';
|
||||
min_query_length?: number;
|
||||
name?: string;
|
||||
options?: OptionField[];
|
||||
option_groups?: {
|
||||
text: string;
|
||||
options: OptionField[];
|
||||
}[];
|
||||
selected_options?: OptionField[];
|
||||
style?: 'default' | 'primary' | 'danger';
|
||||
text: string;
|
||||
type: 'button' | 'select';
|
||||
value?: string;
|
||||
url?: string;
|
||||
}
|
||||
export interface OptionField {
|
||||
description?: string;
|
||||
text: string;
|
||||
value: string;
|
||||
}
|
||||
export interface Confirmation {
|
||||
dismiss_text?: string;
|
||||
ok_text?: string;
|
||||
text: string;
|
||||
title?: string;
|
||||
}
|
||||
export interface LinkUnfurls {
|
||||
[linkUrl: string]: MessageAttachment;
|
||||
}
|
||||
export interface SelectOption {
|
||||
label: string;
|
||||
value: string;
|
||||
}
|
||||
export declare type CallUser = CallUserSlack | CallUserExternal;
|
||||
export interface CallUserSlack {
|
||||
slack_id: string;
|
||||
}
|
||||
export interface CallUserExternal {
|
||||
external_id: string;
|
||||
display_name: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
File diff suppressed because one or more lines are too long
+3
@@ -0,0 +1,3 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"_from": "@slack/types@^1.7.0",
|
||||
"_id": "@slack/[email protected]",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-tA7GG7Tj479vojfV3AoxbckalA48aK6giGjNtgH6ihpLwTyHE3fIgRrvt8TWfLwW8X8dyu7vgmAsGLRG7hWWOg==",
|
||||
"_location": "/@slack/types",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "@slack/types@^1.7.0",
|
||||
"name": "@slack/types",
|
||||
"escapedName": "@slack%2ftypes",
|
||||
"scope": "@slack",
|
||||
"rawSpec": "^1.7.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^1.7.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/@slack/web-api"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/@slack/types/-/types-1.10.0.tgz",
|
||||
"_shasum": "cbf7d83e1027f4cbfd13d6b429f120c7fb09127a",
|
||||
"_spec": "@slack/types@^1.7.0",
|
||||
"_where": "/Users/stevengill/repo/slack-github-action/node_modules/@slack/web-api",
|
||||
"author": {
|
||||
"name": "Slack Technologies, Inc."
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/slackapi/node-slack-sdk/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"deprecated": false,
|
||||
"description": "Shared type definitions for the Node Slack SDK",
|
||||
"devDependencies": {
|
||||
"@microsoft/api-extractor": "^7.3.4",
|
||||
"shx": "^0.3.2",
|
||||
"tslint": "^5.13.1",
|
||||
"tslint-config-airbnb": "^5.11.1",
|
||||
"typescript": "^3.3.3333"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.9.0",
|
||||
"npm": ">= 5.5.1"
|
||||
},
|
||||
"files": [
|
||||
"dist/**/*"
|
||||
],
|
||||
"homepage": "https://slack.dev/node-slack-sdk",
|
||||
"keywords": [
|
||||
"slack",
|
||||
"typescript",
|
||||
"types",
|
||||
"api"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "dist/index.js",
|
||||
"name": "@slack/types",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/slackapi/node-slack-sdk.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:clean && tsc",
|
||||
"build:clean": "shx rm -rf ./dist",
|
||||
"lint": "tslint --project .",
|
||||
"prepare": "npm run build",
|
||||
"ref-docs:model": "api-extractor run",
|
||||
"test": "npm run build && echo \"Tests are not implemented.\" && exit 0"
|
||||
},
|
||||
"types": "dist/index.d.ts",
|
||||
"version": "1.10.0"
|
||||
}
|
||||
+394
@@ -0,0 +1,394 @@
|
||||
# Slack Web API
|
||||
|
||||
<!-- TODO: per-job badge https://github.com/bjfish/travis-matrix-badges/issues/4 -->
|
||||
[](https://travis-ci.org/slackapi/node-slack-sdk)
|
||||
<!-- TODO: per-flag badge https://docs.codecov.io/docs/flags#section-flag-badges-and-graphs -->
|
||||
[](https://codecov.io/gh/slackapi/node-slack-sdk)
|
||||
<!-- TODO: npm versions with scoped packages: https://github.com/rvagg/nodei.co/issues/24 -->
|
||||
|
||||
The `@slack/web-api` package contains a simple, convenient, and configurable HTTP client for making requests to Slack's
|
||||
[Web API](https://api.slack.com/web). Use it in your app to call any of the over 130
|
||||
[methods](https://api.slack.com/methods), and let it handle formatting, queuing, retrying, pagination, and more.
|
||||
|
||||
## Installation
|
||||
|
||||
```shell
|
||||
$ npm install @slack/web-api
|
||||
```
|
||||
|
||||
<!-- START: Remove before copying into the docs directory -->
|
||||
|
||||
## Usage
|
||||
|
||||
These examples show the most common features of the `WebClient`. You'll find even more extensive [documentation on the
|
||||
package's website](https://slack.dev/node-slack-sdk/web-api).
|
||||
|
||||
<!-- END: Remove before copying into the docs directory -->
|
||||
|
||||
---
|
||||
|
||||
### Initialize the client
|
||||
|
||||
The package exports a `WebClient` class. All you need to do is instantiate it, and you're ready to go. You'll typically
|
||||
initialize it with a `token`, so that you don't have to provide the token each time you call a method. A token usually
|
||||
begins with `xoxb` or `xoxp`. You get them from each workspace an app is installed onto. The app configuration pages
|
||||
help you get your first token for your development workspace.
|
||||
|
||||
```javascript
|
||||
const { WebClient } = require('@slack/web-api');
|
||||
|
||||
// Read a token from the environment variables
|
||||
const token = process.env.SLACK_TOKEN;
|
||||
|
||||
// Initialize
|
||||
const web = new WebClient(token);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary markdown="span">
|
||||
<strong><i>Initializing without a token</i></strong>
|
||||
</summary>
|
||||
|
||||
Alternatively, you can create a client without a token, and use it with multiple workspaces as long as you supply a
|
||||
`token` when you call a method.
|
||||
|
||||
```javascript
|
||||
const { WebClient } = require('@slack/web-api');
|
||||
|
||||
// Initialize a single instance for the whole app
|
||||
const web = new WebClient();
|
||||
|
||||
// Find a token in storage (database) before making an API method call
|
||||
(async () => {
|
||||
// Some fictitious database
|
||||
const token = await db.findTokenByTeam(teamId, enterpriseId)
|
||||
|
||||
// Call the method
|
||||
const result = web.auth.test({ token });
|
||||
})();
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### Call a method
|
||||
|
||||
The client instance has a named method for each of the public methods in the Web API. The most popular one is
|
||||
called `chat.postMessage`, and it's used to send a message to a conversation. For every method, you pass arguments as
|
||||
properties of an options object. This helps with the readability of your code since every argument has a name. All
|
||||
named methods return a `Promise` which resolves with the response data or rejects with an error.
|
||||
|
||||
```javascript
|
||||
// Given some known conversation ID (representing a public channel, private channel, DM or group DM)
|
||||
const conversationId = '...';
|
||||
|
||||
(async () => {
|
||||
|
||||
// Post a message to the channel, and await the result.
|
||||
// Find more arguments and details of the response: https://api.slack.com/methods/chat.postMessage
|
||||
const result = await web.chat.postMessage({
|
||||
text: 'Hello world!',
|
||||
channel: conversationId,
|
||||
});
|
||||
|
||||
// The result contains an identifier for the message, `ts`.
|
||||
console.log(`Successfully send message ${result.ts} in conversation ${conversationId}`);
|
||||
})();
|
||||
```
|
||||
|
||||
**Tip**: If you're using an editor that supports TypeScript, even if you're not using TypeScript to write your code,
|
||||
you'll get hints for all the arguments each method supports. This helps you save time by reducing the number of
|
||||
times you need to pop out to a webpage to check the reference. There's more information about [using
|
||||
TypeScript](https://slack.dev/node-slack-sdk/typescript) with this package in the documentation website.
|
||||
|
||||
**Tip**: Use the [Block Kit Builder](https://api.slack.com/tools/block-kit-builder) for a playground
|
||||
where you can prototype your message's look and feel.
|
||||
|
||||
<details>
|
||||
<summary markdown="span">
|
||||
<strong><i>Using a dynamic method name</i></strong>
|
||||
</summary>
|
||||
|
||||
If you want to provide the method name as a string so that you can decide which method to call dynamically or to call
|
||||
a method that might not be available in your version of the client, use the `WebClient.apiCall(methodName, [options])`
|
||||
method. The API method call above can also be written as follows:
|
||||
|
||||
```javascript
|
||||
const conversationId = '...';
|
||||
(async () => {
|
||||
|
||||
// Using apiCall() allows the app to call any method and to do it programmatically
|
||||
const response = await web.apiCall('chat.postMessage', {
|
||||
text: 'Hello world!',
|
||||
channel: conversationId,
|
||||
});
|
||||
})();
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### Handle errors
|
||||
|
||||
Errors can happen for many reasons: maybe the token doesn't have the proper [scopes](https://api.slack.com/scopes) to
|
||||
call a method, maybe its been revoked by a user, or maybe you just used a bad argument. In these cases, the returned
|
||||
`Promise` will reject with an `Error`. You should catch the error and use the information it contains to decide how your
|
||||
app can proceed.
|
||||
|
||||
Each error contains a `code` property, which you can check against the `ErrorCode` export to understand the kind of
|
||||
error you're dealing with. For example, when Slack responds to your app with an error, that is an
|
||||
`ErrorCode.PlatformError`. These types of errors provide Slack's response body as the `data` property.
|
||||
|
||||
```javascript
|
||||
// Import ErrorCode from the package
|
||||
const { WebClient, ErrorCode } = require('@slack/web-api');
|
||||
|
||||
(async () => {
|
||||
|
||||
try {
|
||||
// This method call should fail because we're giving it a bogus user ID to lookup.
|
||||
const response = await web.users.info({ user: '...' });
|
||||
} catch (error) {
|
||||
// Check the code property, and when its a PlatformError, log the whole response.
|
||||
if (error.code === ErrorCode.PlatformError) {
|
||||
console.log(error.data);
|
||||
} else {
|
||||
// Some other error, oh no!
|
||||
console.log('Well, that was unexpected.');
|
||||
}
|
||||
}
|
||||
})();
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary markdown="span">
|
||||
<strong><i>More error types</i></strong>
|
||||
</summary>
|
||||
|
||||
There are a few more types of errors that you might encounter, each with one of these `code`s:
|
||||
|
||||
* `ErrorCode.RequestError`: A request could not be sent. A common reason for this is that your network connection is
|
||||
not available, or `api.slack.com` could not be reached. This error has an `original` property with more details.
|
||||
|
||||
* `ErrorCode.RateLimitedError`: The Web API cannot fulfill the API method call because your app has made too many
|
||||
requests too quickly. This error has a `retryAfter` property with the number of seconds you should wait before trying
|
||||
again. See [the documentation on rate limit handling](https://slack.dev/node-slack-sdk/web-api/#rate-limits) to
|
||||
understand how the client will automatically deal with these problems for you.
|
||||
|
||||
* `ErrorCode.HTTPError`: The HTTP response contained an unfamiliar status code. The Web API only responds with `200`
|
||||
(yes, even for errors) or `429` (rate limiting). If you receive this error, it's likely due to a problem with a proxy,
|
||||
a custom TLS configuration, or a custom API URL. This error has the `statusCode`, `statusMessage`, `headers`, and
|
||||
`body` properties containing more details.
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### Pagination
|
||||
|
||||
[Many of the Web API's methods](https://api.slack.com/docs/pagination#methods_supporting_cursor-based_pagination) return
|
||||
lists of objects, and are known to be **cursor-paginated**. The result of calling these methods will contain a part of
|
||||
the list, or a page, and also provide you with information on how to continue to the next page on a subsequent API call.
|
||||
Instead of calling many times manually, the `WebClient` can manage to get each page, allowing you to determine when to
|
||||
stop, and help you process the results.
|
||||
|
||||
The process of retrieving multiple pages from Slack's API can be described as **asynchronous iteration**, which means
|
||||
you're processing items in a collection, but getting each item is an asynchronous operation. Fortunately, JavaScript
|
||||
has this concept built-in, and in newer versions of the language there's a syntax to make it even simpler:
|
||||
[`for await...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of).
|
||||
|
||||
```javascript
|
||||
(async () => {
|
||||
let result;
|
||||
|
||||
// Async iteration is similar to a simple for loop.
|
||||
// Use only the first two parameters to get an async iterator.
|
||||
for await (const page of web.paginate('something.list', { name: 'value' })) {
|
||||
// You can inspect each page, find your result, and stop the loop with a `break` statement
|
||||
if (containsTheThing(page.something)) {
|
||||
result = page.something.thing;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
The `for await...of` syntax is available in Node v10.0.0 and above. If you're using an older version of Node, see
|
||||
functional iteration below.
|
||||
|
||||
<details>
|
||||
<summary markdown="span">
|
||||
<strong><i>Using functional iteration</i></strong>
|
||||
</summary>
|
||||
|
||||
The `.paginate()` method can accept up to two additional parameters. The third parameter, `stopFn`, is a function that
|
||||
is called once for each page of the result, and should return `true` when the app no longer needs to get another page.
|
||||
The fourth parameter is `reducerFn`, which is a function that gets called once for each page of the result, but can
|
||||
be used to aggregate a result. The value it returns is used to call it the next time as the `accumulator`. The first
|
||||
time it gets called, the `accumulator` is undefined.
|
||||
|
||||
```javascript
|
||||
(async () => {
|
||||
|
||||
// The first two parameters are the method name and the options object.
|
||||
const done = await web.paginate('something.list', { name: 'value' },
|
||||
// The third is a function that receives each page and should return true when the next page isn't needed.
|
||||
(page) => { /* ... */ },
|
||||
// The fourth is a reducer function, similar to the callback parameter of Array.prototype.reduce().
|
||||
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
|
||||
// The accumulator is initialized to undefined.
|
||||
(accumulator, page, index) => { /* ... */ },
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
The returned value is a `Promise`, but what it resolves to depends on whether or not you include the fourth (optional)
|
||||
parameter. If you don't include it, the resolved value is always `undefined`. In this case, its used for control flow
|
||||
purposes (resuming the rest of your program), and the function in the third parameter is used to capture a result. If
|
||||
you do include the fourth parameter, then the resolved value is the value of the `accumulator`. This is a familiar
|
||||
pattern for people that use _functional programming_.
|
||||
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### Logging
|
||||
|
||||
The `WebClient` will log interesting information to the console by default. You can use the `logLevel` to decide how
|
||||
much information, or how interesting the information needs to be, in order for it to be output. There are a few possible
|
||||
log levels, which you can find in the `LogLevel` export. By default, the value is set to `LogLevel.INFO`. While you're
|
||||
in development, its sometimes helpful to set this to the most verbose: `LogLevel.DEBUG`.
|
||||
|
||||
```javascript
|
||||
// Import LogLevel from the package
|
||||
const { WebClient, LogLevel } = require('@slack/web-api');
|
||||
|
||||
// Log level is one of the options you can set in the constructor
|
||||
const web = new WebClient(token, {
|
||||
logLevel: LogLevel.DEBUG,
|
||||
});
|
||||
```
|
||||
|
||||
All the log levels, in order of most to least information, are: `DEBUG`, `INFO`, `WARN`, and `ERROR`.
|
||||
|
||||
<details>
|
||||
<summary markdown="span">
|
||||
<strong><i>Sending log output somewhere besides the console</i></strong>
|
||||
</summary>
|
||||
|
||||
You can also choose to have logs sent to a custom logger using the `logger` option. A custom logger needs to implement
|
||||
specific methods (known as the `Logger` interface):
|
||||
|
||||
| Method | Parameters | Return type |
|
||||
|--------------|-------------------|-------------|
|
||||
| `setLevel()` | `level: LogLevel` | `void` |
|
||||
| `setName()` | `name: string` | `void` |
|
||||
| `debug()` | `...msgs: any[]` | `void` |
|
||||
| `info()` | `...msgs: any[]` | `void` |
|
||||
| `warn()` | `...msgs: any[]` | `void` |
|
||||
| `error()` | `...msgs: any[]` | `void` |
|
||||
|
||||
A very simple custom logger might ignore the name and level, and write all messages to a file.
|
||||
|
||||
```javascript
|
||||
const { createWriteStream } = require('fs');
|
||||
const logWritable = createWriteStream('/var/my_log_file'); // Not shown: close this stream
|
||||
|
||||
const web = new WebClient(token, {
|
||||
// Creating a logger as a literal object. It's more likely that you'd create a class.
|
||||
logger: {
|
||||
debug(...msgs): { logWritable.write('debug: ' + JSON.stringify(msgs)); },
|
||||
info(...msgs): { logWritable.write('info: ' + JSON.stringify(msgs)); },
|
||||
warn(...msgs): { logWritable.write('warn: ' + JSON.stringify(msgs)); },
|
||||
error(...msgs): { logWritable.write('error: ' + JSON.stringify(msgs)); },
|
||||
setLevel(): { },
|
||||
setName(): { },
|
||||
},
|
||||
});
|
||||
```
|
||||
</details>
|
||||
|
||||
---
|
||||
|
||||
### Automatic retries
|
||||
|
||||
In production systems, you want your app to be resilient to short hiccups and temporary outages. Solving for this
|
||||
problem usually involves building a queuing system that handles retrying failed tasks. The `WebClient` comes with this
|
||||
queuing system out of the box, and it's on by default! The client will retry a failed API method call up to 10 times,
|
||||
spaced out over about 30 minutes. If the request doesn't succeed within that time, then the returned `Promise` will reject.
|
||||
You can observe each of the retries in your logs by [setting the log level to DEBUG](#logging). Try running the
|
||||
following code with your network disconnected, and then re-connect after you see a couple of log messages:
|
||||
|
||||
```javascript
|
||||
const { WebClient, LogLevel } = require('@slack/web-api');
|
||||
|
||||
const web = new WebClient('bogus token');
|
||||
|
||||
(async () => {
|
||||
await web.auth.test();
|
||||
|
||||
console.log('Done!');
|
||||
})();
|
||||
```
|
||||
|
||||
Shortly after re-connecting your network, you should see the `Done!` message. Did you notice the program doesn't use a
|
||||
valid token? The client is doing something clever and helpful here. It knows the difference between an error such as not
|
||||
being able to reach `api.slack.com` and an error in the response from Slack about an invalid token. The former is
|
||||
something that can be resolved with a retry, so it was retried. The invalid token error means that the call isn't going
|
||||
to succeed until your app does something differently, so it stops attempting retries.
|
||||
|
||||
You might not think 10 reties in 30 minutes is a good policy for your app. No problem, you can set the `retryConfig` to
|
||||
one that works better for you. The `retryPolicies` export contains a few well known options, and you can always write
|
||||
your own.
|
||||
|
||||
```javascript
|
||||
const { WebClient, retryPolicies } = require('@slack/web-api');
|
||||
|
||||
const web = new WebClient(token, {
|
||||
retryConfig: retryPolicies.fiveRetriesInFiveMinutes,
|
||||
});
|
||||
```
|
||||
|
||||
Here are some other values that you might want to use for `retryConfig`:
|
||||
|
||||
| `retryConfig` | Description |
|
||||
|------------------------------------------------|---------------------------------|
|
||||
| `retryPolicies.tenRetriesInAboutThirtyMinutes` | (default) |
|
||||
| `retryPolicies.fiveRetriesInFiveMinutes` | Five attempts in five minutes |
|
||||
| `retryPolicies.rapidRetryPolicy` | Used to keep tests running fast |
|
||||
| `{ retries: 0 }` | No retries ([other options](https://github.com/tim-kos/node-retry#retryoperationoptions)) |
|
||||
|
||||
**Note**: If an API call results in a rate limit being exceeded, you might still notice the client automatically
|
||||
retrying the API call. If you'd like to opt out of that behavior, set the `rejectRateLimitedCalls` option to `true`.
|
||||
|
||||
---
|
||||
|
||||
### More
|
||||
|
||||
The [documentation website](https://slack.dev/node-slack-sdk/web-api) has information about these additional features of
|
||||
the `WebClient`:
|
||||
|
||||
* Upload a file with a `Buffer` or a `ReadableStream`.
|
||||
* Using a custom agent for proxying
|
||||
* Rate limit handling
|
||||
* Request concurrency
|
||||
* Custom TLS configuration
|
||||
* Custom API URL
|
||||
* Exchange an OAuth grant for a token
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
This package supports Node v8 LTS and higher. It's highly recommended to use [the latest LTS version of
|
||||
node](https://github.com/nodejs/Release#release-schedule), and the documentation is written using syntax and features
|
||||
from that version.
|
||||
|
||||
## Getting Help
|
||||
|
||||
If you get stuck, we're here to help. The following are the best ways to get assistance working through your issue:
|
||||
|
||||
* [Issue Tracker](http://github.com/slackapi/node-slack-sdk/issues) for questions, feature requests, bug reports and
|
||||
general discussion related to these packages. Try searching before you create a new issue.
|
||||
* [Email us](mailto:[email protected]) in Slack developer support: `[email protected]`
|
||||
* [Bot Developers Hangout](https://community.botkit.ai/): a Slack community for developers
|
||||
building all types of bots. You can find the maintainers and users of these packages in **#sdk-node-slack-sdk**.
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
/// <reference types="node" />
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
import { Agent } from 'http';
|
||||
import { SecureContextOptions } from 'tls';
|
||||
import { Methods } from './methods';
|
||||
import { LogLevel, Logger } from './logger';
|
||||
import { RetryOptions } from './retry-policies';
|
||||
/**
|
||||
* A client for Slack's Web API
|
||||
*
|
||||
* This client provides an alias for each {@link https://api.slack.com/methods|Web API method}. Each method is
|
||||
* a convenience wrapper for calling the {@link WebClient#apiCall} method using the method name as the first parameter.
|
||||
*/
|
||||
export declare class WebClient extends Methods {
|
||||
/**
|
||||
* The base URL for reaching Slack's Web API. Consider changing this value for testing purposes.
|
||||
*/
|
||||
readonly slackApiUrl: string;
|
||||
/**
|
||||
* Authentication and authorization token for accessing Slack Web API (usually begins with `xoxp` or `xoxb`)
|
||||
*/
|
||||
readonly token?: string;
|
||||
/**
|
||||
* Configuration for retry operations. See {@link https://github.com/tim-kos/node-retry|node-retry} for more details.
|
||||
*/
|
||||
private retryConfig;
|
||||
/**
|
||||
* Queue of requests in which a maximum of {@link WebClientOptions.maxRequestConcurrency} can concurrently be
|
||||
* in-flight.
|
||||
*/
|
||||
private requestQueue;
|
||||
/**
|
||||
* Axios HTTP client instance used by this client
|
||||
*/
|
||||
private axios;
|
||||
/**
|
||||
* Configuration for custom TLS handling
|
||||
*/
|
||||
private tlsConfig;
|
||||
/**
|
||||
* Preference for immediately rejecting API calls which result in a rate-limited response
|
||||
*/
|
||||
private rejectRateLimitedCalls;
|
||||
/**
|
||||
* The name used to prefix all logging generated from this object
|
||||
*/
|
||||
private static loggerName;
|
||||
/**
|
||||
* This object's logger instance
|
||||
*/
|
||||
private logger;
|
||||
/**
|
||||
* @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`)
|
||||
*/
|
||||
constructor(token?: string, { slackApiUrl, logger, logLevel, maxRequestConcurrency, retryConfig, agent, tls, rejectRateLimitedCalls, headers, }?: WebClientOptions);
|
||||
/**
|
||||
* Generic method for calling a Web API method
|
||||
*
|
||||
* @param method - the Web API method to call {@link https://api.slack.com/methods}
|
||||
* @param options - options
|
||||
*/
|
||||
apiCall(method: string, options?: WebAPICallOptions): Promise<WebAPICallResult>;
|
||||
/**
|
||||
* Iterate over the result pages of a cursor-paginated Web API method. This method can return two types of values,
|
||||
* depending on which arguments are used. When up to two parameters are used, the return value is an async iterator
|
||||
* which can be used as the iterable in a for-await-of loop. When three or four parameters are used, the return
|
||||
* value is a promise that resolves at the end of iteration. The third parameter, `shouldStop`, is a function that is
|
||||
* called with each `page` and can end iteration by returning `true`. The fourth parameter, `reduce`, is a function
|
||||
* that is called with three arguments: `accumulator`, `page`, and `index`. The `accumulator` is a value of any type
|
||||
* you choose, but it will contain `undefined` when `reduce` is called for the first time. The `page` argument and
|
||||
* `index` arguments are exactly what they say they are. The `reduce` function's return value will be passed in as
|
||||
* `accumulator` the next time its called, and the returned promise will resolve to the last value of `accumulator`.
|
||||
*
|
||||
* The for-await-of syntax is part of ES2018. It is available natively in Node starting with v10.0.0. You may be able
|
||||
* to use it in earlier JavaScript runtimes by transpiling your source with a tool like Babel. However, the
|
||||
* transpiled code will likely sacrifice performance.
|
||||
*
|
||||
* @param method - the cursor-paginated Web API method to call {@link https://api.slack.com/docs/pagination}
|
||||
* @param options - options
|
||||
* @param shouldStop - a predicate that is called with each page, and should return true when pagination can end.
|
||||
* @param reduce - a callback that can be used to accumulate a value that the return promise is resolved to
|
||||
*/
|
||||
paginate(method: string, options?: WebAPICallOptions): AsyncIterable<WebAPICallResult>;
|
||||
paginate(method: string, options: WebAPICallOptions, shouldStop: PaginatePredicate): Promise<void>;
|
||||
paginate<R extends PageReducer, A extends PageAccumulator<R>>(method: string, options: WebAPICallOptions, shouldStop: PaginatePredicate, reduce?: PageReducer<A>): Promise<A>;
|
||||
/**
|
||||
* Low-level function to make a single API request. handles queuing, retries, and http-level errors
|
||||
*/
|
||||
private makeRequest;
|
||||
/**
|
||||
* Transforms options (a simple key-value object) into an acceptable value for a body. This can be either
|
||||
* a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used
|
||||
* when the options contain a binary (a stream or a buffer) and the upload should be done with content-type
|
||||
* multipart/form-data.
|
||||
*
|
||||
* @param options - arguments for the Web API method
|
||||
* @param headers - a mutable object representing the HTTP headers for the outgoing request
|
||||
*/
|
||||
private serializeApiCallOptions;
|
||||
/**
|
||||
* Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevent
|
||||
* HTTP headers into the object.
|
||||
* @param response - an http response
|
||||
*/
|
||||
private buildResult;
|
||||
}
|
||||
export default WebClient;
|
||||
export interface WebClientOptions {
|
||||
slackApiUrl?: string;
|
||||
logger?: Logger;
|
||||
logLevel?: LogLevel;
|
||||
maxRequestConcurrency?: number;
|
||||
retryConfig?: RetryOptions;
|
||||
agent?: Agent;
|
||||
tls?: TLSOptions;
|
||||
rejectRateLimitedCalls?: boolean;
|
||||
headers?: object;
|
||||
}
|
||||
export declare type TLSOptions = Pick<SecureContextOptions, 'pfx' | 'key' | 'passphrase' | 'cert' | 'ca'>;
|
||||
export declare enum WebClientEvent {
|
||||
RATE_LIMITED = "rate_limited"
|
||||
}
|
||||
export interface WebAPICallOptions {
|
||||
[argument: string]: unknown;
|
||||
}
|
||||
export interface WebAPICallResult {
|
||||
ok: boolean;
|
||||
error?: string;
|
||||
response_metadata?: {
|
||||
warnings?: string[];
|
||||
next_cursor?: string;
|
||||
scopes?: string[];
|
||||
acceptedScopes?: string[];
|
||||
retryAfter?: number;
|
||||
messages?: string[];
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
export interface PaginatePredicate {
|
||||
(page: WebAPICallResult): boolean | undefined | void;
|
||||
}
|
||||
export interface PageReducer<A = any> {
|
||||
(accumulator: A | undefined, page: WebAPICallResult, index: number): A;
|
||||
}
|
||||
export declare type PageAccumulator<R extends PageReducer> = R extends (accumulator: (infer A) | undefined, page: WebAPICallResult, index: number) => infer A ? A : never;
|
||||
//# sourceMappingURL=WebClient.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"WebClient.d.ts","sourceRoot":"","sources":["../src/WebClient.ts"],"names":[],"mappings":";;AAOA,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAG7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,KAAK,CAAC;AAQ3C,OAAO,EAAE,OAAO,EAA2D,MAAM,WAAW,CAAC;AAK7F,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAa,MAAM,UAAU,CAAC;AACvD,OAAsB,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAG/D;;;;;GAKG;AACH,qBAAa,SAAU,SAAQ,OAAO;IACpC;;OAEG;IACH,SAAgB,WAAW,EAAE,MAAM,CAAC;IAEpC;;OAEG;IACH,SAAgB,KAAK,CAAC,EAAE,MAAM,CAAC;IAE/B;;OAEG;IACH,OAAO,CAAC,WAAW,CAAe;IAElC;;;OAGG;IACH,OAAO,CAAC,YAAY,CAAS;IAE7B;;OAEG;IACH,OAAO,CAAC,KAAK,CAAgB;IAE7B;;OAEG;IACH,OAAO,CAAC,SAAS,CAAa;IAE9B;;OAEG;IACH,OAAO,CAAC,sBAAsB,CAAU;IAExC;;OAEG;IACH,OAAO,CAAC,MAAM,CAAC,UAAU,CAAe;IAExC;;OAEG;IACH,OAAO,CAAC,MAAM,CAAS;IAEvB;;OAEG;gBACS,KAAK,CAAC,EAAE,MAAM,EAAE,EAC1B,WAAsC,EACtC,MAAkB,EAClB,QAAwB,EACxB,qBAAyB,EACzB,WAA0D,EAC1D,KAAiB,EACjB,GAAe,EACf,sBAA8B,EAC9B,OAAY,GACb,GAAE,gBAAqB;IA+CxB;;;;;OAKG;IACU,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC;IA+C5F;;;;;;;;;;;;;;;;;;;OAmBG;IACI,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,aAAa,CAAC,gBAAgB,CAAC;IACtF,QAAQ,CACb,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,iBAAiB,EAC1B,UAAU,EAAE,iBAAiB,GAC5B,OAAO,CAAC,IAAI,CAAC;IACT,QAAQ,CAAC,CAAC,SAAS,WAAW,EAAE,CAAC,SAAS,eAAe,CAAC,CAAC,CAAC,EACjE,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,iBAAiB,EAC1B,UAAU,EAAE,iBAAiB,EAC7B,MAAM,CAAC,EAAE,WAAW,CAAC,CAAC,CAAC,GACtB,OAAO,CAAC,CAAC,CAAC;IA6Eb;;OAEG;YACW,WAAW;IAyDzB;;;;;;;;OAQG;IACH,OAAO,CAAC,uBAAuB;IA2E/B;;;;OAIG;IACH,OAAO,CAAC,WAAW;CAwBpB;AAED,eAAe,SAAS,CAAC;AAMzB,MAAM,WAAW,gBAAgB;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,WAAW,CAAC,EAAE,YAAY,CAAC;IAC3B,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,oBAAY,UAAU,GAAG,IAAI,CAAC,oBAAoB,EAAE,KAAK,GAAG,KAAK,GAAG,YAAY,GAAG,MAAM,GAAG,IAAI,CAAC,CAAC;AAElG,oBAAY,cAAc;IACxB,YAAY,iBAAiB;CAC9B;AAED,MAAM,WAAW,iBAAiB;IAChC,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC;CAC7B;AAED,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iBAAiB,CAAC,EAAE;QAClB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;QACpB,WAAW,CAAC,EAAE,MAAM,CAAC;QAGrB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAClB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;QAC1B,UAAU,CAAC,EAAE,MAAM,CAAC;QAEpB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;KACrB,CAAC;IACF,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAGD,MAAM,WAAW,iBAAiB;IAChC,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,GAAG,SAAS,GAAG,IAAI,CAAC;CACtD;AAED,MAAM,WAAW,WAAW,CAAC,CAAC,GAAG,GAAG;IAClC,CAAC,WAAW,EAAE,CAAC,GAAG,SAAS,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC;CACxE;AAED,oBAAY,eAAe,CAAC,CAAC,SAAS,WAAW,IAC/C,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,MAAM,CAAC,CAAC,GAAG,SAAS,EAAE,IAAI,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC"}
|
||||
+452
@@ -0,0 +1,452 @@
|
||||
"use strict";
|
||||
/// <reference lib="esnext.asynciterable" />
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
|
||||
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
|
||||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
||||
var g = generator.apply(thisArg, _arguments || []), i, q = [];
|
||||
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
|
||||
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
|
||||
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
|
||||
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
|
||||
function fulfill(value) { resume("next", value); }
|
||||
function reject(value) { resume("throw", value); }
|
||||
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
|
||||
};
|
||||
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
||||
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
||||
var m = o[Symbol.asyncIterator], i;
|
||||
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
||||
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
||||
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WebClientEvent = exports.WebClient = void 0;
|
||||
// polyfill for async iterable. see: https://stackoverflow.com/a/43694282/305340
|
||||
// can be removed once node v10 is the minimum target (node v8 and v9 require --harmony_async_iteration flag)
|
||||
if (Symbol['asyncIterator'] === undefined) {
|
||||
(Symbol['asyncIterator']) = Symbol.for('asyncIterator');
|
||||
}
|
||||
const querystring_1 = require("querystring");
|
||||
const path_1 = require("path");
|
||||
const is_stream_1 = __importDefault(require("is-stream"));
|
||||
const p_queue_1 = __importDefault(require("p-queue")); // tslint:disable-line:import-name
|
||||
const p_retry_1 = __importStar(require("p-retry"));
|
||||
const axios_1 = __importDefault(require("axios"));
|
||||
const form_data_1 = __importDefault(require("form-data")); // tslint:disable-line:import-name
|
||||
const methods_1 = require("./methods");
|
||||
const instrument_1 = require("./instrument");
|
||||
const errors_1 = require("./errors");
|
||||
const logger_1 = require("./logger");
|
||||
const retry_policies_1 = __importDefault(require("./retry-policies"));
|
||||
const helpers_1 = require("./helpers");
|
||||
/**
|
||||
* A client for Slack's Web API
|
||||
*
|
||||
* This client provides an alias for each {@link https://api.slack.com/methods|Web API method}. Each method is
|
||||
* a convenience wrapper for calling the {@link WebClient#apiCall} method using the method name as the first parameter.
|
||||
*/
|
||||
class WebClient extends methods_1.Methods {
|
||||
/**
|
||||
* @param token - An API token to authenticate/authorize with Slack (usually start with `xoxp`, `xoxb`)
|
||||
*/
|
||||
constructor(token, { slackApiUrl = 'https://slack.com/api/', logger = undefined, logLevel = logger_1.LogLevel.INFO, maxRequestConcurrency = 3, retryConfig = retry_policies_1.default.tenRetriesInAboutThirtyMinutes, agent = undefined, tls = undefined, rejectRateLimitedCalls = false, headers = {}, } = {}) {
|
||||
super();
|
||||
this.token = token;
|
||||
this.slackApiUrl = slackApiUrl;
|
||||
this.retryConfig = retryConfig;
|
||||
this.requestQueue = new p_queue_1.default({ concurrency: maxRequestConcurrency });
|
||||
// NOTE: may want to filter the keys to only those acceptable for TLS options
|
||||
this.tlsConfig = tls !== undefined ? tls : {};
|
||||
this.rejectRateLimitedCalls = rejectRateLimitedCalls;
|
||||
// Logging
|
||||
if (typeof logger !== 'undefined') {
|
||||
this.logger = logger;
|
||||
if (typeof logLevel !== 'undefined') {
|
||||
this.logger.debug('The logLevel given to WebClient was ignored as you also gave logger');
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.logger = logger_1.getLogger(WebClient.loggerName, logLevel, logger);
|
||||
}
|
||||
this.axios = axios_1.default.create({
|
||||
baseURL: slackApiUrl,
|
||||
headers: Object.assign({
|
||||
'User-Agent': instrument_1.getUserAgent(),
|
||||
}, headers),
|
||||
httpAgent: agent,
|
||||
httpsAgent: agent,
|
||||
transformRequest: [this.serializeApiCallOptions.bind(this)],
|
||||
validateStatus: () => true,
|
||||
maxRedirects: 0,
|
||||
// disabling axios' automatic proxy support:
|
||||
// axios would read from envvars to configure a proxy automatically, but it doesn't support TLS destinations.
|
||||
// for compatibility with https://api.slack.com, and for a larger set of possible proxies (SOCKS or other
|
||||
// protocols), users of this package should use the `agent` option to configure a proxy.
|
||||
proxy: false,
|
||||
});
|
||||
// serializeApiCallOptions will always determine the appropriate content-type
|
||||
delete this.axios.defaults.headers.post['Content-Type'];
|
||||
this.logger.debug('initialized');
|
||||
}
|
||||
/**
|
||||
* Generic method for calling a Web API method
|
||||
*
|
||||
* @param method - the Web API method to call {@link https://api.slack.com/methods}
|
||||
* @param options - options
|
||||
*/
|
||||
async apiCall(method, options) {
|
||||
this.logger.debug(`apiCall('${method}') start`);
|
||||
warnDeprecations(method, this.logger);
|
||||
if (typeof options === 'string' || typeof options === 'number' || typeof options === 'boolean') {
|
||||
throw new TypeError(`Expected an options argument but instead received a ${typeof options}`);
|
||||
}
|
||||
const response = await this.makeRequest(method, Object.assign({ token: this.token }, options));
|
||||
const result = this.buildResult(response);
|
||||
// log warnings in response metadata
|
||||
if (result.response_metadata !== undefined && result.response_metadata.warnings !== undefined) {
|
||||
result.response_metadata.warnings.forEach(this.logger.warn.bind(this.logger));
|
||||
}
|
||||
// log warnings and errors in response metadata messages
|
||||
// related to https://api.slack.com/changelog/2016-09-28-response-metadata-is-on-the-way
|
||||
if (result.response_metadata !== undefined && result.response_metadata.messages !== undefined) {
|
||||
result.response_metadata.messages.forEach((msg) => {
|
||||
const errReg = /\[ERROR\](.*)/;
|
||||
const warnReg = /\[WARN\](.*)/;
|
||||
if (errReg.test(msg)) {
|
||||
const errMatch = msg.match(errReg);
|
||||
if (errMatch != null) {
|
||||
this.logger.error(errMatch[1].trim());
|
||||
}
|
||||
}
|
||||
else if (warnReg.test(msg)) {
|
||||
const warnMatch = msg.match(warnReg);
|
||||
if (warnMatch != null) {
|
||||
this.logger.warn(warnMatch[1].trim());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (!result.ok) {
|
||||
throw errors_1.platformErrorFromResult(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
paginate(method, options, shouldStop, reduce) {
|
||||
if (!methods_1.cursorPaginationEnabledMethods.has(method)) {
|
||||
this.logger.warn(`paginate() called with method ${method}, which is not known to be cursor pagination enabled.`);
|
||||
}
|
||||
const pageSize = (() => {
|
||||
if (options !== undefined && typeof options.limit === 'number') {
|
||||
const limit = options.limit;
|
||||
delete options.limit;
|
||||
return limit;
|
||||
}
|
||||
return defaultPageSize;
|
||||
})();
|
||||
function generatePages() {
|
||||
return __asyncGenerator(this, arguments, function* generatePages_1() {
|
||||
// when result is undefined, that signals that the first of potentially many calls has not yet been made
|
||||
let result = undefined;
|
||||
// paginationOptions stores pagination options not already stored in the options argument
|
||||
let paginationOptions = {
|
||||
limit: pageSize,
|
||||
};
|
||||
if (options !== undefined && options.cursor !== undefined) {
|
||||
paginationOptions.cursor = options.cursor;
|
||||
}
|
||||
// NOTE: test for the situation where you're resuming a pagination using and existing cursor
|
||||
while (result === undefined || paginationOptions !== undefined) {
|
||||
result = yield __await(this.apiCall(method, Object.assign(options !== undefined ? options : {}, paginationOptions)));
|
||||
yield yield __await(result);
|
||||
paginationOptions = paginationOptionsForNextPage(result, pageSize);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (shouldStop === undefined) {
|
||||
return generatePages.call(this);
|
||||
}
|
||||
const pageReducer = (reduce !== undefined) ? reduce : noopPageReducer;
|
||||
let index = 0;
|
||||
return (async () => {
|
||||
// Unroll the first iteration of the iterator
|
||||
// This is done primarily because in order to satisfy the type system, we need a variable that is typed as A
|
||||
// (shown as accumulator before), but before the first iteration all we have is a variable typed A | undefined.
|
||||
// Unrolling the first iteration allows us to deal with undefined as a special case.
|
||||
var e_1, _a;
|
||||
const pageIterator = generatePages.call(this);
|
||||
const firstIteratorResult = await pageIterator.next(undefined);
|
||||
// Assumption: there will always be at least one result in a paginated API request
|
||||
// if (firstIteratorResult.done) { return; }
|
||||
const firstPage = firstIteratorResult.value;
|
||||
let accumulator = pageReducer(undefined, firstPage, index);
|
||||
index += 1;
|
||||
if (shouldStop(firstPage)) {
|
||||
return accumulator;
|
||||
}
|
||||
try {
|
||||
// Continue iteration
|
||||
for (var pageIterator_1 = __asyncValues(pageIterator), pageIterator_1_1; pageIterator_1_1 = await pageIterator_1.next(), !pageIterator_1_1.done;) {
|
||||
const page = pageIterator_1_1.value;
|
||||
accumulator = pageReducer(accumulator, page, index);
|
||||
if (shouldStop(page)) {
|
||||
return accumulator;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
}
|
||||
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
||||
finally {
|
||||
try {
|
||||
if (pageIterator_1_1 && !pageIterator_1_1.done && (_a = pageIterator_1.return)) await _a.call(pageIterator_1);
|
||||
}
|
||||
finally { if (e_1) throw e_1.error; }
|
||||
}
|
||||
return accumulator;
|
||||
})();
|
||||
}
|
||||
/**
|
||||
* Low-level function to make a single API request. handles queuing, retries, and http-level errors
|
||||
*/
|
||||
async makeRequest(url, body, headers = {}) {
|
||||
// TODO: better input types - remove any
|
||||
const task = () => this.requestQueue.add(async () => {
|
||||
this.logger.debug('will perform http request');
|
||||
try {
|
||||
const response = await this.axios.post(url, body, Object.assign({
|
||||
headers,
|
||||
}, this.tlsConfig));
|
||||
this.logger.debug('http response received');
|
||||
if (response.status === 429) {
|
||||
const retrySec = parseRetryHeaders(response);
|
||||
if (retrySec !== undefined) {
|
||||
this.emit(WebClientEvent.RATE_LIMITED, retrySec);
|
||||
if (this.rejectRateLimitedCalls) {
|
||||
throw new p_retry_1.AbortError(errors_1.rateLimitedErrorWithDelay(retrySec));
|
||||
}
|
||||
this.logger.info(`API Call failed due to rate limiting. Will retry in ${retrySec} seconds.`);
|
||||
// pause the request queue and then delay the rejection by the amount of time in the retry header
|
||||
this.requestQueue.pause();
|
||||
// NOTE: if there was a way to introspect the current RetryOperation and know what the next timeout
|
||||
// would be, then we could subtract that time from the following delay, knowing that it the next
|
||||
// attempt still wouldn't occur until after the rate-limit header has specified. an even better
|
||||
// solution would be to subtract the time from only the timeout of this next attempt of the
|
||||
// RetryOperation. this would result in the staying paused for the entire duration specified in the
|
||||
// header, yet this operation not having to pay the timeout cost in addition to that.
|
||||
await helpers_1.delay(retrySec * 1000);
|
||||
// resume the request queue and throw a non-abort error to signal a retry
|
||||
this.requestQueue.start();
|
||||
throw Error('A rate limit was exceeded.');
|
||||
}
|
||||
else {
|
||||
// TODO: turn this into some CodedError
|
||||
throw new p_retry_1.AbortError(new Error('Retry header did not contain a valid timeout.'));
|
||||
}
|
||||
}
|
||||
// Slack's Web API doesn't use meaningful status codes besides 429 and 200
|
||||
if (response.status !== 200) {
|
||||
throw errors_1.httpErrorFromResponse(response);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
catch (error) {
|
||||
this.logger.warn('http request failed', error.message);
|
||||
if (error.request) {
|
||||
throw errors_1.requestErrorWithOriginal(error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
return p_retry_1.default(task, this.retryConfig);
|
||||
}
|
||||
/**
|
||||
* Transforms options (a simple key-value object) into an acceptable value for a body. This can be either
|
||||
* a string, used when posting with a content-type of url-encoded. Or, it can be a readable stream, used
|
||||
* when the options contain a binary (a stream or a buffer) and the upload should be done with content-type
|
||||
* multipart/form-data.
|
||||
*
|
||||
* @param options - arguments for the Web API method
|
||||
* @param headers - a mutable object representing the HTTP headers for the outgoing request
|
||||
*/
|
||||
serializeApiCallOptions(options, headers) {
|
||||
// The following operation both flattens complex objects into a JSON-encoded strings and searches the values for
|
||||
// binary content
|
||||
let containsBinaryData = false;
|
||||
const flattened = Object.entries(options)
|
||||
.map(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return [];
|
||||
}
|
||||
let serializedValue = value;
|
||||
if (Buffer.isBuffer(value) || is_stream_1.default(value)) {
|
||||
containsBinaryData = true;
|
||||
}
|
||||
else if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
|
||||
// if value is anything other than string, number, boolean, binary data, a Stream, or a Buffer, then encode it
|
||||
// as a JSON string.
|
||||
serializedValue = JSON.stringify(value);
|
||||
}
|
||||
return [key, serializedValue];
|
||||
});
|
||||
// A body with binary content should be serialized as multipart/form-data
|
||||
if (containsBinaryData) {
|
||||
this.logger.debug('request arguments contain binary data');
|
||||
const form = flattened.reduce((form, [key, value]) => {
|
||||
if (Buffer.isBuffer(value) || is_stream_1.default(value)) {
|
||||
const options = {};
|
||||
options.filename = (() => {
|
||||
// attempt to find filename from `value`. adapted from:
|
||||
// tslint:disable-next-line:max-line-length
|
||||
// https://github.com/form-data/form-data/blob/028c21e0f93c5fefa46a7bbf1ba753e4f627ab7a/lib/form_data.js#L227-L230
|
||||
// formidable and the browser add a name property
|
||||
// fs- and request- streams have path property
|
||||
const streamOrBuffer = value;
|
||||
if (typeof streamOrBuffer.name === 'string') {
|
||||
return path_1.basename(streamOrBuffer.name);
|
||||
}
|
||||
if (typeof streamOrBuffer.path === 'string') {
|
||||
return path_1.basename(streamOrBuffer.path);
|
||||
}
|
||||
return defaultFilename;
|
||||
})();
|
||||
form.append(key, value, options);
|
||||
}
|
||||
else if (key !== undefined && value !== undefined) {
|
||||
form.append(key, value);
|
||||
}
|
||||
return form;
|
||||
}, new form_data_1.default());
|
||||
// Copying FormData-generated headers into headers param
|
||||
// not reassigning to headers param since it is passed by reference and behaves as an inout param
|
||||
for (const [header, value] of Object.entries(form.getHeaders())) {
|
||||
headers[header] = value;
|
||||
}
|
||||
return form;
|
||||
}
|
||||
// Otherwise, a simple key-value object is returned
|
||||
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
const initialValue = {};
|
||||
return querystring_1.stringify(flattened.reduce((accumulator, [key, value]) => {
|
||||
if (key !== undefined && value !== undefined) {
|
||||
accumulator[key] = value;
|
||||
}
|
||||
return accumulator;
|
||||
}, initialValue));
|
||||
}
|
||||
/**
|
||||
* Processes an HTTP response into a WebAPICallResult by performing JSON parsing on the body and merging relevent
|
||||
* HTTP headers into the object.
|
||||
* @param response - an http response
|
||||
*/
|
||||
buildResult(response) {
|
||||
const data = response.data;
|
||||
if (data.response_metadata === undefined) {
|
||||
data.response_metadata = {};
|
||||
}
|
||||
// add scopes metadata from headers
|
||||
if (response.headers['x-oauth-scopes'] !== undefined) {
|
||||
data.response_metadata.scopes = response.headers['x-oauth-scopes'].trim().split(/\s*,\s*/);
|
||||
}
|
||||
if (response.headers['x-accepted-oauth-scopes'] !== undefined) {
|
||||
data.response_metadata.acceptedScopes =
|
||||
response.headers['x-accepted-oauth-scopes'].trim().split(/\s*,\s*/);
|
||||
}
|
||||
// add retry metadata from headers
|
||||
const retrySec = parseRetryHeaders(response);
|
||||
if (retrySec !== undefined) {
|
||||
data.response_metadata.retryAfter = retrySec;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
}
|
||||
exports.WebClient = WebClient;
|
||||
/**
|
||||
* The name used to prefix all logging generated from this object
|
||||
*/
|
||||
WebClient.loggerName = 'WebClient';
|
||||
exports.default = WebClient;
|
||||
var WebClientEvent;
|
||||
(function (WebClientEvent) {
|
||||
WebClientEvent["RATE_LIMITED"] = "rate_limited";
|
||||
})(WebClientEvent = exports.WebClientEvent || (exports.WebClientEvent = {}));
|
||||
/*
|
||||
* Helpers
|
||||
*/
|
||||
const defaultFilename = 'Untitled';
|
||||
const defaultPageSize = 200;
|
||||
const noopPageReducer = () => undefined;
|
||||
/**
|
||||
* Determines an appropriate set of cursor pagination options for the next request to a paginated API method.
|
||||
* @param previousResult - the result of the last request, where the next cursor might be found.
|
||||
* @param pageSize - the maximum number of additional items to fetch in the next request.
|
||||
*/
|
||||
function paginationOptionsForNextPage(previousResult, pageSize) {
|
||||
if (previousResult !== undefined &&
|
||||
previousResult.response_metadata !== undefined &&
|
||||
previousResult.response_metadata.next_cursor !== undefined &&
|
||||
previousResult.response_metadata.next_cursor !== '') {
|
||||
return {
|
||||
limit: pageSize,
|
||||
cursor: previousResult.response_metadata.next_cursor,
|
||||
};
|
||||
}
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Extract the amount of time (in seconds) the platform has recommended this client wait before sending another request
|
||||
* from a rate-limited HTTP response (statusCode = 429).
|
||||
*/
|
||||
function parseRetryHeaders(response) {
|
||||
if (response.headers['retry-after'] !== undefined) {
|
||||
const retryAfter = parseInt(response.headers['retry-after'], 10);
|
||||
if (!Number.isNaN(retryAfter)) {
|
||||
return retryAfter;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
/**
|
||||
* Log a warning when using a deprecated method
|
||||
* @param method api method being called
|
||||
* @param logger instance of web clients logger
|
||||
*/
|
||||
function warnDeprecations(method, logger) {
|
||||
const deprecatedConversationsMethods = ['channels.', 'groups.', 'im.', 'mpim.'];
|
||||
const deprecatedMethods = ['admin.conversations.whitelist.'];
|
||||
const isDeprecatedConversations = deprecatedConversationsMethods.some((depMethod) => {
|
||||
const re = new RegExp(`^${depMethod}`);
|
||||
return re.test(method);
|
||||
});
|
||||
const isDeprecated = deprecatedMethods.some((depMethod) => {
|
||||
const re = new RegExp(`^${depMethod}`);
|
||||
return re.test(method);
|
||||
});
|
||||
if (isDeprecatedConversations) {
|
||||
logger.warn(`${method} is deprecated. Please use the Conversations API instead. For more info, go to https://api.slack.com/changelog/2020-01-deprecating-antecedents-to-the-conversations-api`);
|
||||
}
|
||||
else if (isDeprecated) {
|
||||
logger.warn(`${method} is deprecated. Please check on https://api.slack.com/methods for an alternative.`);
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=WebClient.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+64
@@ -0,0 +1,64 @@
|
||||
/// <reference types="node" />
|
||||
import { IncomingHttpHeaders } from 'http';
|
||||
import { AxiosResponse } from 'axios';
|
||||
import { WebAPICallResult } from './WebClient';
|
||||
/**
|
||||
* All errors produced by this package adhere to this interface
|
||||
*/
|
||||
export interface CodedError extends NodeJS.ErrnoException {
|
||||
code: ErrorCode;
|
||||
}
|
||||
/**
|
||||
* A dictionary of codes for errors produced by this package
|
||||
*/
|
||||
export declare enum ErrorCode {
|
||||
RequestError = "slack_webapi_request_error",
|
||||
HTTPError = "slack_webapi_http_error",
|
||||
PlatformError = "slack_webapi_platform_error",
|
||||
RateLimitedError = "slack_webapi_rate_limited_error"
|
||||
}
|
||||
export declare type WebAPICallError = WebAPIPlatformError | WebAPIRequestError | WebAPIHTTPError | WebAPIRateLimitedError;
|
||||
export interface WebAPIPlatformError extends CodedError {
|
||||
code: ErrorCode.PlatformError;
|
||||
data: WebAPICallResult & {
|
||||
error: string;
|
||||
};
|
||||
}
|
||||
export interface WebAPIRequestError extends CodedError {
|
||||
code: ErrorCode.RequestError;
|
||||
original: Error;
|
||||
}
|
||||
export interface WebAPIHTTPError extends CodedError {
|
||||
code: ErrorCode.HTTPError;
|
||||
statusCode: number;
|
||||
statusMessage: string;
|
||||
headers: IncomingHttpHeaders;
|
||||
body?: any;
|
||||
}
|
||||
export interface WebAPIRateLimitedError extends CodedError {
|
||||
code: ErrorCode.RateLimitedError;
|
||||
retryAfter: number;
|
||||
}
|
||||
/**
|
||||
* A factory to create WebAPIRequestError objects
|
||||
* @param original - original error
|
||||
*/
|
||||
export declare function requestErrorWithOriginal(original: Error): WebAPIRequestError;
|
||||
/**
|
||||
* A factory to create WebAPIHTTPError objects
|
||||
* @param response - original error
|
||||
*/
|
||||
export declare function httpErrorFromResponse(response: AxiosResponse): WebAPIHTTPError;
|
||||
/**
|
||||
* A factory to create WebAPIPlatformError objects
|
||||
* @param result - Web API call result
|
||||
*/
|
||||
export declare function platformErrorFromResult(result: WebAPICallResult & {
|
||||
error: string;
|
||||
}): WebAPIPlatformError;
|
||||
/**
|
||||
* A factory to create WebAPIRateLimitedError objects
|
||||
* @param retrySec - Number of seconds that the request can be retried in
|
||||
*/
|
||||
export declare function rateLimitedErrorWithDelay(retrySec: number): WebAPIRateLimitedError;
|
||||
//# sourceMappingURL=errors.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AACtC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAE/C;;GAEG;AACH,MAAM,WAAW,UAAW,SAAQ,MAAM,CAAC,cAAc;IACvD,IAAI,EAAE,SAAS,CAAC;CACjB;AAED;;GAEG;AACH,oBAAY,SAAS;IACnB,YAAY,+BAA+B;IAC3C,SAAS,4BAA4B;IACrC,aAAa,gCAAgC;IAC7C,gBAAgB,oCAAoC;CACrD;AAED,oBAAY,eAAe,GAAG,mBAAmB,GAAG,kBAAkB,GAAG,eAAe,GAAG,sBAAsB,CAAC;AAElH,MAAM,WAAW,mBAAoB,SAAQ,UAAU;IACrD,IAAI,EAAE,SAAS,CAAC,aAAa,CAAC;IAC9B,IAAI,EAAE,gBAAgB,GAAG;QACvB,KAAK,EAAE,MAAM,CAAC;KACf,CAAC;CACH;AAED,MAAM,WAAW,kBAAmB,SAAQ,UAAU;IACpD,IAAI,EAAE,SAAS,CAAC,YAAY,CAAC;IAC7B,QAAQ,EAAE,KAAK,CAAC;CACjB;AAED,MAAM,WAAW,eAAgB,SAAQ,UAAU;IACjD,IAAI,EAAE,SAAS,CAAC,SAAS,CAAC;IAC1B,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,mBAAmB,CAAC;IAC7B,IAAI,CAAC,EAAE,GAAG,CAAC;CACZ;AAED,MAAM,WAAW,sBAAuB,SAAQ,UAAU;IACxD,IAAI,EAAE,SAAS,CAAC,gBAAgB,CAAC;IACjC,UAAU,EAAE,MAAM,CAAC;CACpB;AAYD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,KAAK,GAAG,kBAAkB,CAO5E;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,aAAa,GAAG,eAAe,CAU9E;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,gBAAgB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;CAAE,GAAG,mBAAmB,CAO1G;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,sBAAsB,CAOlF"}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.rateLimitedErrorWithDelay = exports.platformErrorFromResult = exports.httpErrorFromResponse = exports.requestErrorWithOriginal = exports.ErrorCode = void 0;
|
||||
/**
|
||||
* A dictionary of codes for errors produced by this package
|
||||
*/
|
||||
var ErrorCode;
|
||||
(function (ErrorCode) {
|
||||
ErrorCode["RequestError"] = "slack_webapi_request_error";
|
||||
ErrorCode["HTTPError"] = "slack_webapi_http_error";
|
||||
ErrorCode["PlatformError"] = "slack_webapi_platform_error";
|
||||
ErrorCode["RateLimitedError"] = "slack_webapi_rate_limited_error";
|
||||
})(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {}));
|
||||
/**
|
||||
* Factory for producing a {@link CodedError} from a generic error
|
||||
*/
|
||||
function errorWithCode(error, code) {
|
||||
// NOTE: might be able to return something more specific than a CodedError with conditional typing
|
||||
const codedError = error;
|
||||
codedError.code = code;
|
||||
return codedError;
|
||||
}
|
||||
/**
|
||||
* A factory to create WebAPIRequestError objects
|
||||
* @param original - original error
|
||||
*/
|
||||
function requestErrorWithOriginal(original) {
|
||||
const error = errorWithCode(new Error(`A request error occurred: ${original.message}`), ErrorCode.RequestError);
|
||||
error.original = original;
|
||||
return error;
|
||||
}
|
||||
exports.requestErrorWithOriginal = requestErrorWithOriginal;
|
||||
/**
|
||||
* A factory to create WebAPIHTTPError objects
|
||||
* @param response - original error
|
||||
*/
|
||||
function httpErrorFromResponse(response) {
|
||||
const error = errorWithCode(new Error(`An HTTP protocol error occurred: statusCode = ${response.status}`), ErrorCode.HTTPError);
|
||||
error.statusCode = response.status;
|
||||
error.statusMessage = response.statusText;
|
||||
error.headers = response.headers;
|
||||
error.body = response.data;
|
||||
return error;
|
||||
}
|
||||
exports.httpErrorFromResponse = httpErrorFromResponse;
|
||||
/**
|
||||
* A factory to create WebAPIPlatformError objects
|
||||
* @param result - Web API call result
|
||||
*/
|
||||
function platformErrorFromResult(result) {
|
||||
const error = errorWithCode(new Error(`An API error occurred: ${result.error}`), ErrorCode.PlatformError);
|
||||
error.data = result;
|
||||
return error;
|
||||
}
|
||||
exports.platformErrorFromResult = platformErrorFromResult;
|
||||
/**
|
||||
* A factory to create WebAPIRateLimitedError objects
|
||||
* @param retrySec - Number of seconds that the request can be retried in
|
||||
*/
|
||||
function rateLimitedErrorWithDelay(retrySec) {
|
||||
const error = errorWithCode(new Error(`A rate-limit has been reached, you may retry this request in ${retrySec} seconds`), ErrorCode.RateLimitedError);
|
||||
error.retryAfter = retrySec;
|
||||
return error;
|
||||
}
|
||||
exports.rateLimitedErrorWithDelay = rateLimitedErrorWithDelay;
|
||||
//# sourceMappingURL=errors.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAWA;;GAEG;AACH,IAAY,SAKX;AALD,WAAY,SAAS;IACnB,wDAA2C,CAAA;IAC3C,kDAAqC,CAAA;IACrC,0DAA6C,CAAA;IAC7C,iEAAoD,CAAA;AACtD,CAAC,EALW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAKpB;AA6BD;;GAEG;AACH,SAAS,aAAa,CAAC,KAAY,EAAE,IAAe;IAClD,kGAAkG;IAClG,MAAM,UAAU,GAAG,KAA4B,CAAC;IAChD,UAAU,CAAC,IAAI,GAAG,IAAI,CAAC;IACvB,OAAO,UAAwB,CAAC;AAClC,CAAC;AAED;;;GAGG;AACH,SAAgB,wBAAwB,CAAC,QAAe;IACtD,MAAM,KAAK,GAAG,aAAa,CACzB,IAAI,KAAK,CAAC,6BAA6B,QAAQ,CAAC,OAAO,EAAE,CAAC,EAC1D,SAAS,CAAC,YAAY,CACQ,CAAC;IACjC,KAAK,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,OAAQ,KAA4B,CAAC;AACvC,CAAC;AAPD,4DAOC;AAED;;;GAGG;AACH,SAAgB,qBAAqB,CAAC,QAAuB;IAC3D,MAAM,KAAK,GAAG,aAAa,CACzB,IAAI,KAAK,CAAC,iDAAiD,QAAQ,CAAC,MAAM,EAAE,CAAC,EAC7E,SAAS,CAAC,SAAS,CACQ,CAAC;IAC9B,KAAK,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC;IACnC,KAAK,CAAC,aAAa,GAAG,QAAQ,CAAC,UAAU,CAAC;IAC1C,KAAK,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;IACjC,KAAK,CAAC,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC3B,OAAQ,KAAyB,CAAC;AACpC,CAAC;AAVD,sDAUC;AAED;;;GAGG;AACH,SAAgB,uBAAuB,CAAC,MAA6C;IACnF,MAAM,KAAK,GAAG,aAAa,CACzB,IAAI,KAAK,CAAC,0BAA0B,MAAM,CAAC,KAAK,EAAE,CAAC,EACnD,SAAS,CAAC,aAAa,CACQ,CAAC;IAClC,KAAK,CAAC,IAAI,GAAG,MAAM,CAAC;IACpB,OAAQ,KAA6B,CAAC;AACxC,CAAC;AAPD,0DAOC;AAED;;;GAGG;AACH,SAAgB,yBAAyB,CAAC,QAAgB;IACxD,MAAM,KAAK,GAAG,aAAa,CACzB,IAAI,KAAK,CAAC,gEAAgE,QAAQ,UAAU,CAAC,EAC7F,SAAS,CAAC,gBAAgB,CACQ,CAAC;IACrC,KAAK,CAAC,UAAU,GAAG,QAAQ,CAAC;IAC5B,OAAQ,KAAgC,CAAC;AAC3C,CAAC;AAPD,8DAOC"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Build a Promise that will resolve after the specified number of milliseconds.
|
||||
* @param ms milliseconds to wait
|
||||
* @param value value for eventual resolution
|
||||
*/
|
||||
export declare function delay<T>(ms: number, value?: T): Promise<T>;
|
||||
//# sourceMappingURL=helpers.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,KAAK,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAI1D"}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.delay = void 0;
|
||||
/**
|
||||
* Build a Promise that will resolve after the specified number of milliseconds.
|
||||
* @param ms milliseconds to wait
|
||||
* @param value value for eventual resolution
|
||||
*/
|
||||
function delay(ms, value) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => resolve(value), ms);
|
||||
});
|
||||
}
|
||||
exports.delay = delay;
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACH,SAAgB,KAAK,CAAI,EAAU,EAAE,KAAS;IAC5C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,UAAU,CAAC,GAAG,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IACvC,CAAC,CAAC,CAAC;AACL,CAAC;AAJD,sBAIC"}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
/// <reference lib="es2017" />
|
||||
export { WebClient, WebClientOptions, WebAPICallOptions, WebAPICallResult, PageAccumulator, PageReducer, PaginatePredicate, WebClientEvent, TLSOptions, } from './WebClient';
|
||||
export { Logger, LogLevel } from './logger';
|
||||
export { CodedError, ErrorCode, WebAPICallError, WebAPIPlatformError, WebAPIRequestError, WebAPIHTTPError, WebAPIRateLimitedError, } from './errors';
|
||||
export { default as retryPolicies, RetryOptions } from './retry-policies';
|
||||
export { addAppMetadata } from './instrument';
|
||||
export * from './methods';
|
||||
export { default as Method } from './methods';
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAEA,OAAO,EACL,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,eAAe,EACf,WAAW,EACX,iBAAiB,EACjB,cAAc,EACd,UAAU,GACX,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,EACL,UAAU,EACV,SAAS,EACT,eAAe,EACf,mBAAmB,EACnB,kBAAkB,EAClB,eAAe,EACf,sBAAsB,GACvB,MAAM,UAAU,CAAC;AAElB,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAE1E,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C,cAAc,WAAW,CAAC;AAC1B,OAAO,EAAE,OAAO,IAAI,MAAM,EAAE,MAAM,WAAW,CAAC"}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
"use strict";
|
||||
/// <reference lib="es2017" />
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var WebClient_1 = require("./WebClient");
|
||||
Object.defineProperty(exports, "WebClient", { enumerable: true, get: function () { return WebClient_1.WebClient; } });
|
||||
Object.defineProperty(exports, "WebClientEvent", { enumerable: true, get: function () { return WebClient_1.WebClientEvent; } });
|
||||
var logger_1 = require("./logger");
|
||||
Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function () { return logger_1.LogLevel; } });
|
||||
var errors_1 = require("./errors");
|
||||
Object.defineProperty(exports, "ErrorCode", { enumerable: true, get: function () { return errors_1.ErrorCode; } });
|
||||
var retry_policies_1 = require("./retry-policies");
|
||||
Object.defineProperty(exports, "retryPolicies", { enumerable: true, get: function () { return retry_policies_1.default; } });
|
||||
var instrument_1 = require("./instrument");
|
||||
Object.defineProperty(exports, "addAppMetadata", { enumerable: true, get: function () { return instrument_1.addAppMetadata; } });
|
||||
__exportStar(require("./methods"), exports);
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,8BAA8B;;;;;;;;;;;;AAE9B,yCAUqB;AATnB,sGAAA,SAAS,OAAA;AAOT,2GAAA,cAAc,OAAA;AAIhB,mCAA4C;AAA3B,kGAAA,QAAQ,OAAA;AAEzB,mCAQkB;AANhB,mGAAA,SAAS,OAAA;AAQX,mDAA0E;AAAjE,+GAAA,OAAO,OAAiB;AAEjC,2CAA8C;AAArC,4GAAA,cAAc,OAAA;AAEvB,4CAA0B"}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Appends the app metadata into the User-Agent value
|
||||
* @param appMetadata.name - name of tool to be counted in instrumentation
|
||||
* @param appMetadata.version - version of tool to be counted in instrumentation
|
||||
*/
|
||||
export declare function addAppMetadata({ name, version }: {
|
||||
name: string;
|
||||
version: string;
|
||||
}): void;
|
||||
/**
|
||||
* Returns the current User-Agent value for instrumentation
|
||||
*/
|
||||
export declare function getUserAgent(): string;
|
||||
//# sourceMappingURL=instrument.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"instrument.d.ts","sourceRoot":"","sources":["../src/instrument.ts"],"names":[],"mappings":"AAgBA;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAEzF;AAED;;GAEG;AACH,wBAAgB,YAAY,IAAI,MAAM,CAIrC"}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getUserAgent = exports.addAppMetadata = void 0;
|
||||
const os = __importStar(require("os"));
|
||||
const packageJson = require('../package.json'); // tslint:disable-line:no-require-imports no-var-requires
|
||||
/**
|
||||
* Replaces occurrences of '/' with ':' in a string, since '/' is meaningful inside User-Agent strings as a separator.
|
||||
*/
|
||||
function replaceSlashes(s) {
|
||||
return s.replace('/', ':');
|
||||
}
|
||||
const baseUserAgent = `${replaceSlashes(packageJson.name)}/${packageJson.version} ` +
|
||||
`node/${process.version.replace('v', '')} ` +
|
||||
`${os.platform()}/${os.release()}`;
|
||||
const appMetadata = {};
|
||||
/**
|
||||
* Appends the app metadata into the User-Agent value
|
||||
* @param appMetadata.name - name of tool to be counted in instrumentation
|
||||
* @param appMetadata.version - version of tool to be counted in instrumentation
|
||||
*/
|
||||
function addAppMetadata({ name, version }) {
|
||||
appMetadata[replaceSlashes(name)] = version;
|
||||
}
|
||||
exports.addAppMetadata = addAppMetadata;
|
||||
/**
|
||||
* Returns the current User-Agent value for instrumentation
|
||||
*/
|
||||
function getUserAgent() {
|
||||
const appIdentifier = Object.entries(appMetadata).map(([name, version]) => `${name}/${version}`).join(' ');
|
||||
// only prepend the appIdentifier when its not empty
|
||||
return ((appIdentifier.length > 0) ? `${appIdentifier} ` : '') + baseUserAgent;
|
||||
}
|
||||
exports.getUserAgent = getUserAgent;
|
||||
//# sourceMappingURL=instrument.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"instrument.js","sourceRoot":"","sources":["../src/instrument.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAyB;AACzB,MAAM,WAAW,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC,yDAAyD;AAEzG;;GAEG;AACH,SAAS,cAAc,CAAC,CAAS;IAC/B,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC7B,CAAC;AAED,MAAM,aAAa,GAAG,GAAG,cAAc,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,WAAW,CAAC,OAAO,GAAG;IAC7D,QAAQ,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG;IAC3C,GAAG,EAAE,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC;AAEzD,MAAM,WAAW,GAA8B,EAAE,CAAC;AAElD;;;;GAIG;AACH,SAAgB,cAAc,CAAC,EAAE,IAAI,EAAE,OAAO,EAAqC;IACjF,WAAW,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,GAAG,OAAO,CAAC;AAC9C,CAAC;AAFD,wCAEC;AAED;;GAEG;AACH,SAAgB,YAAY;IAC1B,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,IAAI,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3G,oDAAoD;IACpD,OAAO,CAAC,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,aAAa,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,aAAa,CAAC;AACjF,CAAC;AAJD,oCAIC"}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
import { Logger, LogLevel } from '@slack/logger';
|
||||
export { Logger, LogLevel } from '@slack/logger';
|
||||
/**
|
||||
* INTERNAL interface for getting or creating a named Logger.
|
||||
*/
|
||||
export declare function getLogger(name: string, level: LogLevel, existingLogger?: Logger): Logger;
|
||||
//# sourceMappingURL=logger.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAiB,MAAM,eAAe,CAAC;AAChE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAIjD;;GAEG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,CAgBxF"}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getLogger = void 0;
|
||||
const logger_1 = require("@slack/logger");
|
||||
var logger_2 = require("@slack/logger");
|
||||
Object.defineProperty(exports, "LogLevel", { enumerable: true, get: function () { return logger_2.LogLevel; } });
|
||||
let instanceCount = 0;
|
||||
/**
|
||||
* INTERNAL interface for getting or creating a named Logger.
|
||||
*/
|
||||
function getLogger(name, level, existingLogger) {
|
||||
// Get a unique ID for the logger.
|
||||
const instanceId = instanceCount;
|
||||
instanceCount += 1;
|
||||
// Set up the logger.
|
||||
const logger = (() => {
|
||||
if (existingLogger !== undefined) {
|
||||
return existingLogger;
|
||||
}
|
||||
return new logger_1.ConsoleLogger();
|
||||
})();
|
||||
logger.setName(`web-api:${name}:${instanceId}`);
|
||||
if (level !== undefined) {
|
||||
logger.setLevel(level);
|
||||
}
|
||||
return logger;
|
||||
}
|
||||
exports.getLogger = getLogger;
|
||||
//# sourceMappingURL=logger.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":";;;AAAA,0CAAgE;AAChE,wCAAiD;AAAhC,kGAAA,QAAQ,OAAA;AAEzB,IAAI,aAAa,GAAG,CAAC,CAAC;AAEtB;;GAEG;AACH,SAAgB,SAAS,CAAC,IAAY,EAAE,KAAe,EAAE,cAAuB;IAC9E,kCAAkC;IAClC,MAAM,UAAU,GAAG,aAAa,CAAC;IACjC,aAAa,IAAI,CAAC,CAAC;IAEnB,qBAAqB;IACrB,MAAM,MAAM,GAAW,CAAC,GAAG,EAAE;QAC3B,IAAI,cAAc,KAAK,SAAS,EAAE;YAAE,OAAO,cAAc,CAAC;SAAE;QAC5D,OAAO,IAAI,sBAAa,EAAE,CAAC;IAC7B,CAAC,CAAC,EAAE,CAAC;IACL,MAAM,CAAC,OAAO,CAAC,WAAW,IAAI,IAAI,UAAU,EAAE,CAAC,CAAC;IAChD,IAAI,KAAK,KAAK,SAAS,EAAE;QACvB,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;KACxB;IAED,OAAO,MAAM,CAAC;AAChB,CAAC;AAhBD,8BAgBC"}
|
||||
+1292
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+406
@@ -0,0 +1,406 @@
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
||||
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.cursorPaginationEnabledMethods = exports.Methods = void 0;
|
||||
const WebClient_1 = require("./WebClient");
|
||||
const eventemitter3_1 = require("eventemitter3");
|
||||
// NOTE: could create a named type alias like data types like `SlackUserID: string`
|
||||
/**
|
||||
* Binds a certain `method` and its arguments and result types to the `apiCall` method in `WebClient`.
|
||||
*/
|
||||
function bindApiCall(self, method) {
|
||||
// We have to "assert" that the bound method does indeed return the more specific `Result` type instead of just
|
||||
// `WebAPICallResult`
|
||||
return self.apiCall.bind(self, method);
|
||||
}
|
||||
/**
|
||||
* A class that defines all Web API methods, their arguments type, their response type, and binds those methods to the
|
||||
* `apiCall` class method.
|
||||
*/
|
||||
class Methods extends eventemitter3_1.EventEmitter {
|
||||
// TODO: As of writing, `WebClient` already extends EventEmitter...
|
||||
// and I want WebClient to extend this class...
|
||||
// and multiple inheritance in JS is cursed...
|
||||
// so I'm just making this class extend EventEmitter.
|
||||
//
|
||||
// It shouldn't be here, indeed. Nothing here uses it, indeed. But it must be here for the sake of sanity.
|
||||
constructor() {
|
||||
super();
|
||||
this.admin = {
|
||||
apps: {
|
||||
approve: bindApiCall(this, 'admin.apps.approve'),
|
||||
approved: {
|
||||
list: bindApiCall(this, 'admin.apps.approved.list'),
|
||||
},
|
||||
requests: {
|
||||
list: bindApiCall(this, 'admin.apps.requests.list'),
|
||||
},
|
||||
restrict: bindApiCall(this, 'admin.apps.restrict'),
|
||||
restricted: {
|
||||
list: bindApiCall(this, 'admin.apps.restricted.list'),
|
||||
},
|
||||
},
|
||||
conversations: {
|
||||
archive: bindApiCall(this, 'admin.conversations.archive'),
|
||||
convertToPrivate: bindApiCall(this, 'admin.conversations.convertToPrivate'),
|
||||
create: bindApiCall(this, 'admin.conversations.create'),
|
||||
delete: bindApiCall(this, 'admin.conversations.delete'),
|
||||
disconnectShared: bindApiCall(this, 'admin.conversations.disconnectShared'),
|
||||
ekm: {
|
||||
listOriginalConnectedChannelInfo: bindApiCall(this, 'admin.conversations.ekm.listOriginalConnectedChannelInfo'),
|
||||
},
|
||||
getConversationPrefs: bindApiCall(this, 'admin.conversations.getConversationPrefs'),
|
||||
getTeams: bindApiCall(this, 'admin.conversations.getTeams'),
|
||||
invite: bindApiCall(this, 'admin.conversations.invite'),
|
||||
rename: bindApiCall(this, 'admin.conversations.rename'),
|
||||
restrictAccess: {
|
||||
addGroup: bindApiCall(this, 'admin.conversations.restrictAccess.addGroup'),
|
||||
listGroups: bindApiCall(this, 'admin.conversations.restrictAccess.listGroups'),
|
||||
removeGroup: bindApiCall(this, 'admin.conversations.restrictAccess.removeGroup'),
|
||||
},
|
||||
search: bindApiCall(this, 'admin.conversations.search'),
|
||||
setConversationPrefs: bindApiCall(this, 'admin.conversations.setConversationPrefs'),
|
||||
setTeams: bindApiCall(this, 'admin.conversations.setTeams'),
|
||||
unarchive: bindApiCall(this, 'admin.conversations.unarchive'),
|
||||
},
|
||||
emoji: {
|
||||
add: bindApiCall(this, 'admin.emoji.add'),
|
||||
addAlias: bindApiCall(this, 'admin.emoji.addAlias'),
|
||||
list: bindApiCall(this, 'admin.emoji.list'),
|
||||
remove: bindApiCall(this, 'admin.emoji.remove'),
|
||||
rename: bindApiCall(this, 'admin.emoji.rename'),
|
||||
},
|
||||
inviteRequests: {
|
||||
approve: bindApiCall(this, 'admin.inviteRequests.approve'),
|
||||
approved: {
|
||||
list: bindApiCall(this, 'admin.inviteRequests.approved.list'),
|
||||
},
|
||||
denied: {
|
||||
list: bindApiCall(this, 'admin.inviteRequests.denied.list'),
|
||||
},
|
||||
deny: bindApiCall(this, 'admin.inviteRequests.deny'),
|
||||
list: bindApiCall(this, 'admin.inviteRequests.list'),
|
||||
},
|
||||
teams: {
|
||||
admins: {
|
||||
list: bindApiCall(this, 'admin.teams.admins.list'),
|
||||
},
|
||||
create: bindApiCall(this, 'admin.teams.create'),
|
||||
list: bindApiCall(this, 'admin.teams.list'),
|
||||
owners: {
|
||||
list: bindApiCall(this, 'admin.teams.owners.list'),
|
||||
},
|
||||
settings: {
|
||||
info: bindApiCall(this, 'admin.teams.settings.info'),
|
||||
setDefaultChannels: bindApiCall(this, 'admin.teams.settings.setDefaultChannels'),
|
||||
setDescription: bindApiCall(this, 'admin.teams.settings.setDescription'),
|
||||
setDiscoverability: bindApiCall(this, 'admin.teams.settings.setDiscoverability'),
|
||||
setIcon: bindApiCall(this, 'admin.teams.settings.setIcon'),
|
||||
setName: bindApiCall(this, 'admin.teams.settings.setName'),
|
||||
},
|
||||
},
|
||||
usergroups: {
|
||||
addChannels: bindApiCall(this, 'admin.usergroups.addChannels'),
|
||||
addTeams: bindApiCall(this, 'admin.usergroups.addTeams'),
|
||||
listChannels: bindApiCall(this, 'admin.usergroups.listChannels'),
|
||||
removeChannels: bindApiCall(this, 'admin.usergroups.removeChannels'),
|
||||
},
|
||||
users: {
|
||||
assign: bindApiCall(this, 'admin.users.assign'),
|
||||
invite: bindApiCall(this, 'admin.users.invite'),
|
||||
list: bindApiCall(this, 'admin.users.list'),
|
||||
remove: bindApiCall(this, 'admin.users.remove'),
|
||||
session: {
|
||||
reset: bindApiCall(this, 'admin.users.session.reset'),
|
||||
invalidate: bindApiCall(this, 'admin.users.session.invalidate'),
|
||||
},
|
||||
setAdmin: bindApiCall(this, 'admin.users.setAdmin'),
|
||||
setExpiration: bindApiCall(this, 'admin.users.setExpiration'),
|
||||
setOwner: bindApiCall(this, 'admin.users.setOwner'),
|
||||
setRegular: bindApiCall(this, 'admin.users.setRegular'),
|
||||
},
|
||||
};
|
||||
this.api = {
|
||||
test: bindApiCall(this, 'api.test'),
|
||||
};
|
||||
this.apps = {
|
||||
event: {
|
||||
authorizations: {
|
||||
list: bindApiCall(this, 'apps.event.authorizations.list'),
|
||||
},
|
||||
},
|
||||
uninstall: bindApiCall(this, 'apps.uninstall'),
|
||||
};
|
||||
this.auth = {
|
||||
revoke: bindApiCall(this, 'auth.revoke'),
|
||||
test: bindApiCall(this, 'auth.test'),
|
||||
};
|
||||
this.bots = {
|
||||
info: bindApiCall(this, 'bots.info'),
|
||||
};
|
||||
this.calls = {
|
||||
add: bindApiCall(this, 'calls.add'),
|
||||
end: bindApiCall(this, 'calls.end'),
|
||||
info: bindApiCall(this, 'calls.info'),
|
||||
update: bindApiCall(this, 'calls.update'),
|
||||
participants: {
|
||||
add: bindApiCall(this, 'calls.participants.add'),
|
||||
remove: bindApiCall(this, 'calls.participants.remove'),
|
||||
},
|
||||
};
|
||||
this.channels = {
|
||||
archive: bindApiCall(this, 'channels.archive'),
|
||||
create: bindApiCall(this, 'channels.create'),
|
||||
history: bindApiCall(this, 'channels.history'),
|
||||
info: bindApiCall(this, 'channels.info'),
|
||||
invite: bindApiCall(this, 'channels.invite'),
|
||||
join: bindApiCall(this, 'channels.join'),
|
||||
kick: bindApiCall(this, 'channels.kick'),
|
||||
leave: bindApiCall(this, 'channels.leave'),
|
||||
list: bindApiCall(this, 'channels.list'),
|
||||
mark: bindApiCall(this, 'channels.mark'),
|
||||
rename: bindApiCall(this, 'channels.rename'),
|
||||
replies: bindApiCall(this, 'channels.replies'),
|
||||
setPurpose: bindApiCall(this, 'channels.setPurpose'),
|
||||
setTopic: bindApiCall(this, 'channels.setTopic'),
|
||||
unarchive: bindApiCall(this, 'channels.unarchive'),
|
||||
};
|
||||
this.chat = {
|
||||
delete: bindApiCall(this, 'chat.delete'),
|
||||
deleteScheduledMessage: bindApiCall(this, 'chat.deleteScheduledMessage'),
|
||||
getPermalink: bindApiCall(this, 'chat.getPermalink'),
|
||||
meMessage: bindApiCall(this, 'chat.meMessage'),
|
||||
postEphemeral: bindApiCall(this, 'chat.postEphemeral'),
|
||||
postMessage: bindApiCall(this, 'chat.postMessage'),
|
||||
scheduleMessage: bindApiCall(this, 'chat.scheduleMessage'),
|
||||
scheduledMessages: {
|
||||
list: bindApiCall(this, 'chat.scheduledMessages.list'),
|
||||
},
|
||||
unfurl: bindApiCall(this, 'chat.unfurl'),
|
||||
update: bindApiCall(this, 'chat.update'),
|
||||
};
|
||||
this.conversations = {
|
||||
archive: bindApiCall(this, 'conversations.archive'),
|
||||
close: bindApiCall(this, 'conversations.close'),
|
||||
create: bindApiCall(this, 'conversations.create'),
|
||||
history: bindApiCall(this, 'conversations.history'),
|
||||
info: bindApiCall(this, 'conversations.info'),
|
||||
invite: bindApiCall(this, 'conversations.invite'),
|
||||
join: bindApiCall(this, 'conversations.join'),
|
||||
kick: bindApiCall(this, 'conversations.kick'),
|
||||
leave: bindApiCall(this, 'conversations.leave'),
|
||||
list: bindApiCall(this, 'conversations.list'),
|
||||
mark: bindApiCall(this, 'conversations.mark'),
|
||||
members: bindApiCall(this, 'conversations.members'),
|
||||
open: bindApiCall(this, 'conversations.open'),
|
||||
rename: bindApiCall(this, 'conversations.rename'),
|
||||
replies: bindApiCall(this, 'conversations.replies'),
|
||||
setPurpose: bindApiCall(this, 'conversations.setPurpose'),
|
||||
setTopic: bindApiCall(this, 'conversations.setTopic'),
|
||||
unarchive: bindApiCall(this, 'conversations.unarchive'),
|
||||
};
|
||||
this.views = {
|
||||
open: bindApiCall(this, 'views.open'),
|
||||
publish: bindApiCall(this, 'views.publish'),
|
||||
push: bindApiCall(this, 'views.push'),
|
||||
update: bindApiCall(this, 'views.update'),
|
||||
};
|
||||
this.dialog = {
|
||||
open: bindApiCall(this, 'dialog.open'),
|
||||
};
|
||||
this.dnd = {
|
||||
endDnd: bindApiCall(this, 'dnd.endDnd'),
|
||||
endSnooze: bindApiCall(this, 'dnd.endSnooze'),
|
||||
info: bindApiCall(this, 'dnd.info'),
|
||||
setSnooze: bindApiCall(this, 'dnd.setSnooze'),
|
||||
teamInfo: bindApiCall(this, 'dnd.teamInfo'),
|
||||
};
|
||||
this.emoji = {
|
||||
list: bindApiCall(this, 'emoji.list'),
|
||||
};
|
||||
this.files = {
|
||||
delete: bindApiCall(this, 'files.delete'),
|
||||
info: bindApiCall(this, 'files.info'),
|
||||
list: bindApiCall(this, 'files.list'),
|
||||
revokePublicURL: bindApiCall(this, 'files.revokePublicURL'),
|
||||
sharedPublicURL: bindApiCall(this, 'files.sharedPublicURL'),
|
||||
upload: bindApiCall(this, 'files.upload'),
|
||||
comments: {
|
||||
delete: bindApiCall(this, 'files.comments.delete'),
|
||||
},
|
||||
remote: {
|
||||
info: bindApiCall(this, 'files.remote.info'),
|
||||
list: bindApiCall(this, 'files.remote.list'),
|
||||
add: bindApiCall(this, 'files.remote.add'),
|
||||
update: bindApiCall(this, 'files.remote.update'),
|
||||
remove: bindApiCall(this, 'files.remote.remove'),
|
||||
share: bindApiCall(this, 'files.remote.share'),
|
||||
},
|
||||
};
|
||||
this.groups = {
|
||||
archive: bindApiCall(this, 'groups.archive'),
|
||||
create: bindApiCall(this, 'groups.create'),
|
||||
createChild: bindApiCall(this, 'groups.createChild'),
|
||||
history: bindApiCall(this, 'groups.history'),
|
||||
info: bindApiCall(this, 'groups.info'),
|
||||
invite: bindApiCall(this, 'groups.invite'),
|
||||
kick: bindApiCall(this, 'groups.kick'),
|
||||
leave: bindApiCall(this, 'groups.leave'),
|
||||
list: bindApiCall(this, 'groups.list'),
|
||||
mark: bindApiCall(this, 'groups.mark'),
|
||||
open: bindApiCall(this, 'groups.open'),
|
||||
rename: bindApiCall(this, 'groups.rename'),
|
||||
replies: bindApiCall(this, 'groups.replies'),
|
||||
setPurpose: bindApiCall(this, 'groups.setPurpose'),
|
||||
setTopic: bindApiCall(this, 'groups.setTopic'),
|
||||
unarchive: bindApiCall(this, 'groups.unarchive'),
|
||||
};
|
||||
this.im = {
|
||||
close: bindApiCall(this, 'im.close'),
|
||||
history: bindApiCall(this, 'im.history'),
|
||||
list: bindApiCall(this, 'im.list'),
|
||||
mark: bindApiCall(this, 'im.mark'),
|
||||
open: bindApiCall(this, 'im.open'),
|
||||
replies: bindApiCall(this, 'im.replies'),
|
||||
};
|
||||
this.migration = {
|
||||
exchange: bindApiCall(this, 'migration.exchange'),
|
||||
};
|
||||
this.mpim = {
|
||||
close: bindApiCall(this, 'mpim.close'),
|
||||
history: bindApiCall(this, 'mpim.history'),
|
||||
list: bindApiCall(this, 'mpim.list'),
|
||||
mark: bindApiCall(this, 'mpim.mark'),
|
||||
open: bindApiCall(this, 'mpim.open'),
|
||||
replies: bindApiCall(this, 'mpim.replies'),
|
||||
};
|
||||
this.oauth = {
|
||||
access: bindApiCall(this, 'oauth.access'),
|
||||
v2: {
|
||||
access: bindApiCall(this, 'oauth.v2.access'),
|
||||
},
|
||||
};
|
||||
this.pins = {
|
||||
add: bindApiCall(this, 'pins.add'),
|
||||
list: bindApiCall(this, 'pins.list'),
|
||||
remove: bindApiCall(this, 'pins.remove'),
|
||||
};
|
||||
this.reactions = {
|
||||
add: bindApiCall(this, 'reactions.add'),
|
||||
get: bindApiCall(this, 'reactions.get'),
|
||||
list: bindApiCall(this, 'reactions.list'),
|
||||
remove: bindApiCall(this, 'reactions.remove'),
|
||||
};
|
||||
this.reminders = {
|
||||
add: bindApiCall(this, 'reminders.add'),
|
||||
complete: bindApiCall(this, 'reminders.complete'),
|
||||
delete: bindApiCall(this, 'reminders.delete'),
|
||||
info: bindApiCall(this, 'reminders.info'),
|
||||
list: bindApiCall(this, 'reminders.list'),
|
||||
};
|
||||
this.rtm = {
|
||||
connect: bindApiCall(this, 'rtm.connect'),
|
||||
start: bindApiCall(this, 'rtm.start'),
|
||||
};
|
||||
this.search = {
|
||||
all: bindApiCall(this, 'search.all'),
|
||||
files: bindApiCall(this, 'search.files'),
|
||||
messages: bindApiCall(this, 'search.messages'),
|
||||
};
|
||||
this.stars = {
|
||||
add: bindApiCall(this, 'stars.add'),
|
||||
list: bindApiCall(this, 'stars.list'),
|
||||
remove: bindApiCall(this, 'stars.remove'),
|
||||
};
|
||||
this.team = {
|
||||
accessLogs: bindApiCall(this, 'team.accessLogs'),
|
||||
billableInfo: bindApiCall(this, 'team.billableInfo'),
|
||||
info: bindApiCall(this, 'team.info'),
|
||||
integrationLogs: bindApiCall(this, 'team.integrationLogs'),
|
||||
profile: {
|
||||
get: bindApiCall(this, 'team.profile.get'),
|
||||
},
|
||||
};
|
||||
this.usergroups = {
|
||||
create: bindApiCall(this, 'usergroups.create'),
|
||||
disable: bindApiCall(this, 'usergroups.disable'),
|
||||
enable: bindApiCall(this, 'usergroups.enable'),
|
||||
list: bindApiCall(this, 'usergroups.list'),
|
||||
update: bindApiCall(this, 'usergroups.update'),
|
||||
users: {
|
||||
list: bindApiCall(this, 'usergroups.users.list'),
|
||||
update: bindApiCall(this, 'usergroups.users.update'),
|
||||
},
|
||||
};
|
||||
this.users = {
|
||||
conversations: bindApiCall(this, 'users.conversations'),
|
||||
deletePhoto: bindApiCall(this, 'users.deletePhoto'),
|
||||
getPresence: bindApiCall(this, 'users.getPresence'),
|
||||
identity: bindApiCall(this, 'users.identity'),
|
||||
info: bindApiCall(this, 'users.info'),
|
||||
list: bindApiCall(this, 'users.list'),
|
||||
lookupByEmail: bindApiCall(this, 'users.lookupByEmail'),
|
||||
setPhoto: bindApiCall(this, 'users.setPhoto'),
|
||||
setPresence: bindApiCall(this, 'users.setPresence'),
|
||||
profile: {
|
||||
get: bindApiCall(this, 'users.profile.get'),
|
||||
set: bindApiCall(this, 'users.profile.set'),
|
||||
},
|
||||
};
|
||||
this.workflows = {
|
||||
stepCompleted: bindApiCall(this, 'workflows.stepCompleted'),
|
||||
stepFailed: bindApiCall(this, 'workflows.stepFailed'),
|
||||
updateStep: bindApiCall(this, 'workflows.updateStep'),
|
||||
};
|
||||
// Check that the class being created extends from `WebClient` rather than this class
|
||||
if (new.target !== WebClient_1.WebClient && !(new.target.prototype instanceof WebClient_1.WebClient)) {
|
||||
throw new Error('Attempt to inherit from WebClient methods without inheriting from WebClient');
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.Methods = Methods;
|
||||
// A set of method names is initialized here and added to each time an argument type extends the CursorPaginationEnabled
|
||||
// interface, so that methods are checked against this set when using the pagination helper. If the method name is not
|
||||
// found, a warning is emitted to guide the developer to using the method correctly.
|
||||
exports.cursorPaginationEnabledMethods = new Set();
|
||||
exports.cursorPaginationEnabledMethods.add('admin.apps.approved.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.apps.requests.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.apps.restricted.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.conversations.ekm.listOriginalConnectedChannelInfo');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.conversations.getTeams');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.conversations.search');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.emoji.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.inviteRequests.approved.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.inviteRequests.denied.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.inviteRequests.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.teams.admins.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.teams.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.teams.owners.list');
|
||||
exports.cursorPaginationEnabledMethods.add('admin.users.list');
|
||||
exports.cursorPaginationEnabledMethods.add('apps.event.authorizations.list');
|
||||
exports.cursorPaginationEnabledMethods.add('channels.list');
|
||||
exports.cursorPaginationEnabledMethods.add('chat.scheduledMessages.list');
|
||||
exports.cursorPaginationEnabledMethods.add('conversations.history');
|
||||
exports.cursorPaginationEnabledMethods.add('conversations.list');
|
||||
exports.cursorPaginationEnabledMethods.add('conversations.members');
|
||||
exports.cursorPaginationEnabledMethods.add('conversations.replies');
|
||||
exports.cursorPaginationEnabledMethods.add('files.info');
|
||||
exports.cursorPaginationEnabledMethods.add('files.remote.list');
|
||||
exports.cursorPaginationEnabledMethods.add('groups.list');
|
||||
exports.cursorPaginationEnabledMethods.add('im.list');
|
||||
exports.cursorPaginationEnabledMethods.add('mpim.list');
|
||||
exports.cursorPaginationEnabledMethods.add('reactions.list');
|
||||
exports.cursorPaginationEnabledMethods.add('stars.list');
|
||||
exports.cursorPaginationEnabledMethods.add('users.conversations');
|
||||
exports.cursorPaginationEnabledMethods.add('users.list');
|
||||
__exportStar(require("@slack/types"), exports);
|
||||
//# sourceMappingURL=methods.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
+27
@@ -0,0 +1,27 @@
|
||||
import { Options } from 'p-retry';
|
||||
/**
|
||||
* Options to create retry policies. Extends from https://github.com/tim-kos/node-retry.
|
||||
*/
|
||||
export interface RetryOptions extends Options {
|
||||
}
|
||||
/**
|
||||
* The default retry policy. Retry up to 10 times, over the span of about 30 minutes. It's not exact because
|
||||
* randomization has been added to prevent a stampeding herd problem (if all instances in your application are retrying
|
||||
* a request at the exact same intervals, they are more likely to cause failures for each other).
|
||||
*/
|
||||
export declare const tenRetriesInAboutThirtyMinutes: RetryOptions;
|
||||
/**
|
||||
* Short & sweet, five retries in five minutes and then bail.
|
||||
*/
|
||||
export declare const fiveRetriesInFiveMinutes: RetryOptions;
|
||||
/**
|
||||
* This policy is just to keep the tests running fast.
|
||||
*/
|
||||
export declare const rapidRetryPolicy: RetryOptions;
|
||||
declare const policies: {
|
||||
tenRetriesInAboutThirtyMinutes: RetryOptions;
|
||||
fiveRetriesInFiveMinutes: RetryOptions;
|
||||
rapidRetryPolicy: RetryOptions;
|
||||
};
|
||||
export default policies;
|
||||
//# sourceMappingURL=retry-policies.d.ts.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"retry-policies.d.ts","sourceRoot":"","sources":["../src/retry-policies.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAElC;;GAEG;AACH,MAAM,WAAW,YAAa,SAAQ,OAAO;CAC5C;AAED;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,EAAE,YAI5C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,wBAAwB,EAAE,YAGtC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,gBAAgB,EAAE,YAG9B,CAAC;AAEF,QAAA,MAAM,QAAQ;;;;CAIb,CAAC;AAEF,eAAe,QAAQ,CAAC"}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.rapidRetryPolicy = exports.fiveRetriesInFiveMinutes = exports.tenRetriesInAboutThirtyMinutes = void 0;
|
||||
/**
|
||||
* The default retry policy. Retry up to 10 times, over the span of about 30 minutes. It's not exact because
|
||||
* randomization has been added to prevent a stampeding herd problem (if all instances in your application are retrying
|
||||
* a request at the exact same intervals, they are more likely to cause failures for each other).
|
||||
*/
|
||||
exports.tenRetriesInAboutThirtyMinutes = {
|
||||
retries: 10,
|
||||
factor: 1.96821,
|
||||
randomize: true,
|
||||
};
|
||||
/**
|
||||
* Short & sweet, five retries in five minutes and then bail.
|
||||
*/
|
||||
exports.fiveRetriesInFiveMinutes = {
|
||||
retries: 5,
|
||||
factor: 3.86,
|
||||
};
|
||||
/**
|
||||
* This policy is just to keep the tests running fast.
|
||||
*/
|
||||
exports.rapidRetryPolicy = {
|
||||
minTimeout: 0,
|
||||
maxTimeout: 1,
|
||||
};
|
||||
const policies = {
|
||||
tenRetriesInAboutThirtyMinutes: exports.tenRetriesInAboutThirtyMinutes,
|
||||
fiveRetriesInFiveMinutes: exports.fiveRetriesInFiveMinutes,
|
||||
rapidRetryPolicy: exports.rapidRetryPolicy,
|
||||
};
|
||||
exports.default = policies;
|
||||
//# sourceMappingURL=retry-policies.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"retry-policies.js","sourceRoot":"","sources":["../src/retry-policies.ts"],"names":[],"mappings":";;;AAQA;;;;GAIG;AACU,QAAA,8BAA8B,GAAiB;IAC1D,OAAO,EAAE,EAAE;IACX,MAAM,EAAE,OAAO;IACf,SAAS,EAAE,IAAI;CAChB,CAAC;AAEF;;GAEG;AACU,QAAA,wBAAwB,GAAiB;IACpD,OAAO,EAAE,CAAC;IACV,MAAM,EAAE,IAAI;CACb,CAAC;AAEF;;GAEG;AACU,QAAA,gBAAgB,GAAiB;IAC5C,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;CACd,CAAC;AAEF,MAAM,QAAQ,GAAG;IACf,8BAA8B,EAA9B,sCAA8B;IAC9B,wBAAwB,EAAxB,gCAAwB;IACxB,gBAAgB,EAAhB,wBAAgB;CACjB,CAAC;AAEF,kBAAe,QAAQ,CAAC"}
|
||||
+413
@@ -0,0 +1,413 @@
|
||||
# Changelog
|
||||
|
||||
### 0.19.2 (Jan 20, 2020)
|
||||
|
||||
- Remove unnecessary XSS check ([#2679](https://github.com/axios/axios/pull/2679)) (see ([#2646](https://github.com/axios/axios/issues/2646)) for discussion)
|
||||
|
||||
### 0.19.1 (Jan 7, 2020)
|
||||
|
||||
Fixes and Functionality:
|
||||
|
||||
- Fixing invalid agent issue ([#1904](https://github.com/axios/axios/pull/1904))
|
||||
- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
|
||||
- Delete useless default to hash ([#2458](https://github.com/axios/axios/pull/2458))
|
||||
- Fix HTTP/HTTPs agents passing to follow-redirect ([#1904](https://github.com/axios/axios/pull/1904))
|
||||
- Fix ignore set withCredentials false ([#2582](https://github.com/axios/axios/pull/2582))
|
||||
- Fix CI build failure ([#2570](https://github.com/axios/axios/pull/2570))
|
||||
- Remove dependency on is-buffer from package.json ([#1816](https://github.com/axios/axios/pull/1816))
|
||||
- Adding options typings ([#2341](https://github.com/axios/axios/pull/2341))
|
||||
- Adding Typescript HTTP method definition for LINK and UNLINK. ([#2444](https://github.com/axios/axios/pull/2444))
|
||||
- Update dist with newest changes, fixes Custom Attributes issue
|
||||
- Change syntax to see if build passes ([#2488](https://github.com/axios/axios/pull/2488))
|
||||
- Update Webpack + deps, remove now unnecessary polyfills ([#2410](https://github.com/axios/axios/pull/2410))
|
||||
- Fix to prevent XSS, throw an error when the URL contains a JS script ([#2464](https://github.com/axios/axios/pull/2464))
|
||||
- Add custom timeout error copy in config ([#2275](https://github.com/axios/axios/pull/2275))
|
||||
- Add error toJSON example ([#2466](https://github.com/axios/axios/pull/2466))
|
||||
- Fixing Vulnerability A Fortify Scan finds a critical Cross-Site Scrip… ([#2451](https://github.com/axios/axios/pull/2451))
|
||||
- Fixing subdomain handling on no_proxy ([#2442](https://github.com/axios/axios/pull/2442))
|
||||
- Make redirection from HTTP to HTTPS work ([#2426](https://github.com/axios/axios/pull/2426] and ([#2547](https://github.com/axios/axios/pull/2547))
|
||||
- Add toJSON property to AxiosError type ([#2427](https://github.com/axios/axios/pull/2427))
|
||||
- Fixing socket hang up error on node side for slow response. ([#1752](https://github.com/axios/axios/pull/1752))
|
||||
- Alternative syntax to send data into the body ([#2317](https://github.com/axios/axios/pull/2317))
|
||||
- Fixing custom config options ([#2207](https://github.com/axios/axios/pull/2207))
|
||||
- Fixing set `config.method` after mergeConfig for Axios.prototype.request ([#2383](https://github.com/axios/axios/pull/2383))
|
||||
- Axios create url bug ([#2290](https://github.com/axios/axios/pull/2290))
|
||||
- Do not modify config.url when using a relative baseURL (resolves [#1628](https://github.com/axios/axios/issues/1098)) ([#2391](https://github.com/axios/axios/pull/2391))
|
||||
- Add typescript HTTP method definition for LINK and UNLINK ([#2444](https://github.com/axios/axios/pull/2444))
|
||||
|
||||
Internal:
|
||||
|
||||
- Revert "Update Webpack + deps, remove now unnecessary polyfills" ([#2479](https://github.com/axios/axios/pull/2479))
|
||||
- Order of if/else blocks is causing unit tests mocking XHR. ([#2201](https://github.com/axios/axios/pull/2201))
|
||||
- Add license badge ([#2446](https://github.com/axios/axios/pull/2446))
|
||||
- Fix travis CI build [#2386](https://github.com/axios/axios/pull/2386)
|
||||
- Fix cancellation error on build master. #2290 #2207 ([#2407](https://github.com/axios/axios/pull/2407))
|
||||
|
||||
Documentation:
|
||||
|
||||
- Fixing typo in CHANGELOG.md: s/Functionallity/Functionality ([#2639](https://github.com/axios/axios/pull/2639))
|
||||
- Fix badge, use master branch ([#2538](https://github.com/axios/axios/pull/2538))
|
||||
- Fix typo in changelog [#2193](https://github.com/axios/axios/pull/2193)
|
||||
- Document fix ([#2514](https://github.com/axios/axios/pull/2514))
|
||||
- Update docs with no_proxy change, issue #2484 ([#2513](https://github.com/axios/axios/pull/2513))
|
||||
- Fixing missing words in docs template ([#2259](https://github.com/axios/axios/pull/2259))
|
||||
- 🐛Fix request finally documentation in README ([#2189](https://github.com/axios/axios/pull/2189))
|
||||
- updating spelling and adding link to docs ([#2212](https://github.com/axios/axios/pull/2212))
|
||||
- docs: minor tweak ([#2404](https://github.com/axios/axios/pull/2404))
|
||||
- Update response interceptor docs ([#2399](https://github.com/axios/axios/pull/2399))
|
||||
- Update README.md ([#2504](https://github.com/axios/axios/pull/2504))
|
||||
- Fix word 'sintaxe' to 'syntax' in README.md ([#2432](https://github.com/axios/axios/pull/2432))
|
||||
- upadating README: notes on CommonJS autocomplete ([#2256](https://github.com/axios/axios/pull/2256))
|
||||
- Fix grammar in README.md ([#2271](https://github.com/axios/axios/pull/2271))
|
||||
- Doc fixes, minor examples cleanup ([#2198](https://github.com/axios/axios/pull/2198))
|
||||
|
||||
### 0.19.0 (May 30, 2019)
|
||||
|
||||
Fixes and Functionality:
|
||||
|
||||
- Added support for no_proxy env variable ([#1693](https://github.com/axios/axios/pull/1693/files)) - Chance Dickson
|
||||
- Unzip response body only for statuses != 204 ([#1129](https://github.com/axios/axios/pull/1129)) - drawski
|
||||
- Destroy stream on exceeding maxContentLength (fixes [#1098](https://github.com/axios/axios/issues/1098)) ([#1485](https://github.com/axios/axios/pull/1485)) - Gadzhi Gadzhiev
|
||||
- Makes Axios error generic to use AxiosResponse ([#1738](https://github.com/axios/axios/pull/1738)) - Suman Lama
|
||||
- Fixing Mocha tests by locking follow-redirects version to 1.5.10 ([#1993](https://github.com/axios/axios/pull/1993)) - grumblerchester
|
||||
- Allow uppercase methods in typings. ([#1781](https://github.com/axios/axios/pull/1781)) - Ken Powers
|
||||
- Fixing building url with hash mark ([#1771](https://github.com/axios/axios/pull/1771)) - Anatoly Ryabov
|
||||
- This commit fix building url with hash map (fragment identifier) when parameters are present: they must not be added after `#`, because client cut everything after `#`
|
||||
- Preserve HTTP method when following redirect ([#1758](https://github.com/axios/axios/pull/1758)) - Rikki Gibson
|
||||
- Add `getUri` signature to TypeScript definition. ([#1736](https://github.com/axios/axios/pull/1736)) - Alexander Trauzzi
|
||||
- Adding isAxiosError flag to errors thrown by axios ([#1419](https://github.com/axios/axios/pull/1419)) - Ayush Gupta
|
||||
|
||||
Internal:
|
||||
|
||||
- Fixing .eslintrc without extension ([#1789](https://github.com/axios/axios/pull/1789)) - Manoel
|
||||
- Fix failing SauceLabs tests by updating configuration - Emily Morehouse
|
||||
- Add issue templates - Emily Morehouse
|
||||
|
||||
Documentation:
|
||||
|
||||
- Consistent coding style in README ([#1787](https://github.com/axios/axios/pull/1787)) - Ali Servet Donmez
|
||||
- Add information about auth parameter to README ([#2166](https://github.com/axios/axios/pull/2166)) - xlaguna
|
||||
- Add DELETE to list of methods that allow data as a config option ([#2169](https://github.com/axios/axios/pull/2169)) - Daniela Borges Matos de Carvalho
|
||||
- Update ECOSYSTEM.md - Add Axios Endpoints ([#2176](https://github.com/axios/axios/pull/2176)) - Renan
|
||||
- Add r2curl in ECOSYSTEM ([#2141](https://github.com/axios/axios/pull/2141)) - 유용우 / CX
|
||||
- Update README.md - Add instructions for installing with yarn ([#2036](https://github.com/axios/axios/pull/2036)) - Victor Hermes
|
||||
- Fixing spacing for README.md ([#2066](https://github.com/axios/axios/pull/2066)) - Josh McCarty
|
||||
- Update README.md. - Change `.then` to `.finally` in example code ([#2090](https://github.com/axios/axios/pull/2090)) - Omar Cai
|
||||
- Clarify what values responseType can have in Node ([#2121](https://github.com/axios/axios/pull/2121)) - Tyler Breisacher
|
||||
- docs(ECOSYSTEM): add axios-api-versioning ([#2020](https://github.com/axios/axios/pull/2020)) - Weffe
|
||||
- It seems that `responseType: 'blob'` doesn't actually work in Node (when I tried using it, response.data was a string, not a Blob, since Node doesn't have Blobs), so this clarifies that this option should only be used in the browser
|
||||
- Update README.md. - Add Querystring library note ([#1896](https://github.com/axios/axios/pull/1896)) - Dmitriy Eroshenko
|
||||
- Add react-hooks-axios to Libraries section of ECOSYSTEM.md ([#1925](https://github.com/axios/axios/pull/1925)) - Cody Chan
|
||||
- Clarify in README that default timeout is 0 (no timeout) ([#1750](https://github.com/axios/axios/pull/1750)) - Ben Standefer
|
||||
|
||||
### 0.19.0-beta.1 (Aug 9, 2018)
|
||||
|
||||
**NOTE:** This is a beta version of this release. There may be functionality that is broken in
|
||||
certain browsers, though we suspect that builds are hanging and not erroring. See
|
||||
https://saucelabs.com/u/axios for the most up-to-date information.
|
||||
|
||||
New Functionality:
|
||||
|
||||
- Add getUri method ([#1712](https://github.com/axios/axios/issues/1712))
|
||||
- Add support for no_proxy env variable ([#1693](https://github.com/axios/axios/issues/1693))
|
||||
- Add toJSON to decorated Axios errors to faciliate serialization ([#1625](https://github.com/axios/axios/issues/1625))
|
||||
- Add second then on axios call ([#1623](https://github.com/axios/axios/issues/1623))
|
||||
- Typings: allow custom return types
|
||||
- Add option to specify character set in responses (with http adapter)
|
||||
|
||||
Fixes:
|
||||
|
||||
- Fix Keep defaults local to instance ([#385](https://github.com/axios/axios/issues/385))
|
||||
- Correctly catch exception in http test ([#1475](https://github.com/axios/axios/issues/1475))
|
||||
- Fix accept header normalization ([#1698](https://github.com/axios/axios/issues/1698))
|
||||
- Fix http adapter to allow HTTPS connections via HTTP ([#959](https://github.com/axios/axios/issues/959))
|
||||
- Fix Removes usage of deprecated Buffer constructor. ([#1555](https://github.com/axios/axios/issues/1555), [#1622](https://github.com/axios/axios/issues/1622))
|
||||
- Fix defaults to use httpAdapter if available ([#1285](https://github.com/axios/axios/issues/1285))
|
||||
- Fixing defaults to use httpAdapter if available
|
||||
- Use a safer, cross-platform method to detect the Node environment
|
||||
- Fix Reject promise if request is cancelled by the browser ([#537](https://github.com/axios/axios/issues/537))
|
||||
- [Typescript] Fix missing type parameters on delete/head methods
|
||||
- [NS]: Send `false` flag isStandardBrowserEnv for Nativescript
|
||||
- Fix missing type parameters on delete/head
|
||||
- Fix Default method for an instance always overwritten by get
|
||||
- Fix type error when socketPath option in AxiosRequestConfig
|
||||
- Capture errors on request data streams
|
||||
- Decorate resolve and reject to clear timeout in all cases
|
||||
|
||||
Huge thanks to everyone who contributed to this release via code (authors listed
|
||||
below) or via reviews and triaging on GitHub:
|
||||
|
||||
- Andrew Scott <ascott18@gmail.com>
|
||||
- Anthony Gauthier <antho325@hotmail.com>
|
||||
- arpit <arpit2438735@gmail.com>
|
||||
- ascott18
|
||||
- Benedikt Rötsch <axe312ger@users.noreply.github.com>
|
||||
- Chance Dickson <me@chancedickson.com>
|
||||
- Dave Stewart <info@davestewart.co.uk>
|
||||
- Deric Cain <deric.cain@gmail.com>
|
||||
- Guillaume Briday <guillaumebriday@gmail.com>
|
||||
- Jacob Wejendorp <jacob@wejendorp.dk>
|
||||
- Jim Lynch <mrdotjim@gmail.com>
|
||||
- johntron
|
||||
- Justin Beckwith <beckwith@google.com>
|
||||
- Justin Beckwith <justin.beckwith@gmail.com>
|
||||
- Khaled Garbaya <khaledgarbaya@gmail.com>
|
||||
- Lim Jing Rong <jjingrong@users.noreply.github.com>
|
||||
- Mark van den Broek <mvdnbrk@gmail.com>
|
||||
- Martti Laine <martti@codeclown.net>
|
||||
- mattridley
|
||||
- mattridley <matt.r@joinblink.com>
|
||||
- Nicolas Del Valle <nicolas.delvalle@gmail.com>
|
||||
- Nilegfx
|
||||
- pbarbiero
|
||||
- Rikki Gibson <rikkigibson@gmail.com>
|
||||
- Sako Hartounian <sakohartounian@yahoo.com>
|
||||
- Shane Fitzpatrick <fitzpasd@gmail.com>
|
||||
- Stephan Schneider <stephanschndr@gmail.com>
|
||||
- Steven <steven@ceriously.com>
|
||||
- Tim Garthwaite <tim.garthwaite@jibo.com>
|
||||
- Tim Johns <timjohns@yahoo.com>
|
||||
- Yutaro Miyazaki <yutaro@studio-rubbish.com>
|
||||
|
||||
### 0.18.0 (Feb 19, 2018)
|
||||
|
||||
- Adding support for UNIX Sockets when running with Node.js ([#1070](https://github.com/axios/axios/pull/1070))
|
||||
- Fixing typings ([#1177](https://github.com/axios/axios/pull/1177)):
|
||||
- AxiosRequestConfig.proxy: allows type false
|
||||
- AxiosProxyConfig: added auth field
|
||||
- Adding function signature in AxiosInstance interface so AxiosInstance can be invoked ([#1192](https://github.com/axios/axios/pull/1192), [#1254](https://github.com/axios/axios/pull/1254))
|
||||
- Allowing maxContentLength to pass through to redirected calls as maxBodyLength in follow-redirects config ([#1287](https://github.com/axios/axios/pull/1287))
|
||||
- Fixing configuration when using an instance - method can now be set ([#1342](https://github.com/axios/axios/pull/1342))
|
||||
|
||||
### 0.17.1 (Nov 11, 2017)
|
||||
|
||||
- Fixing issue with web workers ([#1160](https://github.com/axios/axios/pull/1160))
|
||||
- Allowing overriding transport ([#1080](https://github.com/axios/axios/pull/1080))
|
||||
- Updating TypeScript typings ([#1165](https://github.com/axios/axios/pull/1165), [#1125](https://github.com/axios/axios/pull/1125), [#1131](https://github.com/axios/axios/pull/1131))
|
||||
|
||||
### 0.17.0 (Oct 21, 2017)
|
||||
|
||||
- **BREAKING** Fixing issue with `baseURL` and interceptors ([#950](https://github.com/axios/axios/pull/950))
|
||||
- **BREAKING** Improving handing of duplicate headers ([#874](https://github.com/axios/axios/pull/874))
|
||||
- Adding support for disabling proxies ([#691](https://github.com/axios/axios/pull/691))
|
||||
- Updating TypeScript typings with generic type parameters ([#1061](https://github.com/axios/axios/pull/1061))
|
||||
|
||||
### 0.16.2 (Jun 3, 2017)
|
||||
|
||||
- Fixing issue with including `buffer` in bundle ([#887](https://github.com/axios/axios/pull/887))
|
||||
- Including underlying request in errors ([#830](https://github.com/axios/axios/pull/830))
|
||||
- Convert `method` to lowercase ([#930](https://github.com/axios/axios/pull/930))
|
||||
|
||||
### 0.16.1 (Apr 8, 2017)
|
||||
|
||||
- Improving HTTP adapter to return last request in case of redirects ([#828](https://github.com/axios/axios/pull/828))
|
||||
- Updating `follow-redirects` dependency ([#829](https://github.com/axios/axios/pull/829))
|
||||
- Adding support for passing `Buffer` in node ([#773](https://github.com/axios/axios/pull/773))
|
||||
|
||||
### 0.16.0 (Mar 31, 2017)
|
||||
|
||||
- **BREAKING** Removing `Promise` from axios typings in favor of built-in type declarations ([#480](https://github.com/axios/axios/issues/480))
|
||||
- Adding `options` shortcut method ([#461](https://github.com/axios/axios/pull/461))
|
||||
- Fixing issue with using `responseType: 'json'` in browsers incompatible with XHR Level 2 ([#654](https://github.com/axios/axios/pull/654))
|
||||
- Improving React Native detection ([#731](https://github.com/axios/axios/pull/731))
|
||||
- Fixing `combineURLs` to support empty `relativeURL` ([#581](https://github.com/axios/axios/pull/581))
|
||||
- Removing `PROTECTION_PREFIX` support ([#561](https://github.com/axios/axios/pull/561))
|
||||
|
||||
### 0.15.3 (Nov 27, 2016)
|
||||
|
||||
- Fixing issue with custom instances and global defaults ([#443](https://github.com/axios/axios/issues/443))
|
||||
- Renaming `axios.d.ts` to `index.d.ts` ([#519](https://github.com/axios/axios/issues/519))
|
||||
- Adding `get`, `head`, and `delete` to `defaults.headers` ([#509](https://github.com/axios/axios/issues/509))
|
||||
- Fixing issue with `btoa` and IE ([#507](https://github.com/axios/axios/issues/507))
|
||||
- Adding support for proxy authentication ([#483](https://github.com/axios/axios/pull/483))
|
||||
- Improving HTTP adapter to use `http` protocol by default ([#493](https://github.com/axios/axios/pull/493))
|
||||
- Fixing proxy issues ([#491](https://github.com/axios/axios/pull/491))
|
||||
|
||||
### 0.15.2 (Oct 17, 2016)
|
||||
|
||||
- Fixing issue with calling `cancel` after response has been received ([#482](https://github.com/axios/axios/issues/482))
|
||||
|
||||
### 0.15.1 (Oct 14, 2016)
|
||||
|
||||
- Fixing issue with UMD ([#485](https://github.com/axios/axios/issues/485))
|
||||
|
||||
### 0.15.0 (Oct 10, 2016)
|
||||
|
||||
- Adding cancellation support ([#452](https://github.com/axios/axios/pull/452))
|
||||
- Moving default adapter to global defaults ([#437](https://github.com/axios/axios/pull/437))
|
||||
- Fixing issue with `file` URI scheme ([#440](https://github.com/axios/axios/pull/440))
|
||||
- Fixing issue with `params` objects that have no prototype ([#445](https://github.com/axios/axios/pull/445))
|
||||
|
||||
### 0.14.0 (Aug 27, 2016)
|
||||
|
||||
- **BREAKING** Updating TypeScript definitions ([#419](https://github.com/axios/axios/pull/419))
|
||||
- **BREAKING** Replacing `agent` option with `httpAgent` and `httpsAgent` ([#387](https://github.com/axios/axios/pull/387))
|
||||
- **BREAKING** Splitting `progress` event handlers into `onUploadProgress` and `onDownloadProgress` ([#423](https://github.com/axios/axios/pull/423))
|
||||
- Adding support for `http_proxy` and `https_proxy` environment variables ([#366](https://github.com/axios/axios/pull/366))
|
||||
- Fixing issue with `auth` config option and `Authorization` header ([#397](https://github.com/axios/axios/pull/397))
|
||||
- Don't set XSRF header if `xsrfCookieName` is `null` ([#406](https://github.com/axios/axios/pull/406))
|
||||
|
||||
### 0.13.1 (Jul 16, 2016)
|
||||
|
||||
- Fixing issue with response data not being transformed on error ([#378](https://github.com/axios/axios/issues/378))
|
||||
|
||||
### 0.13.0 (Jul 13, 2016)
|
||||
|
||||
- **BREAKING** Improved error handling ([#345](https://github.com/axios/axios/pull/345))
|
||||
- **BREAKING** Response transformer now invoked in dispatcher not adapter ([10eb238](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e))
|
||||
- **BREAKING** Request adapters now return a `Promise` ([157efd5](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a))
|
||||
- Fixing issue with `withCredentials` not being overwritten ([#343](https://github.com/axios/axios/issues/343))
|
||||
- Fixing regression with request transformer being called before request interceptor ([#352](https://github.com/axios/axios/issues/352))
|
||||
- Fixing custom instance defaults ([#341](https://github.com/axios/axios/issues/341))
|
||||
- Fixing instances created from `axios.create` to have same API as default axios ([#217](https://github.com/axios/axios/issues/217))
|
||||
|
||||
### 0.12.0 (May 31, 2016)
|
||||
|
||||
- Adding support for `URLSearchParams` ([#317](https://github.com/axios/axios/pull/317))
|
||||
- Adding `maxRedirects` option ([#307](https://github.com/axios/axios/pull/307))
|
||||
|
||||
### 0.11.1 (May 17, 2016)
|
||||
|
||||
- Fixing IE CORS support ([#313](https://github.com/axios/axios/pull/313))
|
||||
- Fixing detection of `FormData` ([#325](https://github.com/axios/axios/pull/325))
|
||||
- Adding `Axios` class to exports ([#321](https://github.com/axios/axios/pull/321))
|
||||
|
||||
### 0.11.0 (Apr 26, 2016)
|
||||
|
||||
- Adding support for Stream with HTTP adapter ([#296](https://github.com/axios/axios/pull/296))
|
||||
- Adding support for custom HTTP status code error ranges ([#308](https://github.com/axios/axios/pull/308))
|
||||
- Fixing issue with ArrayBuffer ([#299](https://github.com/axios/axios/pull/299))
|
||||
|
||||
### 0.10.0 (Apr 20, 2016)
|
||||
|
||||
- Fixing issue with some requests sending `undefined` instead of `null` ([#250](https://github.com/axios/axios/pull/250))
|
||||
- Fixing basic auth for HTTP adapter ([#252](https://github.com/axios/axios/pull/252))
|
||||
- Fixing request timeout for XHR adapter ([#227](https://github.com/axios/axios/pull/227))
|
||||
- Fixing IE8 support by using `onreadystatechange` instead of `onload` ([#249](https://github.com/axios/axios/pull/249))
|
||||
- Fixing IE9 cross domain requests ([#251](https://github.com/axios/axios/pull/251))
|
||||
- Adding `maxContentLength` option ([#275](https://github.com/axios/axios/pull/275))
|
||||
- Fixing XHR support for WebWorker environment ([#279](https://github.com/axios/axios/pull/279))
|
||||
- Adding request instance to response ([#200](https://github.com/axios/axios/pull/200))
|
||||
|
||||
### 0.9.1 (Jan 24, 2016)
|
||||
|
||||
- Improving handling of request timeout in node ([#124](https://github.com/axios/axios/issues/124))
|
||||
- Fixing network errors not rejecting ([#205](https://github.com/axios/axios/pull/205))
|
||||
- Fixing issue with IE rejecting on HTTP 204 ([#201](https://github.com/axios/axios/issues/201))
|
||||
- Fixing host/port when following redirects ([#198](https://github.com/axios/axios/pull/198))
|
||||
|
||||
### 0.9.0 (Jan 18, 2016)
|
||||
|
||||
- Adding support for custom adapters
|
||||
- Fixing Content-Type header being removed when data is false ([#195](https://github.com/axios/axios/pull/195))
|
||||
- Improving XDomainRequest implementation ([#185](https://github.com/axios/axios/pull/185))
|
||||
- Improving config merging and order of precedence ([#183](https://github.com/axios/axios/pull/183))
|
||||
- Fixing XDomainRequest support for only <= IE9 ([#182](https://github.com/axios/axios/pull/182))
|
||||
|
||||
### 0.8.1 (Dec 14, 2015)
|
||||
|
||||
- Adding support for passing XSRF token for cross domain requests when using `withCredentials` ([#168](https://github.com/axios/axios/pull/168))
|
||||
- Fixing error with format of basic auth header ([#178](https://github.com/axios/axios/pull/173))
|
||||
- Fixing error with JSON payloads throwing `InvalidStateError` in some cases ([#174](https://github.com/axios/axios/pull/174))
|
||||
|
||||
### 0.8.0 (Dec 11, 2015)
|
||||
|
||||
- Adding support for creating instances of axios ([#123](https://github.com/axios/axios/pull/123))
|
||||
- Fixing http adapter to use `Buffer` instead of `String` in case of `responseType === 'arraybuffer'` ([#128](https://github.com/axios/axios/pull/128))
|
||||
- Adding support for using custom parameter serializer with `paramsSerializer` option ([#121](https://github.com/axios/axios/pull/121))
|
||||
- Fixing issue in IE8 caused by `forEach` on `arguments` ([#127](https://github.com/axios/axios/pull/127))
|
||||
- Adding support for following redirects in node ([#146](https://github.com/axios/axios/pull/146))
|
||||
- Adding support for transparent decompression if `content-encoding` is set ([#149](https://github.com/axios/axios/pull/149))
|
||||
- Adding support for transparent XDomainRequest to handle cross domain requests in IE9 ([#140](https://github.com/axios/axios/pull/140))
|
||||
- Adding support for HTTP basic auth via Authorization header ([#167](https://github.com/axios/axios/pull/167))
|
||||
- Adding support for baseURL option ([#160](https://github.com/axios/axios/pull/160))
|
||||
|
||||
### 0.7.0 (Sep 29, 2015)
|
||||
|
||||
- Fixing issue with minified bundle in IE8 ([#87](https://github.com/axios/axios/pull/87))
|
||||
- Adding support for passing agent in node ([#102](https://github.com/axios/axios/pull/102))
|
||||
- Adding support for returning result from `axios.spread` for chaining ([#106](https://github.com/axios/axios/pull/106))
|
||||
- Fixing typescript definition ([#105](https://github.com/axios/axios/pull/105))
|
||||
- Fixing default timeout config for node ([#112](https://github.com/axios/axios/pull/112))
|
||||
- Adding support for use in web workers, and react-native ([#70](https://github.com/axios/axios/issue/70)), ([#98](https://github.com/axios/axios/pull/98))
|
||||
- Adding support for fetch like API `axios(url[, config])` ([#116](https://github.com/axios/axios/issues/116))
|
||||
|
||||
### 0.6.0 (Sep 21, 2015)
|
||||
|
||||
- Removing deprecated success/error aliases
|
||||
- Fixing issue with array params not being properly encoded ([#49](https://github.com/axios/axios/pull/49))
|
||||
- Fixing issue with User-Agent getting overridden ([#69](https://github.com/axios/axios/issues/69))
|
||||
- Adding support for timeout config ([#56](https://github.com/axios/axios/issues/56))
|
||||
- Removing es6-promise dependency
|
||||
- Fixing issue preventing `length` to be used as a parameter ([#91](https://github.com/axios/axios/pull/91))
|
||||
- Fixing issue with IE8 ([#85](https://github.com/axios/axios/pull/85))
|
||||
- Converting build to UMD
|
||||
|
||||
### 0.5.4 (Apr 08, 2015)
|
||||
|
||||
- Fixing issue with FormData not being sent ([#53](https://github.com/axios/axios/issues/53))
|
||||
|
||||
### 0.5.3 (Apr 07, 2015)
|
||||
|
||||
- Using JSON.parse unconditionally when transforming response string ([#55](https://github.com/axios/axios/issues/55))
|
||||
|
||||
### 0.5.2 (Mar 13, 2015)
|
||||
|
||||
- Adding support for `statusText` in response ([#46](https://github.com/axios/axios/issues/46))
|
||||
|
||||
### 0.5.1 (Mar 10, 2015)
|
||||
|
||||
- Fixing issue using strict mode ([#45](https://github.com/axios/axios/issues/45))
|
||||
- Fixing issue with standalone build ([#47](https://github.com/axios/axios/issues/47))
|
||||
|
||||
### 0.5.0 (Jan 23, 2015)
|
||||
|
||||
- Adding support for intercepetors ([#14](https://github.com/axios/axios/issues/14))
|
||||
- Updating es6-promise dependency
|
||||
|
||||
### 0.4.2 (Dec 10, 2014)
|
||||
|
||||
- Fixing issue with `Content-Type` when using `FormData` ([#22](https://github.com/axios/axios/issues/22))
|
||||
- Adding support for TypeScript ([#25](https://github.com/axios/axios/issues/25))
|
||||
- Fixing issue with standalone build ([#29](https://github.com/axios/axios/issues/29))
|
||||
- Fixing issue with verbs needing to be capitalized in some browsers ([#30](https://github.com/axios/axios/issues/30))
|
||||
|
||||
### 0.4.1 (Oct 15, 2014)
|
||||
|
||||
- Adding error handling to request for node.js ([#18](https://github.com/axios/axios/issues/18))
|
||||
|
||||
### 0.4.0 (Oct 03, 2014)
|
||||
|
||||
- Adding support for `ArrayBuffer` and `ArrayBufferView` ([#10](https://github.com/axios/axios/issues/10))
|
||||
- Adding support for utf-8 for node.js ([#13](https://github.com/axios/axios/issues/13))
|
||||
- Adding support for SSL for node.js ([#12](https://github.com/axios/axios/issues/12))
|
||||
- Fixing incorrect `Content-Type` header ([#9](https://github.com/axios/axios/issues/9))
|
||||
- Adding standalone build without bundled es6-promise ([#11](https://github.com/axios/axios/issues/11))
|
||||
- Deprecating `success`/`error` in favor of `then`/`catch`
|
||||
|
||||
### 0.3.1 (Sep 16, 2014)
|
||||
|
||||
- Fixing missing post body when using node.js ([#3](https://github.com/axios/axios/issues/3))
|
||||
|
||||
### 0.3.0 (Sep 16, 2014)
|
||||
|
||||
- Fixing `success` and `error` to properly receive response data as individual arguments ([#8](https://github.com/axios/axios/issues/8))
|
||||
- Updating `then` and `catch` to receive response data as a single object ([#6](https://github.com/axios/axios/issues/6))
|
||||
- Fixing issue with `all` not working ([#7](https://github.com/axios/axios/issues/7))
|
||||
|
||||
### 0.2.2 (Sep 14, 2014)
|
||||
|
||||
- Fixing bundling with browserify ([#4](https://github.com/axios/axios/issues/4))
|
||||
|
||||
### 0.2.1 (Sep 12, 2014)
|
||||
|
||||
- Fixing build problem causing ridiculous file sizes
|
||||
|
||||
### 0.2.0 (Sep 12, 2014)
|
||||
|
||||
- Adding support for `all` and `spread`
|
||||
- Adding support for node.js ([#1](https://github.com/axios/axios/issues/1))
|
||||
|
||||
### 0.1.0 (Aug 29, 2014)
|
||||
|
||||
- Initial release
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
Copyright (c) 2014-present Matt Zabriskie
|
||||
|
||||
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.
|
||||
+709
@@ -0,0 +1,709 @@
|
||||
# axios
|
||||
|
||||
[](https://www.npmjs.org/package/axios)
|
||||
[](https://travis-ci.org/axios/axios)
|
||||
[](https://coveralls.io/r/mzabriskie/axios)
|
||||
[](https://packagephobia.now.sh/result?p=axios)
|
||||
[](http://npm-stat.com/charts.html?package=axios)
|
||||
[](https://gitter.im/mzabriskie/axios)
|
||||
[](https://www.codetriage.com/axios/axios)
|
||||
|
||||
Promise based HTTP client for the browser and node.js
|
||||
|
||||
## Features
|
||||
|
||||
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser
|
||||
- Make [http](http://nodejs.org/api/http.html) requests from node.js
|
||||
- Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
|
||||
- Intercept request and response
|
||||
- Transform request and response data
|
||||
- Cancel requests
|
||||
- Automatic transforms for JSON data
|
||||
- Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
|
||||
|
||||
## Browser Support
|
||||
|
||||
 |  |  |  |  |  |
|
||||
--- | --- | --- | --- | --- | --- |
|
||||
Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |
|
||||
|
||||
[](https://saucelabs.com/u/axios)
|
||||
|
||||
## Installing
|
||||
|
||||
Using npm:
|
||||
|
||||
```bash
|
||||
$ npm install axios
|
||||
```
|
||||
|
||||
Using bower:
|
||||
|
||||
```bash
|
||||
$ bower install axios
|
||||
```
|
||||
|
||||
Using yarn:
|
||||
|
||||
```bash
|
||||
$ yarn add axios
|
||||
```
|
||||
|
||||
Using cdn:
|
||||
|
||||
```html
|
||||
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
### note: CommonJS usage
|
||||
In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach:
|
||||
|
||||
```js
|
||||
const axios = require('axios').default;
|
||||
|
||||
// axios.<method> will now provide autocomplete and parameter typings
|
||||
```
|
||||
|
||||
Performing a `GET` request
|
||||
|
||||
```js
|
||||
const axios = require('axios');
|
||||
|
||||
// Make a request for a user with a given ID
|
||||
axios.get('/user?ID=12345')
|
||||
.then(function (response) {
|
||||
// handle success
|
||||
console.log(response);
|
||||
})
|
||||
.catch(function (error) {
|
||||
// handle error
|
||||
console.log(error);
|
||||
})
|
||||
.finally(function () {
|
||||
// always executed
|
||||
});
|
||||
|
||||
// Optionally the request above could also be done as
|
||||
axios.get('/user', {
|
||||
params: {
|
||||
ID: 12345
|
||||
}
|
||||
})
|
||||
.then(function (response) {
|
||||
console.log(response);
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log(error);
|
||||
})
|
||||
.finally(function () {
|
||||
// always executed
|
||||
});
|
||||
|
||||
// Want to use async/await? Add the `async` keyword to your outer function/method.
|
||||
async function getUser() {
|
||||
try {
|
||||
const response = await axios.get('/user?ID=12345');
|
||||
console.log(response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet
|
||||
> Explorer and older browsers, so use with caution.
|
||||
|
||||
Performing a `POST` request
|
||||
|
||||
```js
|
||||
axios.post('/user', {
|
||||
firstName: 'Fred',
|
||||
lastName: 'Flintstone'
|
||||
})
|
||||
.then(function (response) {
|
||||
console.log(response);
|
||||
})
|
||||
.catch(function (error) {
|
||||
console.log(error);
|
||||
});
|
||||
```
|
||||
|
||||
Performing multiple concurrent requests
|
||||
|
||||
```js
|
||||
function getUserAccount() {
|
||||
return axios.get('/user/12345');
|
||||
}
|
||||
|
||||
function getUserPermissions() {
|
||||
return axios.get('/user/12345/permissions');
|
||||
}
|
||||
|
||||
axios.all([getUserAccount(), getUserPermissions()])
|
||||
.then(axios.spread(function (acct, perms) {
|
||||
// Both requests are now complete
|
||||
}));
|
||||
```
|
||||
|
||||
## axios API
|
||||
|
||||
Requests can be made by passing the relevant config to `axios`.
|
||||
|
||||
##### axios(config)
|
||||
|
||||
```js
|
||||
// Send a POST request
|
||||
axios({
|
||||
method: 'post',
|
||||
url: '/user/12345',
|
||||
data: {
|
||||
firstName: 'Fred',
|
||||
lastName: 'Flintstone'
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
// GET request for remote image
|
||||
axios({
|
||||
method: 'get',
|
||||
url: 'http://bit.ly/2mTM3nY',
|
||||
responseType: 'stream'
|
||||
})
|
||||
.then(function (response) {
|
||||
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
|
||||
});
|
||||
```
|
||||
|
||||
##### axios(url[, config])
|
||||
|
||||
```js
|
||||
// Send a GET request (default method)
|
||||
axios('/user/12345');
|
||||
```
|
||||
|
||||
### Request method aliases
|
||||
|
||||
For convenience aliases have been provided for all supported request methods.
|
||||
|
||||
##### axios.request(config)
|
||||
##### axios.get(url[, config])
|
||||
##### axios.delete(url[, config])
|
||||
##### axios.head(url[, config])
|
||||
##### axios.options(url[, config])
|
||||
##### axios.post(url[, data[, config]])
|
||||
##### axios.put(url[, data[, config]])
|
||||
##### axios.patch(url[, data[, config]])
|
||||
|
||||
###### NOTE
|
||||
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
|
||||
|
||||
### Concurrency
|
||||
|
||||
Helper functions for dealing with concurrent requests.
|
||||
|
||||
##### axios.all(iterable)
|
||||
##### axios.spread(callback)
|
||||
|
||||
### Creating an instance
|
||||
|
||||
You can create a new instance of axios with a custom config.
|
||||
|
||||
##### axios.create([config])
|
||||
|
||||
```js
|
||||
const instance = axios.create({
|
||||
baseURL: 'https://some-domain.com/api/',
|
||||
timeout: 1000,
|
||||
headers: {'X-Custom-Header': 'foobar'}
|
||||
});
|
||||
```
|
||||
|
||||
### Instance methods
|
||||
|
||||
The available instance methods are listed below. The specified config will be merged with the instance config.
|
||||
|
||||
##### axios#request(config)
|
||||
##### axios#get(url[, config])
|
||||
##### axios#delete(url[, config])
|
||||
##### axios#head(url[, config])
|
||||
##### axios#options(url[, config])
|
||||
##### axios#post(url[, data[, config]])
|
||||
##### axios#put(url[, data[, config]])
|
||||
##### axios#patch(url[, data[, config]])
|
||||
##### axios#getUri([config])
|
||||
|
||||
## Request Config
|
||||
|
||||
These are the available config options for making requests. Only the `url` is required. Requests will default to `GET` if `method` is not specified.
|
||||
|
||||
```js
|
||||
{
|
||||
// `url` is the server URL that will be used for the request
|
||||
url: '/user',
|
||||
|
||||
// `method` is the request method to be used when making the request
|
||||
method: 'get', // default
|
||||
|
||||
// `baseURL` will be prepended to `url` unless `url` is absolute.
|
||||
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
|
||||
// to methods of that instance.
|
||||
baseURL: 'https://some-domain.com/api/',
|
||||
|
||||
// `transformRequest` allows changes to the request data before it is sent to the server
|
||||
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
|
||||
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
|
||||
// FormData or Stream
|
||||
// You may modify the headers object.
|
||||
transformRequest: [function (data, headers) {
|
||||
// Do whatever you want to transform the data
|
||||
|
||||
return data;
|
||||
}],
|
||||
|
||||
// `transformResponse` allows changes to the response data to be made before
|
||||
// it is passed to then/catch
|
||||
transformResponse: [function (data) {
|
||||
// Do whatever you want to transform the data
|
||||
|
||||
return data;
|
||||
}],
|
||||
|
||||
// `headers` are custom headers to be sent
|
||||
headers: {'X-Requested-With': 'XMLHttpRequest'},
|
||||
|
||||
// `params` are the URL parameters to be sent with the request
|
||||
// Must be a plain object or a URLSearchParams object
|
||||
params: {
|
||||
ID: 12345
|
||||
},
|
||||
|
||||
// `paramsSerializer` is an optional function in charge of serializing `params`
|
||||
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
|
||||
paramsSerializer: function (params) {
|
||||
return Qs.stringify(params, {arrayFormat: 'brackets'})
|
||||
},
|
||||
|
||||
// `data` is the data to be sent as the request body
|
||||
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
|
||||
// When no `transformRequest` is set, must be of one of the following types:
|
||||
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
|
||||
// - Browser only: FormData, File, Blob
|
||||
// - Node only: Stream, Buffer
|
||||
data: {
|
||||
firstName: 'Fred'
|
||||
},
|
||||
|
||||
// syntax alternative to send data into the body
|
||||
// method post
|
||||
// only the value is sent, not the key
|
||||
data: 'Country=Brasil&City=Belo Horizonte',
|
||||
|
||||
// `timeout` specifies the number of milliseconds before the request times out.
|
||||
// If the request takes longer than `timeout`, the request will be aborted.
|
||||
timeout: 1000, // default is `0` (no timeout)
|
||||
|
||||
// `withCredentials` indicates whether or not cross-site Access-Control requests
|
||||
// should be made using credentials
|
||||
withCredentials: false, // default
|
||||
|
||||
// `adapter` allows custom handling of requests which makes testing easier.
|
||||
// Return a promise and supply a valid response (see lib/adapters/README.md).
|
||||
adapter: function (config) {
|
||||
/* ... */
|
||||
},
|
||||
|
||||
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
|
||||
// This will set an `Authorization` header, overwriting any existing
|
||||
// `Authorization` custom headers you have set using `headers`.
|
||||
// Please note that only HTTP Basic auth is configurable through this parameter.
|
||||
// For Bearer tokens and such, use `Authorization` custom headers instead.
|
||||
auth: {
|
||||
username: 'janedoe',
|
||||
password: 's00pers3cret'
|
||||
},
|
||||
|
||||
// `responseType` indicates the type of data that the server will respond with
|
||||
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
|
||||
// browser only: 'blob'
|
||||
responseType: 'json', // default
|
||||
|
||||
// `responseEncoding` indicates encoding to use for decoding responses
|
||||
// Note: Ignored for `responseType` of 'stream' or client-side requests
|
||||
responseEncoding: 'utf8', // default
|
||||
|
||||
// `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
|
||||
xsrfCookieName: 'XSRF-TOKEN', // default
|
||||
|
||||
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
|
||||
xsrfHeaderName: 'X-XSRF-TOKEN', // default
|
||||
|
||||
// `onUploadProgress` allows handling of progress events for uploads
|
||||
onUploadProgress: function (progressEvent) {
|
||||
// Do whatever you want with the native progress event
|
||||
},
|
||||
|
||||
// `onDownloadProgress` allows handling of progress events for downloads
|
||||
onDownloadProgress: function (progressEvent) {
|
||||
// Do whatever you want with the native progress event
|
||||
},
|
||||
|
||||
// `maxContentLength` defines the max size of the http response content in bytes allowed
|
||||
maxContentLength: 2000,
|
||||
|
||||
// `validateStatus` defines whether to resolve or reject the promise for a given
|
||||
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
|
||||
// or `undefined`), the promise will be resolved; otherwise, the promise will be
|
||||
// rejected.
|
||||
validateStatus: function (status) {
|
||||
return status >= 200 && status < 300; // default
|
||||
},
|
||||
|
||||
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
|
||||
// If set to 0, no redirects will be followed.
|
||||
maxRedirects: 5, // default
|
||||
|
||||
// `socketPath` defines a UNIX Socket to be used in node.js.
|
||||
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
|
||||
// Only either `socketPath` or `proxy` can be specified.
|
||||
// If both are specified, `socketPath` is used.
|
||||
socketPath: null, // default
|
||||
|
||||
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
|
||||
// and https requests, respectively, in node.js. This allows options to be added like
|
||||
// `keepAlive` that are not enabled by default.
|
||||
httpAgent: new http.Agent({ keepAlive: true }),
|
||||
httpsAgent: new https.Agent({ keepAlive: true }),
|
||||
|
||||
// 'proxy' defines the hostname and port of the proxy server.
|
||||
// You can also define your proxy using the conventional `http_proxy` and
|
||||
// `https_proxy` environment variables. If you are using environment variables
|
||||
// for your proxy configuration, you can also define a `no_proxy` environment
|
||||
// variable as a comma-separated list of domains that should not be proxied.
|
||||
// Use `false` to disable proxies, ignoring environment variables.
|
||||
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
|
||||
// supplies credentials.
|
||||
// This will set an `Proxy-Authorization` header, overwriting any existing
|
||||
// `Proxy-Authorization` custom headers you have set using `headers`.
|
||||
proxy: {
|
||||
host: '127.0.0.1',
|
||||
port: 9000,
|
||||
auth: {
|
||||
username: 'mikeymike',
|
||||
password: 'rapunz3l'
|
||||
}
|
||||
},
|
||||
|
||||
// `cancelToken` specifies a cancel token that can be used to cancel the request
|
||||
// (see Cancellation section below for details)
|
||||
cancelToken: new CancelToken(function (cancel) {
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## Response Schema
|
||||
|
||||
The response for a request contains the following information.
|
||||
|
||||
```js
|
||||
{
|
||||
// `data` is the response that was provided by the server
|
||||
data: {},
|
||||
|
||||
// `status` is the HTTP status code from the server response
|
||||
status: 200,
|
||||
|
||||
// `statusText` is the HTTP status message from the server response
|
||||
statusText: 'OK',
|
||||
|
||||
// `headers` the headers that the server responded with
|
||||
// All header names are lower cased
|
||||
headers: {},
|
||||
|
||||
// `config` is the config that was provided to `axios` for the request
|
||||
config: {},
|
||||
|
||||
// `request` is the request that generated this response
|
||||
// It is the last ClientRequest instance in node.js (in redirects)
|
||||
// and an XMLHttpRequest instance in the browser
|
||||
request: {}
|
||||
}
|
||||
```
|
||||
|
||||
When using `then`, you will receive the response as follows:
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.then(function (response) {
|
||||
console.log(response.data);
|
||||
console.log(response.status);
|
||||
console.log(response.statusText);
|
||||
console.log(response.headers);
|
||||
console.log(response.config);
|
||||
});
|
||||
```
|
||||
|
||||
When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as second parameter of `then`, the response will be available through the `error` object as explained in the [Handling Errors](#handling-errors) section.
|
||||
|
||||
## Config Defaults
|
||||
|
||||
You can specify config defaults that will be applied to every request.
|
||||
|
||||
### Global axios defaults
|
||||
|
||||
```js
|
||||
axios.defaults.baseURL = 'https://api.example.com';
|
||||
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
||||
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
|
||||
```
|
||||
|
||||
### Custom instance defaults
|
||||
|
||||
```js
|
||||
// Set config defaults when creating the instance
|
||||
const instance = axios.create({
|
||||
baseURL: 'https://api.example.com'
|
||||
});
|
||||
|
||||
// Alter defaults after instance has been created
|
||||
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
|
||||
```
|
||||
|
||||
### Config order of precedence
|
||||
|
||||
Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example.
|
||||
|
||||
```js
|
||||
// Create an instance using the config defaults provided by the library
|
||||
// At this point the timeout config value is `0` as is the default for the library
|
||||
const instance = axios.create();
|
||||
|
||||
// Override timeout default for the library
|
||||
// Now all requests using this instance will wait 2.5 seconds before timing out
|
||||
instance.defaults.timeout = 2500;
|
||||
|
||||
// Override timeout for this request as it's known to take a long time
|
||||
instance.get('/longRequest', {
|
||||
timeout: 5000
|
||||
});
|
||||
```
|
||||
|
||||
## Interceptors
|
||||
|
||||
You can intercept requests or responses before they are handled by `then` or `catch`.
|
||||
|
||||
```js
|
||||
// Add a request interceptor
|
||||
axios.interceptors.request.use(function (config) {
|
||||
// Do something before request is sent
|
||||
return config;
|
||||
}, function (error) {
|
||||
// Do something with request error
|
||||
return Promise.reject(error);
|
||||
});
|
||||
|
||||
// Add a response interceptor
|
||||
axios.interceptors.response.use(function (response) {
|
||||
// Any status code that lie within the range of 2xx cause this function to trigger
|
||||
// Do something with response data
|
||||
return response;
|
||||
}, function (error) {
|
||||
// Any status codes that falls outside the range of 2xx cause this function to trigger
|
||||
// Do something with response error
|
||||
return Promise.reject(error);
|
||||
});
|
||||
```
|
||||
|
||||
If you need to remove an interceptor later you can.
|
||||
|
||||
```js
|
||||
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
|
||||
axios.interceptors.request.eject(myInterceptor);
|
||||
```
|
||||
|
||||
You can add interceptors to a custom instance of axios.
|
||||
|
||||
```js
|
||||
const instance = axios.create();
|
||||
instance.interceptors.request.use(function () {/*...*/});
|
||||
```
|
||||
|
||||
## Handling Errors
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.catch(function (error) {
|
||||
if (error.response) {
|
||||
// The request was made and the server responded with a status code
|
||||
// that falls out of the range of 2xx
|
||||
console.log(error.response.data);
|
||||
console.log(error.response.status);
|
||||
console.log(error.response.headers);
|
||||
} else if (error.request) {
|
||||
// The request was made but no response was received
|
||||
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
|
||||
// http.ClientRequest in node.js
|
||||
console.log(error.request);
|
||||
} else {
|
||||
// Something happened in setting up the request that triggered an Error
|
||||
console.log('Error', error.message);
|
||||
}
|
||||
console.log(error.config);
|
||||
});
|
||||
```
|
||||
|
||||
Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error.
|
||||
|
||||
```js
|
||||
axios.get('/user/12345', {
|
||||
validateStatus: function (status) {
|
||||
return status < 500; // Reject only if the status code is greater than or equal to 500
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
Using `toJSON` you get an object with more information about the HTTP error.
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.catch(function (error) {
|
||||
console.log(error.toJSON());
|
||||
});
|
||||
```
|
||||
|
||||
## Cancellation
|
||||
|
||||
You can cancel a request using a *cancel token*.
|
||||
|
||||
> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
|
||||
|
||||
You can create a cancel token using the `CancelToken.source` factory as shown below:
|
||||
|
||||
```js
|
||||
const CancelToken = axios.CancelToken;
|
||||
const source = CancelToken.source();
|
||||
|
||||
axios.get('/user/12345', {
|
||||
cancelToken: source.token
|
||||
}).catch(function (thrown) {
|
||||
if (axios.isCancel(thrown)) {
|
||||
console.log('Request canceled', thrown.message);
|
||||
} else {
|
||||
// handle error
|
||||
}
|
||||
});
|
||||
|
||||
axios.post('/user/12345', {
|
||||
name: 'new name'
|
||||
}, {
|
||||
cancelToken: source.token
|
||||
})
|
||||
|
||||
// cancel the request (the message parameter is optional)
|
||||
source.cancel('Operation canceled by the user.');
|
||||
```
|
||||
|
||||
You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
|
||||
|
||||
```js
|
||||
const CancelToken = axios.CancelToken;
|
||||
let cancel;
|
||||
|
||||
axios.get('/user/12345', {
|
||||
cancelToken: new CancelToken(function executor(c) {
|
||||
// An executor function receives a cancel function as a parameter
|
||||
cancel = c;
|
||||
})
|
||||
});
|
||||
|
||||
// cancel the request
|
||||
cancel();
|
||||
```
|
||||
|
||||
> Note: you can cancel several requests with the same cancel token.
|
||||
|
||||
## Using application/x-www-form-urlencoded format
|
||||
|
||||
By default, axios serializes JavaScript objects to `JSON`. To send data in the `application/x-www-form-urlencoded` format instead, you can use one of the following options.
|
||||
|
||||
### Browser
|
||||
|
||||
In a browser, you can use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API as follows:
|
||||
|
||||
```js
|
||||
const params = new URLSearchParams();
|
||||
params.append('param1', 'value1');
|
||||
params.append('param2', 'value2');
|
||||
axios.post('/foo', params);
|
||||
```
|
||||
|
||||
> Note that `URLSearchParams` is not supported by all browsers (see [caniuse.com](http://www.caniuse.com/#feat=urlsearchparams)), but there is a [polyfill](https://github.com/WebReflection/url-search-params) available (make sure to polyfill the global environment).
|
||||
|
||||
Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
|
||||
|
||||
```js
|
||||
const qs = require('qs');
|
||||
axios.post('/foo', qs.stringify({ 'bar': 123 }));
|
||||
```
|
||||
|
||||
Or in another way (ES6),
|
||||
|
||||
```js
|
||||
import qs from 'qs';
|
||||
const data = { 'bar': 123 };
|
||||
const options = {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
data: qs.stringify(data),
|
||||
url,
|
||||
};
|
||||
axios(options);
|
||||
```
|
||||
|
||||
### Node.js
|
||||
|
||||
In node.js, you can use the [`querystring`](https://nodejs.org/api/querystring.html) module as follows:
|
||||
|
||||
```js
|
||||
const querystring = require('querystring');
|
||||
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));
|
||||
```
|
||||
|
||||
You can also use the [`qs`](https://github.com/ljharb/qs) library.
|
||||
|
||||
###### NOTE
|
||||
The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has known issues with that use case (https://github.com/nodejs/node-v0.x-archive/issues/1665).
|
||||
|
||||
## Semver
|
||||
|
||||
Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes.
|
||||
|
||||
## Promises
|
||||
|
||||
axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises).
|
||||
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
|
||||
|
||||
## TypeScript
|
||||
axios includes [TypeScript](http://typescriptlang.org) definitions.
|
||||
```typescript
|
||||
import axios from 'axios';
|
||||
axios.get('/user?ID=12345');
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
* [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md)
|
||||
* [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md)
|
||||
* [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md)
|
||||
* [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md)
|
||||
* [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md)
|
||||
|
||||
## Credits
|
||||
|
||||
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular.
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
# Upgrade Guide
|
||||
|
||||
### 0.15.x -> 0.16.0
|
||||
|
||||
#### `Promise` Type Declarations
|
||||
|
||||
The `Promise` type declarations have been removed from the axios typings in favor of the built-in type declarations. If you use axios in a TypeScript project that targets `ES5`, please make sure to include the `es2015.promise` lib. Please see [this post](https://blog.mariusschulz.com/2016/11/25/typescript-2-0-built-in-type-declarations) for details.
|
||||
|
||||
### 0.13.x -> 0.14.0
|
||||
|
||||
#### TypeScript Definitions
|
||||
|
||||
The axios TypeScript definitions have been updated to match the axios API and use the ES2015 module syntax.
|
||||
|
||||
Please use the following `import` statement to import axios in TypeScript:
|
||||
|
||||
```typescript
|
||||
import axios from 'axios';
|
||||
|
||||
axios.get('/foo')
|
||||
.then(response => console.log(response))
|
||||
.catch(error => console.log(error));
|
||||
```
|
||||
|
||||
#### `agent` Config Option
|
||||
|
||||
The `agent` config option has been replaced with two new options: `httpAgent` and `httpsAgent`. Please use them instead.
|
||||
|
||||
```js
|
||||
{
|
||||
// Define a custom agent for HTTP
|
||||
httpAgent: new http.Agent({ keepAlive: true }),
|
||||
// Define a custom agent for HTTPS
|
||||
httpsAgent: new https.Agent({ keepAlive: true })
|
||||
}
|
||||
```
|
||||
|
||||
#### `progress` Config Option
|
||||
|
||||
The `progress` config option has been replaced with the `onUploadProgress` and `onDownloadProgress` options.
|
||||
|
||||
```js
|
||||
{
|
||||
// Define a handler for upload progress events
|
||||
onUploadProgress: function (progressEvent) {
|
||||
// ...
|
||||
},
|
||||
|
||||
// Define a handler for download progress events
|
||||
onDownloadProgress: function (progressEvent) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 0.12.x -> 0.13.0
|
||||
|
||||
The `0.13.0` release contains several changes to custom adapters and error handling.
|
||||
|
||||
#### Error Handling
|
||||
|
||||
Previous to this release an error could either be a server response with bad status code or an actual `Error`. With this release Promise will always reject with an `Error`. In the case that a response was received, the `Error` will also include the response.
|
||||
|
||||
```js
|
||||
axios.get('/user/12345')
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
console.log(error.code); // Not always specified
|
||||
console.log(error.config); // The config that was used to make the request
|
||||
console.log(error.response); // Only available if response was received from the server
|
||||
});
|
||||
```
|
||||
|
||||
#### Request Adapters
|
||||
|
||||
This release changes a few things about how request adapters work. Please take note if you are using your own custom adapter.
|
||||
|
||||
1. Response transformer is now called outside of adapter.
|
||||
2. Request adapter returns a `Promise`.
|
||||
|
||||
This means that you no longer need to invoke `transformData` on response data. You will also no longer receive `resolve` and `reject` as arguments in your adapter.
|
||||
|
||||
Previous code:
|
||||
|
||||
```js
|
||||
function myAdapter(resolve, reject, config) {
|
||||
var response = {
|
||||
data: transformData(
|
||||
responseData,
|
||||
responseHeaders,
|
||||
config.transformResponse
|
||||
),
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders
|
||||
};
|
||||
settle(resolve, reject, response);
|
||||
}
|
||||
```
|
||||
|
||||
New code:
|
||||
|
||||
```js
|
||||
function myAdapter(config) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
var response = {
|
||||
data: responseData,
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders
|
||||
};
|
||||
settle(resolve, reject, response);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
See the related commits for more details:
|
||||
- [Response transformers](https://github.com/axios/axios/commit/10eb23865101f9347570552c04e9d6211376e25e)
|
||||
- [Request adapter Promise](https://github.com/axios/axios/commit/157efd5615890301824e3121cc6c9d2f9b21f94a)
|
||||
|
||||
### 0.5.x -> 0.6.0
|
||||
|
||||
The `0.6.0` release contains mostly bug fixes, but there are a couple things to be aware of when upgrading.
|
||||
|
||||
#### ES6 Promise Polyfill
|
||||
|
||||
Up until the `0.6.0` release ES6 `Promise` was being polyfilled using [es6-promise](https://github.com/jakearchibald/es6-promise). With this release, the polyfill has been removed, and you will need to supply it yourself if your environment needs it.
|
||||
|
||||
```js
|
||||
require('es6-promise').polyfill();
|
||||
var axios = require('axios');
|
||||
```
|
||||
|
||||
This will polyfill the global environment, and only needs to be done once.
|
||||
|
||||
#### `axios.success`/`axios.error`
|
||||
|
||||
The `success`, and `error` aliases were deprectated in [0.4.0](https://github.com/axios/axios/blob/master/CHANGELOG.md#040-oct-03-2014). As of this release they have been removed entirely. Instead please use `axios.then`, and `axios.catch` respectively.
|
||||
|
||||
```js
|
||||
axios.get('some/url')
|
||||
.then(function (res) {
|
||||
/* ... */
|
||||
})
|
||||
.catch(function (err) {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
#### UMD
|
||||
|
||||
Previous versions of axios shipped with an AMD, CommonJS, and Global build. This has all been rolled into a single UMD build.
|
||||
|
||||
```js
|
||||
// AMD
|
||||
require(['bower_components/axios/dist/axios'], function (axios) {
|
||||
/* ... */
|
||||
});
|
||||
|
||||
// CommonJS
|
||||
var axios = require('axios/dist/axios');
|
||||
```
|
||||
+1715
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+3
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+157
@@ -0,0 +1,157 @@
|
||||
export interface AxiosTransformer {
|
||||
(data: any, headers?: any): any;
|
||||
}
|
||||
|
||||
export interface AxiosAdapter {
|
||||
(config: AxiosRequestConfig): AxiosPromise<any>;
|
||||
}
|
||||
|
||||
export interface AxiosBasicCredentials {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AxiosProxyConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
auth?: {
|
||||
username: string;
|
||||
password:string;
|
||||
};
|
||||
protocol?: string;
|
||||
}
|
||||
|
||||
export type Method =
|
||||
| 'get' | 'GET'
|
||||
| 'delete' | 'DELETE'
|
||||
| 'head' | 'HEAD'
|
||||
| 'options' | 'OPTIONS'
|
||||
| 'post' | 'POST'
|
||||
| 'put' | 'PUT'
|
||||
| 'patch' | 'PATCH'
|
||||
| 'link' | 'LINK'
|
||||
| 'unlink' | 'UNLINK'
|
||||
|
||||
export type ResponseType =
|
||||
| 'arraybuffer'
|
||||
| 'blob'
|
||||
| 'document'
|
||||
| 'json'
|
||||
| 'text'
|
||||
| 'stream'
|
||||
|
||||
export interface AxiosRequestConfig {
|
||||
url?: string;
|
||||
method?: Method;
|
||||
baseURL?: string;
|
||||
transformRequest?: AxiosTransformer | AxiosTransformer[];
|
||||
transformResponse?: AxiosTransformer | AxiosTransformer[];
|
||||
headers?: any;
|
||||
params?: any;
|
||||
paramsSerializer?: (params: any) => string;
|
||||
data?: any;
|
||||
timeout?: number;
|
||||
timeoutErrorMessage?: string;
|
||||
withCredentials?: boolean;
|
||||
adapter?: AxiosAdapter;
|
||||
auth?: AxiosBasicCredentials;
|
||||
responseType?: ResponseType;
|
||||
xsrfCookieName?: string;
|
||||
xsrfHeaderName?: string;
|
||||
onUploadProgress?: (progressEvent: any) => void;
|
||||
onDownloadProgress?: (progressEvent: any) => void;
|
||||
maxContentLength?: number;
|
||||
validateStatus?: (status: number) => boolean;
|
||||
maxRedirects?: number;
|
||||
socketPath?: string | null;
|
||||
httpAgent?: any;
|
||||
httpsAgent?: any;
|
||||
proxy?: AxiosProxyConfig | false;
|
||||
cancelToken?: CancelToken;
|
||||
}
|
||||
|
||||
export interface AxiosResponse<T = any> {
|
||||
data: T;
|
||||
status: number;
|
||||
statusText: string;
|
||||
headers: any;
|
||||
config: AxiosRequestConfig;
|
||||
request?: any;
|
||||
}
|
||||
|
||||
export interface AxiosError<T = any> extends Error {
|
||||
config: AxiosRequestConfig;
|
||||
code?: string;
|
||||
request?: any;
|
||||
response?: AxiosResponse<T>;
|
||||
isAxiosError: boolean;
|
||||
toJSON: () => object;
|
||||
}
|
||||
|
||||
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
|
||||
}
|
||||
|
||||
export interface CancelStatic {
|
||||
new (message?: string): Cancel;
|
||||
}
|
||||
|
||||
export interface Cancel {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface Canceler {
|
||||
(message?: string): void;
|
||||
}
|
||||
|
||||
export interface CancelTokenStatic {
|
||||
new (executor: (cancel: Canceler) => void): CancelToken;
|
||||
source(): CancelTokenSource;
|
||||
}
|
||||
|
||||
export interface CancelToken {
|
||||
promise: Promise<Cancel>;
|
||||
reason?: Cancel;
|
||||
throwIfRequested(): void;
|
||||
}
|
||||
|
||||
export interface CancelTokenSource {
|
||||
token: CancelToken;
|
||||
cancel: Canceler;
|
||||
}
|
||||
|
||||
export interface AxiosInterceptorManager<V> {
|
||||
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
|
||||
eject(id: number): void;
|
||||
}
|
||||
|
||||
export interface AxiosInstance {
|
||||
(config: AxiosRequestConfig): AxiosPromise;
|
||||
(url: string, config?: AxiosRequestConfig): AxiosPromise;
|
||||
defaults: AxiosRequestConfig;
|
||||
interceptors: {
|
||||
request: AxiosInterceptorManager<AxiosRequestConfig>;
|
||||
response: AxiosInterceptorManager<AxiosResponse>;
|
||||
};
|
||||
getUri(config?: AxiosRequestConfig): string;
|
||||
request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>;
|
||||
get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
delete<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
head<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
options<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;
|
||||
post<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||
put<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||
patch<T = any, R = AxiosResponse<T>>(url: string, data?: any, config?: AxiosRequestConfig): Promise<R>;
|
||||
}
|
||||
|
||||
export interface AxiosStatic extends AxiosInstance {
|
||||
create(config?: AxiosRequestConfig): AxiosInstance;
|
||||
Cancel: CancelStatic;
|
||||
CancelToken: CancelTokenStatic;
|
||||
isCancel(value: any): boolean;
|
||||
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
|
||||
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
|
||||
}
|
||||
|
||||
declare const Axios: AxiosStatic;
|
||||
|
||||
export default Axios;
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require('./lib/axios');
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# axios // adapters
|
||||
|
||||
The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
|
||||
|
||||
## Example
|
||||
|
||||
```js
|
||||
var settle = require('./../core/settle');
|
||||
|
||||
module.exports = function myAdapter(config) {
|
||||
// At this point:
|
||||
// - config has been merged with defaults
|
||||
// - request transformers have already run
|
||||
// - request interceptors have already run
|
||||
|
||||
// Make the request using config provided
|
||||
// Upon response settle the Promise
|
||||
|
||||
return new Promise(function(resolve, reject) {
|
||||
|
||||
var response = {
|
||||
data: responseData,
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders,
|
||||
config: config,
|
||||
request: request
|
||||
};
|
||||
|
||||
settle(resolve, reject, response);
|
||||
|
||||
// From here:
|
||||
// - response transformers will run
|
||||
// - response interceptors will run
|
||||
});
|
||||
}
|
||||
```
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var settle = require('./../core/settle');
|
||||
var buildFullPath = require('../core/buildFullPath');
|
||||
var buildURL = require('./../helpers/buildURL');
|
||||
var http = require('http');
|
||||
var https = require('https');
|
||||
var httpFollow = require('follow-redirects').http;
|
||||
var httpsFollow = require('follow-redirects').https;
|
||||
var url = require('url');
|
||||
var zlib = require('zlib');
|
||||
var pkg = require('./../../package.json');
|
||||
var createError = require('../core/createError');
|
||||
var enhanceError = require('../core/enhanceError');
|
||||
|
||||
var isHttps = /https:?/;
|
||||
|
||||
/*eslint consistent-return:0*/
|
||||
module.exports = function httpAdapter(config) {
|
||||
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
|
||||
var resolve = function resolve(value) {
|
||||
resolvePromise(value);
|
||||
};
|
||||
var reject = function reject(value) {
|
||||
rejectPromise(value);
|
||||
};
|
||||
var data = config.data;
|
||||
var headers = config.headers;
|
||||
|
||||
// Set User-Agent (required by some servers)
|
||||
// Only set header if it hasn't been set in config
|
||||
// See https://github.com/axios/axios/issues/69
|
||||
if (!headers['User-Agent'] && !headers['user-agent']) {
|
||||
headers['User-Agent'] = 'axios/' + pkg.version;
|
||||
}
|
||||
|
||||
if (data && !utils.isStream(data)) {
|
||||
if (Buffer.isBuffer(data)) {
|
||||
// Nothing to do...
|
||||
} else if (utils.isArrayBuffer(data)) {
|
||||
data = Buffer.from(new Uint8Array(data));
|
||||
} else if (utils.isString(data)) {
|
||||
data = Buffer.from(data, 'utf-8');
|
||||
} else {
|
||||
return reject(createError(
|
||||
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
|
||||
config
|
||||
));
|
||||
}
|
||||
|
||||
// Add Content-Length header if data exists
|
||||
headers['Content-Length'] = data.length;
|
||||
}
|
||||
|
||||
// HTTP basic authentication
|
||||
var auth = undefined;
|
||||
if (config.auth) {
|
||||
var username = config.auth.username || '';
|
||||
var password = config.auth.password || '';
|
||||
auth = username + ':' + password;
|
||||
}
|
||||
|
||||
// Parse url
|
||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||
var parsed = url.parse(fullPath);
|
||||
var protocol = parsed.protocol || 'http:';
|
||||
|
||||
if (!auth && parsed.auth) {
|
||||
var urlAuth = parsed.auth.split(':');
|
||||
var urlUsername = urlAuth[0] || '';
|
||||
var urlPassword = urlAuth[1] || '';
|
||||
auth = urlUsername + ':' + urlPassword;
|
||||
}
|
||||
|
||||
if (auth) {
|
||||
delete headers.Authorization;
|
||||
}
|
||||
|
||||
var isHttpsRequest = isHttps.test(protocol);
|
||||
var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
|
||||
|
||||
var options = {
|
||||
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
|
||||
method: config.method.toUpperCase(),
|
||||
headers: headers,
|
||||
agent: agent,
|
||||
agents: { http: config.httpAgent, https: config.httpsAgent },
|
||||
auth: auth
|
||||
};
|
||||
|
||||
if (config.socketPath) {
|
||||
options.socketPath = config.socketPath;
|
||||
} else {
|
||||
options.hostname = parsed.hostname;
|
||||
options.port = parsed.port;
|
||||
}
|
||||
|
||||
var proxy = config.proxy;
|
||||
if (!proxy && proxy !== false) {
|
||||
var proxyEnv = protocol.slice(0, -1) + '_proxy';
|
||||
var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
|
||||
if (proxyUrl) {
|
||||
var parsedProxyUrl = url.parse(proxyUrl);
|
||||
var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;
|
||||
var shouldProxy = true;
|
||||
|
||||
if (noProxyEnv) {
|
||||
var noProxy = noProxyEnv.split(',').map(function trim(s) {
|
||||
return s.trim();
|
||||
});
|
||||
|
||||
shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {
|
||||
if (!proxyElement) {
|
||||
return false;
|
||||
}
|
||||
if (proxyElement === '*') {
|
||||
return true;
|
||||
}
|
||||
if (proxyElement[0] === '.' &&
|
||||
parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return parsed.hostname === proxyElement;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
if (shouldProxy) {
|
||||
proxy = {
|
||||
host: parsedProxyUrl.hostname,
|
||||
port: parsedProxyUrl.port
|
||||
};
|
||||
|
||||
if (parsedProxyUrl.auth) {
|
||||
var proxyUrlAuth = parsedProxyUrl.auth.split(':');
|
||||
proxy.auth = {
|
||||
username: proxyUrlAuth[0],
|
||||
password: proxyUrlAuth[1]
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (proxy) {
|
||||
options.hostname = proxy.host;
|
||||
options.host = proxy.host;
|
||||
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
|
||||
options.port = proxy.port;
|
||||
options.path = protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path;
|
||||
|
||||
// Basic proxy authorization
|
||||
if (proxy.auth) {
|
||||
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
|
||||
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
|
||||
}
|
||||
}
|
||||
|
||||
var transport;
|
||||
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
|
||||
if (config.transport) {
|
||||
transport = config.transport;
|
||||
} else if (config.maxRedirects === 0) {
|
||||
transport = isHttpsProxy ? https : http;
|
||||
} else {
|
||||
if (config.maxRedirects) {
|
||||
options.maxRedirects = config.maxRedirects;
|
||||
}
|
||||
transport = isHttpsProxy ? httpsFollow : httpFollow;
|
||||
}
|
||||
|
||||
if (config.maxContentLength && config.maxContentLength > -1) {
|
||||
options.maxBodyLength = config.maxContentLength;
|
||||
}
|
||||
|
||||
// Create the request
|
||||
var req = transport.request(options, function handleResponse(res) {
|
||||
if (req.aborted) return;
|
||||
|
||||
// uncompress the response body transparently if required
|
||||
var stream = res;
|
||||
switch (res.headers['content-encoding']) {
|
||||
/*eslint default-case:0*/
|
||||
case 'gzip':
|
||||
case 'compress':
|
||||
case 'deflate':
|
||||
// add the unzipper to the body stream processing pipeline
|
||||
stream = (res.statusCode === 204) ? stream : stream.pipe(zlib.createUnzip());
|
||||
|
||||
// remove the content-encoding in order to not confuse downstream operations
|
||||
delete res.headers['content-encoding'];
|
||||
break;
|
||||
}
|
||||
|
||||
// return the last request in case of redirects
|
||||
var lastRequest = res.req || req;
|
||||
|
||||
var response = {
|
||||
status: res.statusCode,
|
||||
statusText: res.statusMessage,
|
||||
headers: res.headers,
|
||||
config: config,
|
||||
request: lastRequest
|
||||
};
|
||||
|
||||
if (config.responseType === 'stream') {
|
||||
response.data = stream;
|
||||
settle(resolve, reject, response);
|
||||
} else {
|
||||
var responseBuffer = [];
|
||||
stream.on('data', function handleStreamData(chunk) {
|
||||
responseBuffer.push(chunk);
|
||||
|
||||
// make sure the content length is not over the maxContentLength if specified
|
||||
if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {
|
||||
stream.destroy();
|
||||
reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
|
||||
config, null, lastRequest));
|
||||
}
|
||||
});
|
||||
|
||||
stream.on('error', function handleStreamError(err) {
|
||||
if (req.aborted) return;
|
||||
reject(enhanceError(err, config, null, lastRequest));
|
||||
});
|
||||
|
||||
stream.on('end', function handleStreamEnd() {
|
||||
var responseData = Buffer.concat(responseBuffer);
|
||||
if (config.responseType !== 'arraybuffer') {
|
||||
responseData = responseData.toString(config.responseEncoding);
|
||||
}
|
||||
|
||||
response.data = responseData;
|
||||
settle(resolve, reject, response);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
req.on('error', function handleRequestError(err) {
|
||||
if (req.aborted) return;
|
||||
reject(enhanceError(err, config, null, req));
|
||||
});
|
||||
|
||||
// Handle request timeout
|
||||
if (config.timeout) {
|
||||
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
|
||||
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
|
||||
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
|
||||
// And then these socket which be hang up will devoring CPU little by little.
|
||||
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
|
||||
req.setTimeout(config.timeout, function handleRequestTimeout() {
|
||||
req.abort();
|
||||
reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req));
|
||||
});
|
||||
}
|
||||
|
||||
if (config.cancelToken) {
|
||||
// Handle cancellation
|
||||
config.cancelToken.promise.then(function onCanceled(cancel) {
|
||||
if (req.aborted) return;
|
||||
|
||||
req.abort();
|
||||
reject(cancel);
|
||||
});
|
||||
}
|
||||
|
||||
// Send the request
|
||||
if (utils.isStream(data)) {
|
||||
data.on('error', function handleStreamError(err) {
|
||||
reject(enhanceError(err, config, null, req));
|
||||
}).pipe(req);
|
||||
} else {
|
||||
req.end(data);
|
||||
}
|
||||
});
|
||||
};
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var settle = require('./../core/settle');
|
||||
var buildURL = require('./../helpers/buildURL');
|
||||
var buildFullPath = require('../core/buildFullPath');
|
||||
var parseHeaders = require('./../helpers/parseHeaders');
|
||||
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
|
||||
var createError = require('../core/createError');
|
||||
|
||||
module.exports = function xhrAdapter(config) {
|
||||
return new Promise(function dispatchXhrRequest(resolve, reject) {
|
||||
var requestData = config.data;
|
||||
var requestHeaders = config.headers;
|
||||
|
||||
if (utils.isFormData(requestData)) {
|
||||
delete requestHeaders['Content-Type']; // Let the browser set it
|
||||
}
|
||||
|
||||
var request = new XMLHttpRequest();
|
||||
|
||||
// HTTP basic authentication
|
||||
if (config.auth) {
|
||||
var username = config.auth.username || '';
|
||||
var password = config.auth.password || '';
|
||||
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
|
||||
}
|
||||
|
||||
var fullPath = buildFullPath(config.baseURL, config.url);
|
||||
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
|
||||
|
||||
// Set the request timeout in MS
|
||||
request.timeout = config.timeout;
|
||||
|
||||
// Listen for ready state
|
||||
request.onreadystatechange = function handleLoad() {
|
||||
if (!request || request.readyState !== 4) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The request errored out and we didn't get a response, this will be
|
||||
// handled by onerror instead
|
||||
// With one exception: request that using file: protocol, most browsers
|
||||
// will return status as 0 even though it's a successful request
|
||||
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Prepare the response
|
||||
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
|
||||
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
|
||||
var response = {
|
||||
data: responseData,
|
||||
status: request.status,
|
||||
statusText: request.statusText,
|
||||
headers: responseHeaders,
|
||||
config: config,
|
||||
request: request
|
||||
};
|
||||
|
||||
settle(resolve, reject, response);
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Handle browser request cancellation (as opposed to a manual cancellation)
|
||||
request.onabort = function handleAbort() {
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
reject(createError('Request aborted', config, 'ECONNABORTED', request));
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Handle low level network errors
|
||||
request.onerror = function handleError() {
|
||||
// Real errors are hidden from us by the browser
|
||||
// onerror should only fire if it's a network error
|
||||
reject(createError('Network Error', config, null, request));
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Handle timeout
|
||||
request.ontimeout = function handleTimeout() {
|
||||
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
|
||||
if (config.timeoutErrorMessage) {
|
||||
timeoutErrorMessage = config.timeoutErrorMessage;
|
||||
}
|
||||
reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
|
||||
request));
|
||||
|
||||
// Clean up request
|
||||
request = null;
|
||||
};
|
||||
|
||||
// Add xsrf header
|
||||
// This is only done if running in a standard browser environment.
|
||||
// Specifically not if we're in a web worker, or react-native.
|
||||
if (utils.isStandardBrowserEnv()) {
|
||||
var cookies = require('./../helpers/cookies');
|
||||
|
||||
// Add xsrf header
|
||||
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
|
||||
cookies.read(config.xsrfCookieName) :
|
||||
undefined;
|
||||
|
||||
if (xsrfValue) {
|
||||
requestHeaders[config.xsrfHeaderName] = xsrfValue;
|
||||
}
|
||||
}
|
||||
|
||||
// Add headers to the request
|
||||
if ('setRequestHeader' in request) {
|
||||
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
|
||||
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
|
||||
// Remove Content-Type if data is undefined
|
||||
delete requestHeaders[key];
|
||||
} else {
|
||||
// Otherwise add header to the request
|
||||
request.setRequestHeader(key, val);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Add withCredentials to request if needed
|
||||
if (!utils.isUndefined(config.withCredentials)) {
|
||||
request.withCredentials = !!config.withCredentials;
|
||||
}
|
||||
|
||||
// Add responseType to request if needed
|
||||
if (config.responseType) {
|
||||
try {
|
||||
request.responseType = config.responseType;
|
||||
} catch (e) {
|
||||
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
|
||||
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
|
||||
if (config.responseType !== 'json') {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle progress if needed
|
||||
if (typeof config.onDownloadProgress === 'function') {
|
||||
request.addEventListener('progress', config.onDownloadProgress);
|
||||
}
|
||||
|
||||
// Not all browsers support upload events
|
||||
if (typeof config.onUploadProgress === 'function' && request.upload) {
|
||||
request.upload.addEventListener('progress', config.onUploadProgress);
|
||||
}
|
||||
|
||||
if (config.cancelToken) {
|
||||
// Handle cancellation
|
||||
config.cancelToken.promise.then(function onCanceled(cancel) {
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
|
||||
request.abort();
|
||||
reject(cancel);
|
||||
// Clean up request
|
||||
request = null;
|
||||
});
|
||||
}
|
||||
|
||||
if (requestData === undefined) {
|
||||
requestData = null;
|
||||
}
|
||||
|
||||
// Send the request
|
||||
request.send(requestData);
|
||||
});
|
||||
};
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./utils');
|
||||
var bind = require('./helpers/bind');
|
||||
var Axios = require('./core/Axios');
|
||||
var mergeConfig = require('./core/mergeConfig');
|
||||
var defaults = require('./defaults');
|
||||
|
||||
/**
|
||||
* Create an instance of Axios
|
||||
*
|
||||
* @param {Object} defaultConfig The default config for the instance
|
||||
* @return {Axios} A new instance of Axios
|
||||
*/
|
||||
function createInstance(defaultConfig) {
|
||||
var context = new Axios(defaultConfig);
|
||||
var instance = bind(Axios.prototype.request, context);
|
||||
|
||||
// Copy axios.prototype to instance
|
||||
utils.extend(instance, Axios.prototype, context);
|
||||
|
||||
// Copy context to instance
|
||||
utils.extend(instance, context);
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
// Create the default instance to be exported
|
||||
var axios = createInstance(defaults);
|
||||
|
||||
// Expose Axios class to allow class inheritance
|
||||
axios.Axios = Axios;
|
||||
|
||||
// Factory for creating new instances
|
||||
axios.create = function create(instanceConfig) {
|
||||
return createInstance(mergeConfig(axios.defaults, instanceConfig));
|
||||
};
|
||||
|
||||
// Expose Cancel & CancelToken
|
||||
axios.Cancel = require('./cancel/Cancel');
|
||||
axios.CancelToken = require('./cancel/CancelToken');
|
||||
axios.isCancel = require('./cancel/isCancel');
|
||||
|
||||
// Expose all/spread
|
||||
axios.all = function all(promises) {
|
||||
return Promise.all(promises);
|
||||
};
|
||||
axios.spread = require('./helpers/spread');
|
||||
|
||||
module.exports = axios;
|
||||
|
||||
// Allow use of default import syntax in TypeScript
|
||||
module.exports.default = axios;
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* A `Cancel` is an object that is thrown when an operation is canceled.
|
||||
*
|
||||
* @class
|
||||
* @param {string=} message The message.
|
||||
*/
|
||||
function Cancel(message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
Cancel.prototype.toString = function toString() {
|
||||
return 'Cancel' + (this.message ? ': ' + this.message : '');
|
||||
};
|
||||
|
||||
Cancel.prototype.__CANCEL__ = true;
|
||||
|
||||
module.exports = Cancel;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
'use strict';
|
||||
|
||||
var Cancel = require('./Cancel');
|
||||
|
||||
/**
|
||||
* A `CancelToken` is an object that can be used to request cancellation of an operation.
|
||||
*
|
||||
* @class
|
||||
* @param {Function} executor The executor function.
|
||||
*/
|
||||
function CancelToken(executor) {
|
||||
if (typeof executor !== 'function') {
|
||||
throw new TypeError('executor must be a function.');
|
||||
}
|
||||
|
||||
var resolvePromise;
|
||||
this.promise = new Promise(function promiseExecutor(resolve) {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
|
||||
var token = this;
|
||||
executor(function cancel(message) {
|
||||
if (token.reason) {
|
||||
// Cancellation has already been requested
|
||||
return;
|
||||
}
|
||||
|
||||
token.reason = new Cancel(message);
|
||||
resolvePromise(token.reason);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws a `Cancel` if cancellation has been requested.
|
||||
*/
|
||||
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
|
||||
if (this.reason) {
|
||||
throw this.reason;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an object that contains a new `CancelToken` and a function that, when called,
|
||||
* cancels the `CancelToken`.
|
||||
*/
|
||||
CancelToken.source = function source() {
|
||||
var cancel;
|
||||
var token = new CancelToken(function executor(c) {
|
||||
cancel = c;
|
||||
});
|
||||
return {
|
||||
token: token,
|
||||
cancel: cancel
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = CancelToken;
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function isCancel(value) {
|
||||
return !!(value && value.__CANCEL__);
|
||||
};
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var buildURL = require('../helpers/buildURL');
|
||||
var InterceptorManager = require('./InterceptorManager');
|
||||
var dispatchRequest = require('./dispatchRequest');
|
||||
var mergeConfig = require('./mergeConfig');
|
||||
|
||||
/**
|
||||
* Create a new instance of Axios
|
||||
*
|
||||
* @param {Object} instanceConfig The default config for the instance
|
||||
*/
|
||||
function Axios(instanceConfig) {
|
||||
this.defaults = instanceConfig;
|
||||
this.interceptors = {
|
||||
request: new InterceptorManager(),
|
||||
response: new InterceptorManager()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a request
|
||||
*
|
||||
* @param {Object} config The config specific for this request (merged with this.defaults)
|
||||
*/
|
||||
Axios.prototype.request = function request(config) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
// Allow for axios('example/url'[, config]) a la fetch API
|
||||
if (typeof config === 'string') {
|
||||
config = arguments[1] || {};
|
||||
config.url = arguments[0];
|
||||
} else {
|
||||
config = config || {};
|
||||
}
|
||||
|
||||
config = mergeConfig(this.defaults, config);
|
||||
|
||||
// Set config.method
|
||||
if (config.method) {
|
||||
config.method = config.method.toLowerCase();
|
||||
} else if (this.defaults.method) {
|
||||
config.method = this.defaults.method.toLowerCase();
|
||||
} else {
|
||||
config.method = 'get';
|
||||
}
|
||||
|
||||
// Hook up interceptors middleware
|
||||
var chain = [dispatchRequest, undefined];
|
||||
var promise = Promise.resolve(config);
|
||||
|
||||
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
|
||||
chain.unshift(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
|
||||
chain.push(interceptor.fulfilled, interceptor.rejected);
|
||||
});
|
||||
|
||||
while (chain.length) {
|
||||
promise = promise.then(chain.shift(), chain.shift());
|
||||
}
|
||||
|
||||
return promise;
|
||||
};
|
||||
|
||||
Axios.prototype.getUri = function getUri(config) {
|
||||
config = mergeConfig(this.defaults, config);
|
||||
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
|
||||
};
|
||||
|
||||
// Provide aliases for supported request methods
|
||||
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
|
||||
/*eslint func-names:0*/
|
||||
Axios.prototype[method] = function(url, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url
|
||||
}));
|
||||
};
|
||||
});
|
||||
|
||||
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||
/*eslint func-names:0*/
|
||||
Axios.prototype[method] = function(url, data, config) {
|
||||
return this.request(utils.merge(config || {}, {
|
||||
method: method,
|
||||
url: url,
|
||||
data: data
|
||||
}));
|
||||
};
|
||||
});
|
||||
|
||||
module.exports = Axios;
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
function InterceptorManager() {
|
||||
this.handlers = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new interceptor to the stack
|
||||
*
|
||||
* @param {Function} fulfilled The function to handle `then` for a `Promise`
|
||||
* @param {Function} rejected The function to handle `reject` for a `Promise`
|
||||
*
|
||||
* @return {Number} An ID used to remove interceptor later
|
||||
*/
|
||||
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
|
||||
this.handlers.push({
|
||||
fulfilled: fulfilled,
|
||||
rejected: rejected
|
||||
});
|
||||
return this.handlers.length - 1;
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove an interceptor from the stack
|
||||
*
|
||||
* @param {Number} id The ID that was returned by `use`
|
||||
*/
|
||||
InterceptorManager.prototype.eject = function eject(id) {
|
||||
if (this.handlers[id]) {
|
||||
this.handlers[id] = null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Iterate over all the registered interceptors
|
||||
*
|
||||
* This method is particularly useful for skipping over any
|
||||
* interceptors that may have become `null` calling `eject`.
|
||||
*
|
||||
* @param {Function} fn The function to call for each interceptor
|
||||
*/
|
||||
InterceptorManager.prototype.forEach = function forEach(fn) {
|
||||
utils.forEach(this.handlers, function forEachHandler(h) {
|
||||
if (h !== null) {
|
||||
fn(h);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = InterceptorManager;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# axios // core
|
||||
|
||||
The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:
|
||||
|
||||
- Dispatching requests
|
||||
- Managing interceptors
|
||||
- Handling config
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
|
||||
var combineURLs = require('../helpers/combineURLs');
|
||||
|
||||
/**
|
||||
* Creates a new URL by combining the baseURL with the requestedURL,
|
||||
* only when the requestedURL is not already an absolute URL.
|
||||
* If the requestURL is absolute, this function returns the requestedURL untouched.
|
||||
*
|
||||
* @param {string} baseURL The base URL
|
||||
* @param {string} requestedURL Absolute or relative URL to combine
|
||||
* @returns {string} The combined full path
|
||||
*/
|
||||
module.exports = function buildFullPath(baseURL, requestedURL) {
|
||||
if (baseURL && !isAbsoluteURL(requestedURL)) {
|
||||
return combineURLs(baseURL, requestedURL);
|
||||
}
|
||||
return requestedURL;
|
||||
};
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
var enhanceError = require('./enhanceError');
|
||||
|
||||
/**
|
||||
* Create an Error with the specified message, config, error code, request and response.
|
||||
*
|
||||
* @param {string} message The error message.
|
||||
* @param {Object} config The config.
|
||||
* @param {string} [code] The error code (for example, 'ECONNABORTED').
|
||||
* @param {Object} [request] The request.
|
||||
* @param {Object} [response] The response.
|
||||
* @returns {Error} The created error.
|
||||
*/
|
||||
module.exports = function createError(message, config, code, request, response) {
|
||||
var error = new Error(message);
|
||||
return enhanceError(error, config, code, request, response);
|
||||
};
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
var transformData = require('./transformData');
|
||||
var isCancel = require('../cancel/isCancel');
|
||||
var defaults = require('../defaults');
|
||||
|
||||
/**
|
||||
* Throws a `Cancel` if cancellation has been requested.
|
||||
*/
|
||||
function throwIfCancellationRequested(config) {
|
||||
if (config.cancelToken) {
|
||||
config.cancelToken.throwIfRequested();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a request to the server using the configured adapter.
|
||||
*
|
||||
* @param {object} config The config that is to be used for the request
|
||||
* @returns {Promise} The Promise to be fulfilled
|
||||
*/
|
||||
module.exports = function dispatchRequest(config) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Ensure headers exist
|
||||
config.headers = config.headers || {};
|
||||
|
||||
// Transform request data
|
||||
config.data = transformData(
|
||||
config.data,
|
||||
config.headers,
|
||||
config.transformRequest
|
||||
);
|
||||
|
||||
// Flatten headers
|
||||
config.headers = utils.merge(
|
||||
config.headers.common || {},
|
||||
config.headers[config.method] || {},
|
||||
config.headers
|
||||
);
|
||||
|
||||
utils.forEach(
|
||||
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
|
||||
function cleanHeaderConfig(method) {
|
||||
delete config.headers[method];
|
||||
}
|
||||
);
|
||||
|
||||
var adapter = config.adapter || defaults.adapter;
|
||||
|
||||
return adapter(config).then(function onAdapterResolution(response) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Transform response data
|
||||
response.data = transformData(
|
||||
response.data,
|
||||
response.headers,
|
||||
config.transformResponse
|
||||
);
|
||||
|
||||
return response;
|
||||
}, function onAdapterRejection(reason) {
|
||||
if (!isCancel(reason)) {
|
||||
throwIfCancellationRequested(config);
|
||||
|
||||
// Transform response data
|
||||
if (reason && reason.response) {
|
||||
reason.response.data = transformData(
|
||||
reason.response.data,
|
||||
reason.response.headers,
|
||||
config.transformResponse
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(reason);
|
||||
});
|
||||
};
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Update an Error with the specified config, error code, and response.
|
||||
*
|
||||
* @param {Error} error The error to update.
|
||||
* @param {Object} config The config.
|
||||
* @param {string} [code] The error code (for example, 'ECONNABORTED').
|
||||
* @param {Object} [request] The request.
|
||||
* @param {Object} [response] The response.
|
||||
* @returns {Error} The error.
|
||||
*/
|
||||
module.exports = function enhanceError(error, config, code, request, response) {
|
||||
error.config = config;
|
||||
if (code) {
|
||||
error.code = code;
|
||||
}
|
||||
|
||||
error.request = request;
|
||||
error.response = response;
|
||||
error.isAxiosError = true;
|
||||
|
||||
error.toJSON = function() {
|
||||
return {
|
||||
// Standard
|
||||
message: this.message,
|
||||
name: this.name,
|
||||
// Microsoft
|
||||
description: this.description,
|
||||
number: this.number,
|
||||
// Mozilla
|
||||
fileName: this.fileName,
|
||||
lineNumber: this.lineNumber,
|
||||
columnNumber: this.columnNumber,
|
||||
stack: this.stack,
|
||||
// Axios
|
||||
config: this.config,
|
||||
code: this.code
|
||||
};
|
||||
};
|
||||
return error;
|
||||
};
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('../utils');
|
||||
|
||||
/**
|
||||
* Config-specific merge-function which creates a new config-object
|
||||
* by merging two configuration objects together.
|
||||
*
|
||||
* @param {Object} config1
|
||||
* @param {Object} config2
|
||||
* @returns {Object} New object resulting from merging config2 to config1
|
||||
*/
|
||||
module.exports = function mergeConfig(config1, config2) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
config2 = config2 || {};
|
||||
var config = {};
|
||||
|
||||
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
|
||||
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
|
||||
var defaultToConfig2Keys = [
|
||||
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
|
||||
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
|
||||
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
|
||||
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
|
||||
'httpsAgent', 'cancelToken', 'socketPath'
|
||||
];
|
||||
|
||||
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
|
||||
if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
}
|
||||
});
|
||||
|
||||
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
|
||||
if (utils.isObject(config2[prop])) {
|
||||
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
|
||||
} else if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
} else if (utils.isObject(config1[prop])) {
|
||||
config[prop] = utils.deepMerge(config1[prop]);
|
||||
} else if (typeof config1[prop] !== 'undefined') {
|
||||
config[prop] = config1[prop];
|
||||
}
|
||||
});
|
||||
|
||||
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
|
||||
if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
} else if (typeof config1[prop] !== 'undefined') {
|
||||
config[prop] = config1[prop];
|
||||
}
|
||||
});
|
||||
|
||||
var axiosKeys = valueFromConfig2Keys
|
||||
.concat(mergeDeepPropertiesKeys)
|
||||
.concat(defaultToConfig2Keys);
|
||||
|
||||
var otherKeys = Object
|
||||
.keys(config2)
|
||||
.filter(function filterAxiosKeys(key) {
|
||||
return axiosKeys.indexOf(key) === -1;
|
||||
});
|
||||
|
||||
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
|
||||
if (typeof config2[prop] !== 'undefined') {
|
||||
config[prop] = config2[prop];
|
||||
} else if (typeof config1[prop] !== 'undefined') {
|
||||
config[prop] = config1[prop];
|
||||
}
|
||||
});
|
||||
|
||||
return config;
|
||||
};
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
var createError = require('./createError');
|
||||
|
||||
/**
|
||||
* Resolve or reject a Promise based on response status.
|
||||
*
|
||||
* @param {Function} resolve A function that resolves the promise.
|
||||
* @param {Function} reject A function that rejects the promise.
|
||||
* @param {object} response The response.
|
||||
*/
|
||||
module.exports = function settle(resolve, reject, response) {
|
||||
var validateStatus = response.config.validateStatus;
|
||||
if (!validateStatus || validateStatus(response.status)) {
|
||||
resolve(response);
|
||||
} else {
|
||||
reject(createError(
|
||||
'Request failed with status code ' + response.status,
|
||||
response.config,
|
||||
null,
|
||||
response.request,
|
||||
response
|
||||
));
|
||||
}
|
||||
};
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
/**
|
||||
* Transform the data for a request or a response
|
||||
*
|
||||
* @param {Object|String} data The data to be transformed
|
||||
* @param {Array} headers The headers for the request or response
|
||||
* @param {Array|Function} fns A single function or Array of functions
|
||||
* @returns {*} The resulting transformed data
|
||||
*/
|
||||
module.exports = function transformData(data, headers, fns) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
utils.forEach(fns, function transform(fn) {
|
||||
data = fn(data, headers);
|
||||
});
|
||||
|
||||
return data;
|
||||
};
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./utils');
|
||||
var normalizeHeaderName = require('./helpers/normalizeHeaderName');
|
||||
|
||||
var DEFAULT_CONTENT_TYPE = {
|
||||
'Content-Type': 'application/x-www-form-urlencoded'
|
||||
};
|
||||
|
||||
function setContentTypeIfUnset(headers, value) {
|
||||
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
|
||||
headers['Content-Type'] = value;
|
||||
}
|
||||
}
|
||||
|
||||
function getDefaultAdapter() {
|
||||
var adapter;
|
||||
if (typeof XMLHttpRequest !== 'undefined') {
|
||||
// For browsers use XHR adapter
|
||||
adapter = require('./adapters/xhr');
|
||||
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
|
||||
// For node use HTTP adapter
|
||||
adapter = require('./adapters/http');
|
||||
}
|
||||
return adapter;
|
||||
}
|
||||
|
||||
var defaults = {
|
||||
adapter: getDefaultAdapter(),
|
||||
|
||||
transformRequest: [function transformRequest(data, headers) {
|
||||
normalizeHeaderName(headers, 'Accept');
|
||||
normalizeHeaderName(headers, 'Content-Type');
|
||||
if (utils.isFormData(data) ||
|
||||
utils.isArrayBuffer(data) ||
|
||||
utils.isBuffer(data) ||
|
||||
utils.isStream(data) ||
|
||||
utils.isFile(data) ||
|
||||
utils.isBlob(data)
|
||||
) {
|
||||
return data;
|
||||
}
|
||||
if (utils.isArrayBufferView(data)) {
|
||||
return data.buffer;
|
||||
}
|
||||
if (utils.isURLSearchParams(data)) {
|
||||
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
|
||||
return data.toString();
|
||||
}
|
||||
if (utils.isObject(data)) {
|
||||
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
|
||||
return JSON.stringify(data);
|
||||
}
|
||||
return data;
|
||||
}],
|
||||
|
||||
transformResponse: [function transformResponse(data) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
if (typeof data === 'string') {
|
||||
try {
|
||||
data = JSON.parse(data);
|
||||
} catch (e) { /* Ignore */ }
|
||||
}
|
||||
return data;
|
||||
}],
|
||||
|
||||
/**
|
||||
* A timeout in milliseconds to abort a request. If set to 0 (default) a
|
||||
* timeout is not created.
|
||||
*/
|
||||
timeout: 0,
|
||||
|
||||
xsrfCookieName: 'XSRF-TOKEN',
|
||||
xsrfHeaderName: 'X-XSRF-TOKEN',
|
||||
|
||||
maxContentLength: -1,
|
||||
|
||||
validateStatus: function validateStatus(status) {
|
||||
return status >= 200 && status < 300;
|
||||
}
|
||||
};
|
||||
|
||||
defaults.headers = {
|
||||
common: {
|
||||
'Accept': 'application/json, text/plain, */*'
|
||||
}
|
||||
};
|
||||
|
||||
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
|
||||
defaults.headers[method] = {};
|
||||
});
|
||||
|
||||
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
|
||||
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
|
||||
});
|
||||
|
||||
module.exports = defaults;
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
# axios // helpers
|
||||
|
||||
The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like:
|
||||
|
||||
- Browser polyfills
|
||||
- Managing cookies
|
||||
- Parsing HTTP headers
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
module.exports = function bind(fn, thisArg) {
|
||||
return function wrap() {
|
||||
var args = new Array(arguments.length);
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i] = arguments[i];
|
||||
}
|
||||
return fn.apply(thisArg, args);
|
||||
};
|
||||
};
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
function encode(val) {
|
||||
return encodeURIComponent(val).
|
||||
replace(/%40/gi, '@').
|
||||
replace(/%3A/gi, ':').
|
||||
replace(/%24/g, '$').
|
||||
replace(/%2C/gi, ',').
|
||||
replace(/%20/g, '+').
|
||||
replace(/%5B/gi, '[').
|
||||
replace(/%5D/gi, ']');
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a URL by appending params to the end
|
||||
*
|
||||
* @param {string} url The base of the url (e.g., http://www.google.com)
|
||||
* @param {object} [params] The params to be appended
|
||||
* @returns {string} The formatted url
|
||||
*/
|
||||
module.exports = function buildURL(url, params, paramsSerializer) {
|
||||
/*eslint no-param-reassign:0*/
|
||||
if (!params) {
|
||||
return url;
|
||||
}
|
||||
|
||||
var serializedParams;
|
||||
if (paramsSerializer) {
|
||||
serializedParams = paramsSerializer(params);
|
||||
} else if (utils.isURLSearchParams(params)) {
|
||||
serializedParams = params.toString();
|
||||
} else {
|
||||
var parts = [];
|
||||
|
||||
utils.forEach(params, function serialize(val, key) {
|
||||
if (val === null || typeof val === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (utils.isArray(val)) {
|
||||
key = key + '[]';
|
||||
} else {
|
||||
val = [val];
|
||||
}
|
||||
|
||||
utils.forEach(val, function parseValue(v) {
|
||||
if (utils.isDate(v)) {
|
||||
v = v.toISOString();
|
||||
} else if (utils.isObject(v)) {
|
||||
v = JSON.stringify(v);
|
||||
}
|
||||
parts.push(encode(key) + '=' + encode(v));
|
||||
});
|
||||
});
|
||||
|
||||
serializedParams = parts.join('&');
|
||||
}
|
||||
|
||||
if (serializedParams) {
|
||||
var hashmarkIndex = url.indexOf('#');
|
||||
if (hashmarkIndex !== -1) {
|
||||
url = url.slice(0, hashmarkIndex);
|
||||
}
|
||||
|
||||
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
|
||||
}
|
||||
|
||||
return url;
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Creates a new URL by combining the specified URLs
|
||||
*
|
||||
* @param {string} baseURL The base URL
|
||||
* @param {string} relativeURL The relative URL
|
||||
* @returns {string} The combined URL
|
||||
*/
|
||||
module.exports = function combineURLs(baseURL, relativeURL) {
|
||||
return relativeURL
|
||||
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
|
||||
: baseURL;
|
||||
};
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
module.exports = (
|
||||
utils.isStandardBrowserEnv() ?
|
||||
|
||||
// Standard browser envs support document.cookie
|
||||
(function standardBrowserEnv() {
|
||||
return {
|
||||
write: function write(name, value, expires, path, domain, secure) {
|
||||
var cookie = [];
|
||||
cookie.push(name + '=' + encodeURIComponent(value));
|
||||
|
||||
if (utils.isNumber(expires)) {
|
||||
cookie.push('expires=' + new Date(expires).toGMTString());
|
||||
}
|
||||
|
||||
if (utils.isString(path)) {
|
||||
cookie.push('path=' + path);
|
||||
}
|
||||
|
||||
if (utils.isString(domain)) {
|
||||
cookie.push('domain=' + domain);
|
||||
}
|
||||
|
||||
if (secure === true) {
|
||||
cookie.push('secure');
|
||||
}
|
||||
|
||||
document.cookie = cookie.join('; ');
|
||||
},
|
||||
|
||||
read: function read(name) {
|
||||
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
|
||||
return (match ? decodeURIComponent(match[3]) : null);
|
||||
},
|
||||
|
||||
remove: function remove(name) {
|
||||
this.write(name, '', Date.now() - 86400000);
|
||||
}
|
||||
};
|
||||
})() :
|
||||
|
||||
// Non standard browser env (web workers, react-native) lack needed support.
|
||||
(function nonStandardBrowserEnv() {
|
||||
return {
|
||||
write: function write() {},
|
||||
read: function read() { return null; },
|
||||
remove: function remove() {}
|
||||
};
|
||||
})()
|
||||
);
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
|
||||
/*eslint no-console:0*/
|
||||
|
||||
/**
|
||||
* Supply a warning to the developer that a method they are using
|
||||
* has been deprecated.
|
||||
*
|
||||
* @param {string} method The name of the deprecated method
|
||||
* @param {string} [instead] The alternate method to use if applicable
|
||||
* @param {string} [docs] The documentation URL to get further details
|
||||
*/
|
||||
module.exports = function deprecatedMethod(method, instead, docs) {
|
||||
try {
|
||||
console.warn(
|
||||
'DEPRECATED method `' + method + '`.' +
|
||||
(instead ? ' Use `' + instead + '` instead.' : '') +
|
||||
' This method will be removed in a future release.');
|
||||
|
||||
if (docs) {
|
||||
console.warn('For more information about usage see ' + docs);
|
||||
}
|
||||
} catch (e) { /* Ignore */ }
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Determines whether the specified URL is absolute
|
||||
*
|
||||
* @param {string} url The URL to test
|
||||
* @returns {boolean} True if the specified URL is absolute, otherwise false
|
||||
*/
|
||||
module.exports = function isAbsoluteURL(url) {
|
||||
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
|
||||
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
|
||||
// by any combination of letters, digits, plus, period, or hyphen.
|
||||
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
|
||||
};
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
module.exports = (
|
||||
utils.isStandardBrowserEnv() ?
|
||||
|
||||
// Standard browser envs have full support of the APIs needed to test
|
||||
// whether the request URL is of the same origin as current location.
|
||||
(function standardBrowserEnv() {
|
||||
var msie = /(msie|trident)/i.test(navigator.userAgent);
|
||||
var urlParsingNode = document.createElement('a');
|
||||
var originURL;
|
||||
|
||||
/**
|
||||
* Parse a URL to discover it's components
|
||||
*
|
||||
* @param {String} url The URL to be parsed
|
||||
* @returns {Object}
|
||||
*/
|
||||
function resolveURL(url) {
|
||||
var href = url;
|
||||
|
||||
if (msie) {
|
||||
// IE needs attribute set twice to normalize properties
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
href = urlParsingNode.href;
|
||||
}
|
||||
|
||||
urlParsingNode.setAttribute('href', href);
|
||||
|
||||
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
|
||||
return {
|
||||
href: urlParsingNode.href,
|
||||
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
|
||||
host: urlParsingNode.host,
|
||||
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
|
||||
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
|
||||
hostname: urlParsingNode.hostname,
|
||||
port: urlParsingNode.port,
|
||||
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
|
||||
urlParsingNode.pathname :
|
||||
'/' + urlParsingNode.pathname
|
||||
};
|
||||
}
|
||||
|
||||
originURL = resolveURL(window.location.href);
|
||||
|
||||
/**
|
||||
* Determine if a URL shares the same origin as the current location
|
||||
*
|
||||
* @param {String} requestURL The URL to test
|
||||
* @returns {boolean} True if URL shares the same origin, otherwise false
|
||||
*/
|
||||
return function isURLSameOrigin(requestURL) {
|
||||
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
|
||||
return (parsed.protocol === originURL.protocol &&
|
||||
parsed.host === originURL.host);
|
||||
};
|
||||
})() :
|
||||
|
||||
// Non standard browser envs (web workers, react-native) lack needed support.
|
||||
(function nonStandardBrowserEnv() {
|
||||
return function isURLSameOrigin() {
|
||||
return true;
|
||||
};
|
||||
})()
|
||||
);
|
||||
Generated
Vendored
+12
@@ -0,0 +1,12 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('../utils');
|
||||
|
||||
module.exports = function normalizeHeaderName(headers, normalizedName) {
|
||||
utils.forEach(headers, function processHeader(value, name) {
|
||||
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
|
||||
headers[normalizedName] = value;
|
||||
delete headers[name];
|
||||
}
|
||||
});
|
||||
};
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
var utils = require('./../utils');
|
||||
|
||||
// Headers whose duplicates are ignored by node
|
||||
// c.f. https://nodejs.org/api/http.html#http_message_headers
|
||||
var ignoreDuplicateOf = [
|
||||
'age', 'authorization', 'content-length', 'content-type', 'etag',
|
||||
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
|
||||
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
|
||||
'referer', 'retry-after', 'user-agent'
|
||||
];
|
||||
|
||||
/**
|
||||
* Parse headers into an object
|
||||
*
|
||||
* ```
|
||||
* Date: Wed, 27 Aug 2014 08:58:49 GMT
|
||||
* Content-Type: application/json
|
||||
* Connection: keep-alive
|
||||
* Transfer-Encoding: chunked
|
||||
* ```
|
||||
*
|
||||
* @param {String} headers Headers needing to be parsed
|
||||
* @returns {Object} Headers parsed into an object
|
||||
*/
|
||||
module.exports = function parseHeaders(headers) {
|
||||
var parsed = {};
|
||||
var key;
|
||||
var val;
|
||||
var i;
|
||||
|
||||
if (!headers) { return parsed; }
|
||||
|
||||
utils.forEach(headers.split('\n'), function parser(line) {
|
||||
i = line.indexOf(':');
|
||||
key = utils.trim(line.substr(0, i)).toLowerCase();
|
||||
val = utils.trim(line.substr(i + 1));
|
||||
|
||||
if (key) {
|
||||
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
|
||||
return;
|
||||
}
|
||||
if (key === 'set-cookie') {
|
||||
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
|
||||
} else {
|
||||
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return parsed;
|
||||
};
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Syntactic sugar for invoking a function and expanding an array for arguments.
|
||||
*
|
||||
* Common use case would be to use `Function.prototype.apply`.
|
||||
*
|
||||
* ```js
|
||||
* function f(x, y, z) {}
|
||||
* var args = [1, 2, 3];
|
||||
* f.apply(null, args);
|
||||
* ```
|
||||
*
|
||||
* With `spread` this example can be re-written.
|
||||
*
|
||||
* ```js
|
||||
* spread(function(x, y, z) {})([1, 2, 3]);
|
||||
* ```
|
||||
*
|
||||
* @param {Function} callback
|
||||
* @returns {Function}
|
||||
*/
|
||||
module.exports = function spread(callback) {
|
||||
return function wrap(arr) {
|
||||
return callback.apply(null, arr);
|
||||
};
|
||||
};
|
||||
+344
@@ -0,0 +1,344 @@
|
||||
'use strict';
|
||||
|
||||
var bind = require('./helpers/bind');
|
||||
|
||||
/*global toString:true*/
|
||||
|
||||
// utils is a library of generic helper functions non-specific to axios
|
||||
|
||||
var toString = Object.prototype.toString;
|
||||
|
||||
/**
|
||||
* Determine if a value is an Array
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is an Array, otherwise false
|
||||
*/
|
||||
function isArray(val) {
|
||||
return toString.call(val) === '[object Array]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is undefined
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if the value is undefined, otherwise false
|
||||
*/
|
||||
function isUndefined(val) {
|
||||
return typeof val === 'undefined';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a Buffer
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a Buffer, otherwise false
|
||||
*/
|
||||
function isBuffer(val) {
|
||||
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
|
||||
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is an ArrayBuffer
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
|
||||
*/
|
||||
function isArrayBuffer(val) {
|
||||
return toString.call(val) === '[object ArrayBuffer]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a FormData
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is an FormData, otherwise false
|
||||
*/
|
||||
function isFormData(val) {
|
||||
return (typeof FormData !== 'undefined') && (val instanceof FormData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a view on an ArrayBuffer
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
|
||||
*/
|
||||
function isArrayBufferView(val) {
|
||||
var result;
|
||||
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
|
||||
result = ArrayBuffer.isView(val);
|
||||
} else {
|
||||
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a String
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a String, otherwise false
|
||||
*/
|
||||
function isString(val) {
|
||||
return typeof val === 'string';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a Number
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a Number, otherwise false
|
||||
*/
|
||||
function isNumber(val) {
|
||||
return typeof val === 'number';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is an Object
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is an Object, otherwise false
|
||||
*/
|
||||
function isObject(val) {
|
||||
return val !== null && typeof val === 'object';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a Date
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a Date, otherwise false
|
||||
*/
|
||||
function isDate(val) {
|
||||
return toString.call(val) === '[object Date]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a File
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a File, otherwise false
|
||||
*/
|
||||
function isFile(val) {
|
||||
return toString.call(val) === '[object File]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a Blob
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a Blob, otherwise false
|
||||
*/
|
||||
function isBlob(val) {
|
||||
return toString.call(val) === '[object Blob]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a Function
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a Function, otherwise false
|
||||
*/
|
||||
function isFunction(val) {
|
||||
return toString.call(val) === '[object Function]';
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a Stream
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a Stream, otherwise false
|
||||
*/
|
||||
function isStream(val) {
|
||||
return isObject(val) && isFunction(val.pipe);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a value is a URLSearchParams object
|
||||
*
|
||||
* @param {Object} val The value to test
|
||||
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
|
||||
*/
|
||||
function isURLSearchParams(val) {
|
||||
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trim excess whitespace off the beginning and end of a string
|
||||
*
|
||||
* @param {String} str The String to trim
|
||||
* @returns {String} The String freed of excess whitespace
|
||||
*/
|
||||
function trim(str) {
|
||||
return str.replace(/^\s*/, '').replace(/\s*$/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if we're running in a standard browser environment
|
||||
*
|
||||
* This allows axios to run in a web worker, and react-native.
|
||||
* Both environments support XMLHttpRequest, but not fully standard globals.
|
||||
*
|
||||
* web workers:
|
||||
* typeof window -> undefined
|
||||
* typeof document -> undefined
|
||||
*
|
||||
* react-native:
|
||||
* navigator.product -> 'ReactNative'
|
||||
* nativescript
|
||||
* navigator.product -> 'NativeScript' or 'NS'
|
||||
*/
|
||||
function isStandardBrowserEnv() {
|
||||
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
|
||||
navigator.product === 'NativeScript' ||
|
||||
navigator.product === 'NS')) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof document !== 'undefined'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over an Array or an Object invoking a function for each item.
|
||||
*
|
||||
* If `obj` is an Array callback will be called passing
|
||||
* the value, index, and complete array for each item.
|
||||
*
|
||||
* If 'obj' is an Object callback will be called passing
|
||||
* the value, key, and complete object for each property.
|
||||
*
|
||||
* @param {Object|Array} obj The object to iterate
|
||||
* @param {Function} fn The callback to invoke for each item
|
||||
*/
|
||||
function forEach(obj, fn) {
|
||||
// Don't bother if no value provided
|
||||
if (obj === null || typeof obj === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Force an array if not already something iterable
|
||||
if (typeof obj !== 'object') {
|
||||
/*eslint no-param-reassign:0*/
|
||||
obj = [obj];
|
||||
}
|
||||
|
||||
if (isArray(obj)) {
|
||||
// Iterate over array values
|
||||
for (var i = 0, l = obj.length; i < l; i++) {
|
||||
fn.call(null, obj[i], i, obj);
|
||||
}
|
||||
} else {
|
||||
// Iterate over object keys
|
||||
for (var key in obj) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
||||
fn.call(null, obj[key], key, obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts varargs expecting each argument to be an object, then
|
||||
* immutably merges the properties of each object and returns result.
|
||||
*
|
||||
* When multiple objects contain the same key the later object in
|
||||
* the arguments list will take precedence.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* var result = merge({foo: 123}, {foo: 456});
|
||||
* console.log(result.foo); // outputs 456
|
||||
* ```
|
||||
*
|
||||
* @param {Object} obj1 Object to merge
|
||||
* @returns {Object} Result of all merge properties
|
||||
*/
|
||||
function merge(/* obj1, obj2, obj3, ... */) {
|
||||
var result = {};
|
||||
function assignValue(val, key) {
|
||||
if (typeof result[key] === 'object' && typeof val === 'object') {
|
||||
result[key] = merge(result[key], val);
|
||||
} else {
|
||||
result[key] = val;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0, l = arguments.length; i < l; i++) {
|
||||
forEach(arguments[i], assignValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function equal to merge with the difference being that no reference
|
||||
* to original objects is kept.
|
||||
*
|
||||
* @see merge
|
||||
* @param {Object} obj1 Object to merge
|
||||
* @returns {Object} Result of all merge properties
|
||||
*/
|
||||
function deepMerge(/* obj1, obj2, obj3, ... */) {
|
||||
var result = {};
|
||||
function assignValue(val, key) {
|
||||
if (typeof result[key] === 'object' && typeof val === 'object') {
|
||||
result[key] = deepMerge(result[key], val);
|
||||
} else if (typeof val === 'object') {
|
||||
result[key] = deepMerge({}, val);
|
||||
} else {
|
||||
result[key] = val;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0, l = arguments.length; i < l; i++) {
|
||||
forEach(arguments[i], assignValue);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extends object a by mutably adding to it the properties of object b.
|
||||
*
|
||||
* @param {Object} a The object to be extended
|
||||
* @param {Object} b The object to copy properties from
|
||||
* @param {Object} thisArg The object to bind function to
|
||||
* @return {Object} The resulting value of object a
|
||||
*/
|
||||
function extend(a, b, thisArg) {
|
||||
forEach(b, function assignValue(val, key) {
|
||||
if (thisArg && typeof val === 'function') {
|
||||
a[key] = bind(val, thisArg);
|
||||
} else {
|
||||
a[key] = val;
|
||||
}
|
||||
});
|
||||
return a;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isArray: isArray,
|
||||
isArrayBuffer: isArrayBuffer,
|
||||
isBuffer: isBuffer,
|
||||
isFormData: isFormData,
|
||||
isArrayBufferView: isArrayBufferView,
|
||||
isString: isString,
|
||||
isNumber: isNumber,
|
||||
isObject: isObject,
|
||||
isUndefined: isUndefined,
|
||||
isDate: isDate,
|
||||
isFile: isFile,
|
||||
isBlob: isBlob,
|
||||
isFunction: isFunction,
|
||||
isStream: isStream,
|
||||
isURLSearchParams: isURLSearchParams,
|
||||
isStandardBrowserEnv: isStandardBrowserEnv,
|
||||
forEach: forEach,
|
||||
merge: merge,
|
||||
deepMerge: deepMerge,
|
||||
extend: extend,
|
||||
trim: trim
|
||||
};
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
{
|
||||
"_from": "axios@^0.19.0",
|
||||
"_id": "[email protected]",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==",
|
||||
"_location": "/@slack/web-api/axios",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "range",
|
||||
"registry": true,
|
||||
"raw": "axios@^0.19.0",
|
||||
"name": "axios",
|
||||
"escapedName": "axios",
|
||||
"rawSpec": "^0.19.0",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "^0.19.0"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/@slack/web-api"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz",
|
||||
"_shasum": "3ea36c5d8818d0d5f8a8a97a6d36b86cdc00cb27",
|
||||
"_spec": "axios@^0.19.0",
|
||||
"_where": "/Users/stevengill/repo/slack-github-action/node_modules/@slack/web-api",
|
||||
"author": {
|
||||
"name": "Matt Zabriskie"
|
||||
},
|
||||
"browser": {
|
||||
"./lib/adapters/http.js": "./lib/adapters/xhr.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/axios/axios/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"bundlesize": [
|
||||
{
|
||||
"path": "./dist/axios.min.js",
|
||||
"threshold": "5kB"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"follow-redirects": "1.5.10"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Promise based HTTP client for the browser and node.js",
|
||||
"devDependencies": {
|
||||
"bundlesize": "^0.17.0",
|
||||
"coveralls": "^3.0.0",
|
||||
"es6-promise": "^4.2.4",
|
||||
"grunt": "^1.0.2",
|
||||
"grunt-banner": "^0.6.0",
|
||||
"grunt-cli": "^1.2.0",
|
||||
"grunt-contrib-clean": "^1.1.0",
|
||||
"grunt-contrib-watch": "^1.0.0",
|
||||
"grunt-eslint": "^20.1.0",
|
||||
"grunt-karma": "^2.0.0",
|
||||
"grunt-mocha-test": "^0.13.3",
|
||||
"grunt-ts": "^6.0.0-beta.19",
|
||||
"grunt-webpack": "^1.0.18",
|
||||
"istanbul-instrumenter-loader": "^1.0.0",
|
||||
"jasmine-core": "^2.4.1",
|
||||
"karma": "^1.3.0",
|
||||
"karma-chrome-launcher": "^2.2.0",
|
||||
"karma-coverage": "^1.1.1",
|
||||
"karma-firefox-launcher": "^1.1.0",
|
||||
"karma-jasmine": "^1.1.1",
|
||||
"karma-jasmine-ajax": "^0.1.13",
|
||||
"karma-opera-launcher": "^1.0.0",
|
||||
"karma-safari-launcher": "^1.0.0",
|
||||
"karma-sauce-launcher": "^1.2.0",
|
||||
"karma-sinon": "^1.0.5",
|
||||
"karma-sourcemap-loader": "^0.3.7",
|
||||
"karma-webpack": "^1.7.0",
|
||||
"load-grunt-tasks": "^3.5.2",
|
||||
"minimist": "^1.2.0",
|
||||
"mocha": "^5.2.0",
|
||||
"sinon": "^4.5.0",
|
||||
"typescript": "^2.8.1",
|
||||
"url-search-params": "^0.10.0",
|
||||
"webpack": "^1.13.1",
|
||||
"webpack-dev-server": "^1.14.1"
|
||||
},
|
||||
"homepage": "https://github.com/axios/axios",
|
||||
"keywords": [
|
||||
"xhr",
|
||||
"http",
|
||||
"ajax",
|
||||
"promise",
|
||||
"node"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "axios",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/axios/axios.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "NODE_ENV=production grunt build",
|
||||
"coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
|
||||
"examples": "node ./examples/server.js",
|
||||
"fix": "eslint --fix lib/**/*.js",
|
||||
"postversion": "git push && git push --tags",
|
||||
"preversion": "npm test",
|
||||
"start": "node ./sandbox/server.js",
|
||||
"test": "grunt test && bundlesize",
|
||||
"version": "npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"
|
||||
},
|
||||
"typings": "./index.d.ts",
|
||||
"version": "0.19.2"
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
Copyright 2014–present Olivier Lalonde <[email protected]>, James Talmage <[email protected]>, Ruben Verborgh
|
||||
|
||||
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.
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
## Follow Redirects
|
||||
|
||||
Drop-in replacement for Nodes `http` and `https` that automatically follows redirects.
|
||||
|
||||
[](https://www.npmjs.com/package/follow-redirects)
|
||||
[](https://travis-ci.org/follow-redirects/follow-redirects)
|
||||
[](https://coveralls.io/r/follow-redirects/follow-redirects?branch=master)
|
||||
[](https://david-dm.org/follow-redirects/follow-redirects)
|
||||
[](https://www.npmjs.com/package/follow-redirects)
|
||||
|
||||
`follow-redirects` provides [request](https://nodejs.org/api/http.html#http_http_request_options_callback) and [get](https://nodejs.org/api/http.html#http_http_get_options_callback)
|
||||
methods that behave identically to those found on the native [http](https://nodejs.org/api/http.html#http_http_request_options_callback) and [https](https://nodejs.org/api/https.html#https_https_request_options_callback)
|
||||
modules, with the exception that they will seamlessly follow redirects.
|
||||
|
||||
```javascript
|
||||
var http = require('follow-redirects').http;
|
||||
var https = require('follow-redirects').https;
|
||||
|
||||
http.get('http://bit.ly/900913', function (response) {
|
||||
response.on('data', function (chunk) {
|
||||
console.log(chunk);
|
||||
});
|
||||
}).on('error', function (err) {
|
||||
console.error(err);
|
||||
});
|
||||
```
|
||||
|
||||
You can inspect the final redirected URL through the `responseUrl` property on the `response`.
|
||||
If no redirection happened, `responseUrl` is the original request URL.
|
||||
|
||||
```javascript
|
||||
https.request({
|
||||
host: 'bitly.com',
|
||||
path: '/UHfDGO',
|
||||
}, function (response) {
|
||||
console.log(response.responseUrl);
|
||||
// 'http://duckduckgo.com/robots.txt'
|
||||
});
|
||||
```
|
||||
|
||||
## Options
|
||||
### Global options
|
||||
Global options are set directly on the `follow-redirects` module:
|
||||
|
||||
```javascript
|
||||
var followRedirects = require('follow-redirects');
|
||||
followRedirects.maxRedirects = 10;
|
||||
followRedirects.maxBodyLength = 20 * 1024 * 1024; // 20 MB
|
||||
```
|
||||
|
||||
The following global options are supported:
|
||||
|
||||
- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
|
||||
|
||||
- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
|
||||
|
||||
|
||||
### Per-request options
|
||||
Per-request options are set by passing an `options` object:
|
||||
|
||||
```javascript
|
||||
var url = require('url');
|
||||
var followRedirects = require('follow-redirects');
|
||||
|
||||
var options = url.parse('http://bit.ly/900913');
|
||||
options.maxRedirects = 10;
|
||||
http.request(options);
|
||||
```
|
||||
|
||||
In addition to the [standard HTTP](https://nodejs.org/api/http.html#http_http_request_options_callback) and [HTTPS options](https://nodejs.org/api/https.html#https_https_request_options_callback),
|
||||
the following per-request options are supported:
|
||||
- `followRedirects` (default: `true`) – whether redirects should be followed.
|
||||
|
||||
- `maxRedirects` (default: `21`) – sets the maximum number of allowed redirects; if exceeded, an error will be emitted.
|
||||
|
||||
- `maxBodyLength` (default: 10MB) – sets the maximum size of the request body; if exceeded, an error will be emitted.
|
||||
|
||||
- `agents` (default: `undefined`) – sets the `agent` option per protocol, since HTTP and HTTPS use different agents. Example value: `{ http: new http.Agent(), https: new https.Agent() }`
|
||||
|
||||
- `trackRedirects` (default: `false`) – whether to store the redirected response details into the `redirects` array on the response object.
|
||||
|
||||
|
||||
### Advanced usage
|
||||
By default, `follow-redirects` will use the Node.js default implementations
|
||||
of [`http`](https://nodejs.org/api/http.html)
|
||||
and [`https`](https://nodejs.org/api/https.html).
|
||||
To enable features such as caching and/or intermediate request tracking,
|
||||
you might instead want to wrap `follow-redirects` around custom protocol implementations:
|
||||
|
||||
```javascript
|
||||
var followRedirects = require('follow-redirects').wrap({
|
||||
http: require('your-custom-http'),
|
||||
https: require('your-custom-https'),
|
||||
});
|
||||
```
|
||||
|
||||
Such custom protocols only need an implementation of the `request` method.
|
||||
|
||||
## Browserify Usage
|
||||
|
||||
Due to the way `XMLHttpRequest` works, the `browserify` versions of `http` and `https` already follow redirects.
|
||||
If you are *only* targeting the browser, then this library has little value for you. If you want to write cross
|
||||
platform code for node and the browser, `follow-redirects` provides a great solution for making the native node
|
||||
modules behave the same as they do in browserified builds in the browser. To avoid bundling unnecessary code
|
||||
you should tell browserify to swap out `follow-redirects` with the standard modules when bundling.
|
||||
To make this easier, you need to change how you require the modules:
|
||||
|
||||
```javascript
|
||||
var http = require('follow-redirects/http');
|
||||
var https = require('follow-redirects/https');
|
||||
```
|
||||
|
||||
You can then replace `follow-redirects` in your browserify configuration like so:
|
||||
|
||||
```javascript
|
||||
"browser": {
|
||||
"follow-redirects/http" : "http",
|
||||
"follow-redirects/https" : "https"
|
||||
}
|
||||
```
|
||||
|
||||
The `browserify-http` module has not kept pace with node development, and no long behaves identically to the native
|
||||
module when running in the browser. If you are experiencing problems, you may want to check out
|
||||
[browserify-http-2](https://www.npmjs.com/package/http-browserify-2). It is more actively maintained and
|
||||
attempts to address a few of the shortcomings of `browserify-http`. In that case, your browserify config should
|
||||
look something like this:
|
||||
|
||||
```javascript
|
||||
"browser": {
|
||||
"follow-redirects/http" : "browserify-http-2/http",
|
||||
"follow-redirects/https" : "browserify-http-2/https"
|
||||
}
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull Requests are always welcome. Please [file an issue](https://github.com/follow-redirects/follow-redirects/issues)
|
||||
detailing your proposal before you invest your valuable time. Additional features and bug fixes should be accompanied
|
||||
by tests. You can run the test suite locally with a simple `npm test` command.
|
||||
|
||||
## Debug Logging
|
||||
|
||||
`follow-redirects` uses the excellent [debug](https://www.npmjs.com/package/debug) for logging. To turn on logging
|
||||
set the environment variable `DEBUG=follow-redirects` for debug output from just this module. When running the test
|
||||
suite it is sometimes advantageous to set `DEBUG=*` to see output from the express server as well.
|
||||
|
||||
## Authors
|
||||
|
||||
- Olivier Lalonde (olalonde@gmail.com)
|
||||
- James Talmage (james@talmage.io)
|
||||
- [Ruben Verborgh](https://ruben.verborgh.org/)
|
||||
|
||||
## License
|
||||
|
||||
[https://github.com/follow-redirects/follow-redirects/blob/master/LICENSE](MIT License)
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./").http;
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = require("./").https;
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
var url = require("url");
|
||||
var http = require("http");
|
||||
var https = require("https");
|
||||
var assert = require("assert");
|
||||
var Writable = require("stream").Writable;
|
||||
var debug = require("debug")("follow-redirects");
|
||||
|
||||
// RFC7231§4.2.1: Of the request methods defined by this specification,
|
||||
// the GET, HEAD, OPTIONS, and TRACE methods are defined to be safe.
|
||||
var SAFE_METHODS = { GET: true, HEAD: true, OPTIONS: true, TRACE: true };
|
||||
|
||||
// Create handlers that pass events from native requests
|
||||
var eventHandlers = Object.create(null);
|
||||
["abort", "aborted", "error", "socket", "timeout"].forEach(function (event) {
|
||||
eventHandlers[event] = function (arg) {
|
||||
this._redirectable.emit(event, arg);
|
||||
};
|
||||
});
|
||||
|
||||
// An HTTP(S) request that can be redirected
|
||||
function RedirectableRequest(options, responseCallback) {
|
||||
// Initialize the request
|
||||
Writable.call(this);
|
||||
options.headers = options.headers || {};
|
||||
this._options = options;
|
||||
this._redirectCount = 0;
|
||||
this._redirects = [];
|
||||
this._requestBodyLength = 0;
|
||||
this._requestBodyBuffers = [];
|
||||
|
||||
// Since http.request treats host as an alias of hostname,
|
||||
// but the url module interprets host as hostname plus port,
|
||||
// eliminate the host property to avoid confusion.
|
||||
if (options.host) {
|
||||
// Use hostname if set, because it has precedence
|
||||
if (!options.hostname) {
|
||||
options.hostname = options.host;
|
||||
}
|
||||
delete options.host;
|
||||
}
|
||||
|
||||
// Attach a callback if passed
|
||||
if (responseCallback) {
|
||||
this.on("response", responseCallback);
|
||||
}
|
||||
|
||||
// React to responses of native requests
|
||||
var self = this;
|
||||
this._onNativeResponse = function (response) {
|
||||
self._processResponse(response);
|
||||
};
|
||||
|
||||
// Complete the URL object when necessary
|
||||
if (!options.pathname && options.path) {
|
||||
var searchPos = options.path.indexOf("?");
|
||||
if (searchPos < 0) {
|
||||
options.pathname = options.path;
|
||||
}
|
||||
else {
|
||||
options.pathname = options.path.substring(0, searchPos);
|
||||
options.search = options.path.substring(searchPos);
|
||||
}
|
||||
}
|
||||
|
||||
// Perform the first request
|
||||
this._performRequest();
|
||||
}
|
||||
RedirectableRequest.prototype = Object.create(Writable.prototype);
|
||||
|
||||
// Writes buffered data to the current native request
|
||||
RedirectableRequest.prototype.write = function (data, encoding, callback) {
|
||||
// Validate input and shift parameters if necessary
|
||||
if (!(typeof data === "string" || typeof data === "object" && ("length" in data))) {
|
||||
throw new Error("data should be a string, Buffer or Uint8Array");
|
||||
}
|
||||
if (typeof encoding === "function") {
|
||||
callback = encoding;
|
||||
encoding = null;
|
||||
}
|
||||
|
||||
// Ignore empty buffers, since writing them doesn't invoke the callback
|
||||
// https://github.com/nodejs/node/issues/22066
|
||||
if (data.length === 0) {
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Only write when we don't exceed the maximum body length
|
||||
if (this._requestBodyLength + data.length <= this._options.maxBodyLength) {
|
||||
this._requestBodyLength += data.length;
|
||||
this._requestBodyBuffers.push({ data: data, encoding: encoding });
|
||||
this._currentRequest.write(data, encoding, callback);
|
||||
}
|
||||
// Error when we exceed the maximum body length
|
||||
else {
|
||||
this.emit("error", new Error("Request body larger than maxBodyLength limit"));
|
||||
this.abort();
|
||||
}
|
||||
};
|
||||
|
||||
// Ends the current native request
|
||||
RedirectableRequest.prototype.end = function (data, encoding, callback) {
|
||||
// Shift parameters if necessary
|
||||
if (typeof data === "function") {
|
||||
callback = data;
|
||||
data = encoding = null;
|
||||
}
|
||||
else if (typeof encoding === "function") {
|
||||
callback = encoding;
|
||||
encoding = null;
|
||||
}
|
||||
|
||||
// Write data and end
|
||||
var currentRequest = this._currentRequest;
|
||||
this.write(data || "", encoding, function () {
|
||||
currentRequest.end(null, null, callback);
|
||||
});
|
||||
};
|
||||
|
||||
// Sets a header value on the current native request
|
||||
RedirectableRequest.prototype.setHeader = function (name, value) {
|
||||
this._options.headers[name] = value;
|
||||
this._currentRequest.setHeader(name, value);
|
||||
};
|
||||
|
||||
// Clears a header value on the current native request
|
||||
RedirectableRequest.prototype.removeHeader = function (name) {
|
||||
delete this._options.headers[name];
|
||||
this._currentRequest.removeHeader(name);
|
||||
};
|
||||
|
||||
// Proxy all other public ClientRequest methods
|
||||
[
|
||||
"abort", "flushHeaders", "getHeader",
|
||||
"setNoDelay", "setSocketKeepAlive", "setTimeout",
|
||||
].forEach(function (method) {
|
||||
RedirectableRequest.prototype[method] = function (a, b) {
|
||||
return this._currentRequest[method](a, b);
|
||||
};
|
||||
});
|
||||
|
||||
// Proxy all public ClientRequest properties
|
||||
["aborted", "connection", "socket"].forEach(function (property) {
|
||||
Object.defineProperty(RedirectableRequest.prototype, property, {
|
||||
get: function () { return this._currentRequest[property]; },
|
||||
});
|
||||
});
|
||||
|
||||
// Executes the next native request (initial or redirect)
|
||||
RedirectableRequest.prototype._performRequest = function () {
|
||||
// Load the native protocol
|
||||
var protocol = this._options.protocol;
|
||||
var nativeProtocol = this._options.nativeProtocols[protocol];
|
||||
if (!nativeProtocol) {
|
||||
this.emit("error", new Error("Unsupported protocol " + protocol));
|
||||
return;
|
||||
}
|
||||
|
||||
// If specified, use the agent corresponding to the protocol
|
||||
// (HTTP and HTTPS use different types of agents)
|
||||
if (this._options.agents) {
|
||||
var scheme = protocol.substr(0, protocol.length - 1);
|
||||
this._options.agent = this._options.agents[scheme];
|
||||
}
|
||||
|
||||
// Create the native request
|
||||
var request = this._currentRequest =
|
||||
nativeProtocol.request(this._options, this._onNativeResponse);
|
||||
this._currentUrl = url.format(this._options);
|
||||
|
||||
// Set up event handlers
|
||||
request._redirectable = this;
|
||||
for (var event in eventHandlers) {
|
||||
/* istanbul ignore else */
|
||||
if (event) {
|
||||
request.on(event, eventHandlers[event]);
|
||||
}
|
||||
}
|
||||
|
||||
// End a redirected request
|
||||
// (The first request must be ended explicitly with RedirectableRequest#end)
|
||||
if (this._isRedirect) {
|
||||
// Write the request entity and end.
|
||||
var i = 0;
|
||||
var buffers = this._requestBodyBuffers;
|
||||
(function writeNext() {
|
||||
if (i < buffers.length) {
|
||||
var buffer = buffers[i++];
|
||||
request.write(buffer.data, buffer.encoding, writeNext);
|
||||
}
|
||||
else {
|
||||
request.end();
|
||||
}
|
||||
}());
|
||||
}
|
||||
};
|
||||
|
||||
// Processes a response from the current native request
|
||||
RedirectableRequest.prototype._processResponse = function (response) {
|
||||
// Store the redirected response
|
||||
if (this._options.trackRedirects) {
|
||||
this._redirects.push({
|
||||
url: this._currentUrl,
|
||||
headers: response.headers,
|
||||
statusCode: response.statusCode,
|
||||
});
|
||||
}
|
||||
|
||||
// RFC7231§6.4: The 3xx (Redirection) class of status code indicates
|
||||
// that further action needs to be taken by the user agent in order to
|
||||
// fulfill the request. If a Location header field is provided,
|
||||
// the user agent MAY automatically redirect its request to the URI
|
||||
// referenced by the Location field value,
|
||||
// even if the specific status code is not understood.
|
||||
var location = response.headers.location;
|
||||
if (location && this._options.followRedirects !== false &&
|
||||
response.statusCode >= 300 && response.statusCode < 400) {
|
||||
// RFC7231§6.4: A client SHOULD detect and intervene
|
||||
// in cyclical redirections (i.e., "infinite" redirection loops).
|
||||
if (++this._redirectCount > this._options.maxRedirects) {
|
||||
this.emit("error", new Error("Max redirects exceeded."));
|
||||
return;
|
||||
}
|
||||
|
||||
// RFC7231§6.4: Automatic redirection needs to done with
|
||||
// care for methods not known to be safe […],
|
||||
// since the user might not wish to redirect an unsafe request.
|
||||
// RFC7231§6.4.7: The 307 (Temporary Redirect) status code indicates
|
||||
// that the target resource resides temporarily under a different URI
|
||||
// and the user agent MUST NOT change the request method
|
||||
// if it performs an automatic redirection to that URI.
|
||||
var header;
|
||||
var headers = this._options.headers;
|
||||
if (response.statusCode !== 307 && !(this._options.method in SAFE_METHODS)) {
|
||||
this._options.method = "GET";
|
||||
// Drop a possible entity and headers related to it
|
||||
this._requestBodyBuffers = [];
|
||||
for (header in headers) {
|
||||
if (/^content-/i.test(header)) {
|
||||
delete headers[header];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Drop the Host header, as the redirect might lead to a different host
|
||||
if (!this._isRedirect) {
|
||||
for (header in headers) {
|
||||
if (/^host$/i.test(header)) {
|
||||
delete headers[header];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Perform the redirected request
|
||||
var redirectUrl = url.resolve(this._currentUrl, location);
|
||||
debug("redirecting to", redirectUrl);
|
||||
Object.assign(this._options, url.parse(redirectUrl));
|
||||
this._isRedirect = true;
|
||||
this._performRequest();
|
||||
|
||||
// Discard the remainder of the response to avoid waiting for data
|
||||
response.destroy();
|
||||
}
|
||||
else {
|
||||
// The response is not a redirect; return it as-is
|
||||
response.responseUrl = this._currentUrl;
|
||||
response.redirects = this._redirects;
|
||||
this.emit("response", response);
|
||||
|
||||
// Clean up
|
||||
this._requestBodyBuffers = [];
|
||||
}
|
||||
};
|
||||
|
||||
// Wraps the key/value object of protocols with redirect functionality
|
||||
function wrap(protocols) {
|
||||
// Default settings
|
||||
var exports = {
|
||||
maxRedirects: 21,
|
||||
maxBodyLength: 10 * 1024 * 1024,
|
||||
};
|
||||
|
||||
// Wrap each protocol
|
||||
var nativeProtocols = {};
|
||||
Object.keys(protocols).forEach(function (scheme) {
|
||||
var protocol = scheme + ":";
|
||||
var nativeProtocol = nativeProtocols[protocol] = protocols[scheme];
|
||||
var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol);
|
||||
|
||||
// Executes a request, following redirects
|
||||
wrappedProtocol.request = function (options, callback) {
|
||||
if (typeof options === "string") {
|
||||
options = url.parse(options);
|
||||
options.maxRedirects = exports.maxRedirects;
|
||||
}
|
||||
else {
|
||||
options = Object.assign({
|
||||
protocol: protocol,
|
||||
maxRedirects: exports.maxRedirects,
|
||||
maxBodyLength: exports.maxBodyLength,
|
||||
}, options);
|
||||
}
|
||||
options.nativeProtocols = nativeProtocols;
|
||||
assert.equal(options.protocol, protocol, "protocol mismatch");
|
||||
debug("options", options);
|
||||
return new RedirectableRequest(options, callback);
|
||||
};
|
||||
|
||||
// Executes a GET request, following redirects
|
||||
wrappedProtocol.get = function (options, callback) {
|
||||
var request = wrappedProtocol.request(options, callback);
|
||||
request.end();
|
||||
return request;
|
||||
};
|
||||
});
|
||||
return exports;
|
||||
}
|
||||
|
||||
// Exports
|
||||
module.exports = wrap({ http: http, https: https });
|
||||
module.exports.wrap = wrap;
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"_from": "[email protected]",
|
||||
"_id": "[email protected]",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==",
|
||||
"_location": "/@slack/web-api/follow-redirects",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "version",
|
||||
"registry": true,
|
||||
"raw": "[email protected]",
|
||||
"name": "follow-redirects",
|
||||
"escapedName": "follow-redirects",
|
||||
"rawSpec": "1.5.10",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "1.5.10"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/@slack/web-api/axios"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz",
|
||||
"_shasum": "7b7a9f9aea2fdff36786a94ff643ed07f4ff5e2a",
|
||||
"_spec": "[email protected]",
|
||||
"_where": "/Users/stevengill/repo/slack-github-action/node_modules/@slack/web-api/node_modules/axios",
|
||||
"author": {
|
||||
"name": "Ruben Verborgh",
|
||||
"email": "[email protected]",
|
||||
"url": "https://ruben.verborgh.org/"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/follow-redirects/follow-redirects/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Olivier Lalonde",
|
||||
"email": "[email protected]",
|
||||
"url": "http://www.syskall.com"
|
||||
},
|
||||
{
|
||||
"name": "James Talmage",
|
||||
"email": "[email protected]"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"debug": "=3.1.0"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "HTTP and HTTPS modules that follow redirects.",
|
||||
"devDependencies": {
|
||||
"concat-stream": "^1.6.0",
|
||||
"coveralls": "^3.0.2",
|
||||
"eslint": "^4.19.1",
|
||||
"express": "^4.16.2",
|
||||
"mocha": "^5.0.0",
|
||||
"nyc": "^11.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
"create.js",
|
||||
"http.js",
|
||||
"https.js"
|
||||
],
|
||||
"homepage": "https://github.com/follow-redirects/follow-redirects",
|
||||
"keywords": [
|
||||
"http",
|
||||
"https",
|
||||
"url",
|
||||
"redirect",
|
||||
"client",
|
||||
"location",
|
||||
"utility"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"name": "follow-redirects",
|
||||
"nyc": {
|
||||
"reporter": [
|
||||
"lcov",
|
||||
"text"
|
||||
]
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://[email protected]/follow-redirects/follow-redirects.git"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint *.js test",
|
||||
"mocha": "nyc mocha",
|
||||
"test": "npm run lint && npm run mocha"
|
||||
},
|
||||
"version": "1.5.10"
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
{
|
||||
"_from": "@slack/web-api",
|
||||
"_id": "@slack/[email protected]",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-xT27bhYvkjidKCmGt3Dy4tx12Hk4oI9G/6vQFUdDXV1WSk50tysswHe67ckgcSU95yRPcnLVQicVpM3cAH6/AA==",
|
||||
"_location": "/@slack/web-api",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "tag",
|
||||
"registry": true,
|
||||
"raw": "@slack/web-api",
|
||||
"name": "@slack/web-api",
|
||||
"escapedName": "@slack%2fweb-api",
|
||||
"scope": "@slack",
|
||||
"rawSpec": "",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "latest"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER",
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/@slack/web-api/-/web-api-5.13.0.tgz",
|
||||
"_shasum": "44b3c744f8f2c75b188a928c1dcb51024ac8d4d4",
|
||||
"_spec": "@slack/web-api",
|
||||
"_where": "/Users/stevengill/repo/slack-github-action",
|
||||
"author": {
|
||||
"name": "Slack Technologies, Inc."
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/slackapi/node-slack-sdk/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"dependencies": {
|
||||
"@slack/logger": ">=1.0.0 <3.0.0",
|
||||
"@slack/types": "^1.7.0",
|
||||
"@types/is-stream": "^1.1.0",
|
||||
"@types/node": ">=8.9.0",
|
||||
"axios": "^0.19.0",
|
||||
"eventemitter3": "^3.1.0",
|
||||
"form-data": "^2.5.0",
|
||||
"is-stream": "^1.1.0",
|
||||
"p-queue": "^6.6.1",
|
||||
"p-retry": "^4.0.0"
|
||||
},
|
||||
"deprecated": false,
|
||||
"description": "Official library for using the Slack Platform's Web API",
|
||||
"devDependencies": {
|
||||
"@aoberoi/capture-console": "^1.1.0",
|
||||
"@microsoft/api-extractor": "^7.3.4",
|
||||
"@types/chai": "^4.1.7",
|
||||
"@types/mocha": "^5.2.6",
|
||||
"busboy": "^0.3.0",
|
||||
"chai": "^4.2.0",
|
||||
"codecov": "^3.2.0",
|
||||
"mocha": "^6.0.2",
|
||||
"nock": "^10.0.6",
|
||||
"nyc": "^14.1.1",
|
||||
"shelljs": "^0.8.3",
|
||||
"shx": "^0.3.2",
|
||||
"sinon": "^7.2.7",
|
||||
"source-map-support": "^0.5.10",
|
||||
"ts-node": "^8.0.3",
|
||||
"tsd": "^0.13.1",
|
||||
"tslint": "^5.13.1",
|
||||
"tslint-config-airbnb": "^5.11.1",
|
||||
"typescript": "^3.3.3333"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 8.9.0",
|
||||
"npm": ">= 5.5.1"
|
||||
},
|
||||
"files": [
|
||||
"dist/**/*"
|
||||
],
|
||||
"homepage": "https://slack.dev/node-slack-sdk/web-api",
|
||||
"keywords": [
|
||||
"slack",
|
||||
"web-api",
|
||||
"bot",
|
||||
"client",
|
||||
"http",
|
||||
"api",
|
||||
"proxy",
|
||||
"rate-limiting",
|
||||
"pagination"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "dist/index.js",
|
||||
"name": "@slack/web-api",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/slackapi/node-slack-sdk.git"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:clean && tsc",
|
||||
"build:clean": "shx rm -rf ./dist ./coverage ./.nyc_output",
|
||||
"coverage": "codecov -F webapi --root=$PWD",
|
||||
"lint": "tslint --project .",
|
||||
"prepare": "npm run build",
|
||||
"ref-docs:model": "api-extractor run",
|
||||
"test": "npm run build && npm run test:mocha && npm run test:types",
|
||||
"test:mocha": "nyc mocha --config .mocharc.json src/*.spec.js",
|
||||
"test:types": "tsd",
|
||||
"watch": "npx nodemon --watch 'src' --ext 'ts' --exec npm run build"
|
||||
},
|
||||
"tsd": {
|
||||
"directory": "test/types"
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"version": "5.13.0"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation. All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user