Implemented new APIs and resolved bugs in existing ones. Added functionality for song uploads and improved data retrieval in song-related endpoints. Enhanced overall API performance and ensured proper error handling.

This commit is contained in:
Aniket Yadav 2024-03-21 16:26:27 +05:30
parent fc5abc0432
commit ac2ce43707
172 changed files with 7447 additions and 25614 deletions

3
.gitignore vendored
View File

@ -1 +1,2 @@
node_modules/
node_modules
package-lock.json

View File

@ -1,4 +1,4 @@
const User = require('../models/user.model');
const {User} = require('../models/user.model');
const constant = require('../util/constant')
const bcrypt = require('bcryptjs');
const objectConverter = require('../util/objectConverter');
@ -6,86 +6,86 @@ const objectConverter = require('../util/objectConverter');
const createAdmin = async (req, res) => {
// const createAdmin = async (req, res) => {
try {
let user = await User.findOne({ userTypes: constant.userTypes.admin })
// try {
// let user = await User.findOne({ userTypes: constant.userTypes.admin })
if (user) {
console.log('Admin Already Created', user);
// if (user) {
// console.log('Admin Already Created', user);
return res.status(201).send({
message: 'Admin already created'
});
}
// return res.status(201).send({
// message: 'Admin already created'
// });
// }
let obj = {
email: req.body.email ? req.body.email : undefined,
password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
userName: 'Admin',
userTypes: constant.userTypes.admin
// let obj = {
// email: req.body.email ? req.body.email : undefined,
// password: req.body.password ? bcrypt.hashSync(req.body.password) : undefined,
// userName: 'Admin',
// userTypes: constant.userTypes.admin
}
if (req.file) {
const { filename, path } = req.file;
obj["image"] = {
fileName: filename,
fileAddress: path
}
}
// }
// if (req.file) {
// const { filename, path } = req.file;
// obj["image"] = {
// fileName: filename,
// fileAddress: path
// }
// }
console.log(obj);
await User.create(obj);
res.status(200).send({
errorCode: 200,
message: 'Admin Got Created'
})
console.log('Admin got created');
// console.log(obj);
// await User.create(obj);
// res.status(200).send({
// errorCode: 200,
// message: 'Admin Got Created'
// })
// console.log('Admin got created');
} catch (err) {
console.log(err);
res.status(500).send({
errorCode: 500,
message: 'Internal Error while creating Admin'
})
}
}
// } catch (err) {
// console.log(err);
// res.status(500).send({
// errorCode: 500,
// message: 'Internal Error while creating Admin'
// })
// }
// }
const getList = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const limit = parseInt(req.query.limit) || 5;
const skipIndex = (page - 1) * limit;
const searchQuery = req.query.search || ''; // Get search query from request query parameters
const searchQuery = req.query.search || '';
let obj = {
userTypes: constant.userTypes.customer
};
// Add search functionality
if (searchQuery) {
obj.$or = [
{ username: { $regex: searchQuery, $options: 'i' } }, // Case-insensitive search for username
{ email: { $regex: searchQuery, $options: 'i' } } // Case-insensitive search for email
{ username: { $regex: searchQuery, $options: 'i' } },
{ email: { $regex: searchQuery, $options: 'i' } }
];
}
const users = await User.find(obj)
.limit(limit)
.skip(skipIndex);
const totalCount = await User.countDocuments(obj);
.skip(skipIndex)
.lean(); // Convert to plain JavaScript objects for manipulation
const totalCount = await User.countDocuments(obj); // Get total count of matching documents
console.log('users', users)
return res.status(200).send({
status: 200,
message: 'Users retrieved successfully',
users: users,
total_users: totalCount, // Include total data count in the response
total_pages: Math.ceil(totalCount / limit),
current_page: page
});
} catch (err) {
console.error(err);
@ -98,6 +98,8 @@ const getList = async (req, res) => {
};
const update = async (req, res) => {
try {
const adminId = req.userId;
@ -304,7 +306,7 @@ const changePassword = async (req, res) => {
module.exports = {
createAdmin,
// createAdmin,
updateProfile,
getList,
adminProfile,

View File

@ -3,6 +3,8 @@ const Artist = require('../models/artist.model');
const createArtist = async (req, res) => {
try {
console.log(req,"=============================>123");
console.log(req.body,"hooooo")
const { ArtistName } = req.body;
// Check if the required fields are present in the request body
@ -21,7 +23,6 @@ const createArtist = async (req, res) => {
const baseUrl = `${req.protocol}://${req.get('host')}`;
const imagePath = `uploads/${req.file.filename}`;
const imageUrl = `${baseUrl}/${imagePath}`;
console.log("🚀 ~ createArtist ~ imageUrl:", imageUrl);
obj["image"] = {
fileName: req.file.filename,
@ -29,14 +30,13 @@ const createArtist = async (req, res) => {
};
obj["imageUrl"] = imageUrl;
}
// Save 'obj' to the database
const newArtist = await Artist.create(obj);
console.log("🚀 ~ createArtist ~ newArtist:", newArtist);
// Return a success response with the newly created Artist
return res.status(201).send({
error_code: 201,
return res.status(200).send({
error_code: 200,
message: "Artist created",
Artist: newArtist
});
@ -188,33 +188,55 @@ const changeArtistStatus = async (req, res) => {
}
};
const getAllArtist = async (req, res) => {
const allArtist =async(req,res)=>{
try {
// Pagination parameters
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
// Search query
const searchQuery = req.query.search || '';
// Fetch artists with pagination and search
const artistsQuery = Artist.find();
if (searchQuery) {
artistsQuery.where('ArtistName').regex(new RegExp(searchQuery, 'i'));
}
const artists = await artistsQuery.skip(skip).limit(limit);
// Count total number of artists for pagination
const totalCount = await Artist.countDocuments(artistsQuery.getQuery());
const artists = await Artist.find();
return res.status(200).json({
error_code: 200,
message: 'Artists fetched successfully',
artists
});
} catch (error) {
console.error('Error inside getAllArtist controller:', error);
return res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
}
const getAllArtist = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
// Build the query for fetching artists with pagination and search
const artistQuery = Artist.find({
ArtistName: { $regex: searchQuery, $options: 'i' }
});
// Execute the query with pagination
const artists = await artistQuery.skip(skip).limit(limit);
// Count total number of artists for pagination
const totalCount = await Artist.countDocuments({
ArtistName: { $regex: searchQuery, $options: 'i' }
});
res.json({
error_code: 200,
message: 'Artists retrieved successfully',
artists,
currentPage: page,
totalPages: Math.ceil(totalCount / limit)
total_count: totalCount,
page,
limit
});
} catch (error) {
console.error('Error inside getAllArtist controller:', error);
@ -225,10 +247,14 @@ const getAllArtist = async (req, res) => {
}
};
module.exports = {
createArtist,
updateArtist,
deleteArtist,
getArtistById,
changeArtistStatus, getAllArtist
changeArtistStatus, getAllArtist,
allArtist
};

View File

@ -346,8 +346,8 @@ const getAlbums = async (req, res) => {
{ shortDescription: { $regex: searchQuery, $options: 'i' } }
]
})
.populate('categoryId') // Populate categoryId field
.populate('subcategoryId') // Populate subcategoryId field
.populate('categoryId')
.populate('subcategoryId')
.skip(skip)
.limit(limit);
@ -386,6 +386,134 @@ const getAlbums = async (req, res) => {
};
// const getAlbums = async (req, res) => {
// try {
// // Pagination parameters
// const { page = 1, limit = 10 } = req.query;
// const skip = (page - 1) * limit;
// const searchQuery = req.query.search || '';
// const matchQuery = {
// SubCategoriesName: { $regex: searchQuery, $options: 'i' },
// 'CategoriesId.deleted': { $ne: true },
// 'subcategoryId.deleted':{$ne:true},
// 'deleted': { $ne: true }
// };
// // Aggregation pipeline to exclude albums with deleted categories or subcategories
// const albums = await Album.aggregate([
// {$match:matchQuery },
// {
// $lookup: {
// from: 'categories',
// localField: 'categoryId',
// foreignField: '_id',
// as: 'category'
// }
// },
// {
// $lookup: {
// from: 'subcategories',
// localField: 'subcategoryId',
// foreignField: '_id',
// as: 'subcategory'
// }
// },
// {
// $match: {
// $and: [
// { 'category': { $not: { $elemMatch: { 'deleted': true } } } }, // Exclude albums with deleted categories
// { 'subcategory': { $not: { $elemMatch: { 'deleted': true } } } } // Exclude albums with deleted subcategories
// ]
// }
// },
// { $skip: skip },
// { $limit: limit }
// ]);
// const totalCount = await Album.countDocuments({
// $or: [
// { albumName: { $regex: searchQuery, $options: 'i' } },
// { shortDescription: { $regex: searchQuery, $options: 'i' } }
// ]
// });
// const totalPages = Math.ceil(totalCount / limit);
// return res.status(200).json({
// error_code: 200,
// message: "Albums retrieved successfully",
// data: albums.map(album => ({
// _id: album._id,
// status: album.status,
// image: album.image,
// imageUrl: album.imageUrl,
// albumName: album.albumName,
// shortDescription: album.shortDescription,
// category: album.category[0] ? album.category[0].name : null,
// subcategory: album.subcategory[0] ? album.subcategory[0].SubCategoriesName : null
// })),
// totalPages: totalPages,
// currentPage: page
// });
// } catch (err) {
// console.log("Error inside GetAlbums Controller", err);
// return res.status(500).json({
// error_code: 500,
// message: "Internal Server Error"
// });
// }
// };
const allAlbums =async(req,res)=>{
try {
const albums = await Album.find();
return res.status(200).json({
error_code: 200,
message: 'Albums fetched successfully',
albums
});
} catch (error) {
console.log("Error inside GetAlbums Controller", err);
return res.status(500).json({
error_code: 500,
message: "Internal Server Error"
});
}
}
const getsubcategories = async (req, res) => {
try {
const { subcategoryId } = req.params;
const subCategories = await Album.find({ subcategoryId: subcategoryId });
if (!subCategories || subCategories.length === 0) {
return res.status(400).send({
error_code: 400,
message: 'subCategories not found for the given subCategories ID'
});
}
res.status(200).json({
error_code: 200,
message: 'Categories retrieved successfully',
subCategories: subCategories
});
} catch (err) {
console.error('Error inside getCategories', err);
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
}
};
@ -395,7 +523,9 @@ module.exports = {
deleteAlbum,
changeAlbumStatus,
getAlbums,
deletMany
allAlbums,
deletMany,
getsubcategories
}

View File

@ -1,97 +1,251 @@
const bcrypt = require('bcryptjs');
const User = require('../models/user.model');
const { User } = require('../models/user.model');
const multer = require('multer');
const jwt = require('jsonwebtoken');
const authConfig = require('../configs/auth.config');
const constant = require('../util/constant')
const nodemailer = require('nodemailer');
const signUp = async(req,res) => {
const sendOTPByEmail = async (email, otp) => {
try {
const obj = {
name : req.body.name,
password : bcrypt.hashSync(req.body.password,8),
email : req.body.email,
registerWith : constant.registerWith.Email
}
const generateOTP = () => {
return Math.floor(10000 + Math.random() * 90000);
}
const email = req.body.email;
const otp = generateOTP();
obj['otp'] = otp;
const user = await User.create(obj);
const transporter = nodemailer.createTransport({
service: 'Gmail', // e.g., 'Gmail'
service: 'gmail', // e.g., 'Gmail'
auth: {
user: 'checkdemo02@gmail.com',
pass: 'vqdoqmekygtousli'
user: 'ay2087355@gmail.com',
pass: 'phbcdqcqdvsgdlsb'
}
});
const mailOptions = {
from: 'checkdemo02@gmail.com',
to: req.body.email, // The user's email
to: email,
subject: 'Your OTP Code',
text: `Your OTP code is: ${otp}`
};
// Send the email
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending OTP email:', error);
return res.status(500).send({
errorCode : 500,
message : "Mail not Send"
})
} else {
const info = await transporter.sendMail(mailOptions);
console.log('OTP email sent:', info.response);
return info.response;
} catch (error) {
console.error('Error sending OTP email:', error);
throw error;
}
};
const generateOTP = () => {
return Math.floor(10000 + Math.random() * 90000);
};
const signUp = async (req, res) => {
try {
const { name, email, password, confirmPassword } = req.body;
if (password !== confirmPassword) {
return res.status(400).send({
error_code: 400,
message: 'Password and confirm password do not match'
});
const token = jwt.sign({id:user._id},authConfig.secretKey,{
expiresIn : 6000000
}
let existingUser = await User.findOne({ email: email });
if (existingUser) {
if (existingUser.otpVerifly == true) {
return res.status(401).send({
error_code: 401,
message: 'Email already registered'
});
}
if (existingUser.otpVerifly == false) {
existingUser.password = bcrypt.hashSync(password, 8);
existingUser.otp = generateOTP();
// Send OTP email
await sendOTPByEmail(email, existingUser.otp);
return res.status(201).send({
// Save updated user
existingUser = await existingUser.save();
return res.status(200).send({
error_code: 200,
message : 'Success',
otp : otp,
accessToken : token
})
message: 'User registered successfully. ',
email: email,
otp: existingUser.otp,
});
}
} else {
// Create new user
const obj = {
name: name,
password: bcrypt.hashSync(password, 8),
email: email,
registerWith: constant.registerWith.Email,
otp: generateOTP() // Assuming generateOTP() function is defined
};
// Send OTP email
await sendOTPByEmail(email, obj.otp);
// Create new user
const user = await User.create(obj);
return res.status(200).send({
error_code: 200,
message: 'User registered successfully. ',
email: email,
otp: obj.otp,
});
}
} catch (err) {
console.log(err);
console.error(err);
res.status(500).send({
error_code : 200,
error_code: 500,
message: 'Failed'
})
}
});
}
};
// const signUp = async (req, res) => {
// try {
// const obj = {
// name: req.body.name,
// password: bcrypt.hashSync(req.body.password, 8),
// email: req.body.email,
// registerWith: constant.registerWith.Email
// }
// const generateOTP = () => {
// return Math.floor(10000 + Math.random() * 90000);
// }
// const email = req.body.email;
// const otp = generateOTP();
// obj['otp'] = otp;
// const user = await User.create(obj);
// const transporter = nodemailer.createTransport({
// service: 'gmail', // e.g., 'Gmail'
// auth: {
// user: 'ay2087355@gmail.com',
// pass: 'phbcdqcqdvsgdlsb'
// }
// });
// const mailOptions = {
// from: 'checkdemo02@gmail.com',
// to: req.body.email, // The user's email
// subject: 'Your OTP Code',
// text: `Your OTP code is: ${otp}`
// };
// // Send the email
// transporter.sendMail(mailOptions, (error, info) => {
// if (error) {
// console.error('Error sending OTP email:', error);
// return res.status(500).send({
// errorCode: 500,
// message: "Mail not Send"
// })
// } else {
// console.log('OTP email sent:', info.response);
// }
// });
// return res.status(201).send({
// error_code: 200,
// message: 'Success',
// email: email,
// otp: otp,
// })
// } catch (err) {
// console.log(err);
// res.status(500).send({
// error_code: 200,
// message: 'Failed'
// })
// }
// }
// const signIn = async (req, res) => {
// try {
// console.log(req.body,"===================================>123")
// const { email, password } = req.body;
// if (!email){
// return res.status(400).json({
// error_code: 400,
// message: 'Email is required'
// });
// }
// if (!password){
// return res.status(400).json({
// error_code: 400,
// message: 'Password is required'
// });
// }
// const user = await User.findOne({ email });
// console.log("🚀 ~ signIn ~ user:", user)
// // console.log("🚀 ~ signIn ~ user:", user)
// if (!user) {
// return res.status(404).json({
// error_code: 404,
// message: 'User not found'
// });
// }
// const isPasswordValid = bcrypt.compareSync(password, user.password);
// if (!isPasswordValid) {
// return res.status(401).json({
// error_code: 401,
// message: 'Password is incorrect'
// });
// }
// const token = jwt.sign({ id: user._id,userTypes:user.userTypes }, authConfig.secretKey, { expiresIn: '1h' });
// console.log("🚀 ~ signIn ~ token:", token)
// return res.status(200).json({
// error_code: 200,
// message: 'User logged in successfully',
// accessToken: token
// });
// } catch (err) {
// console.error('Error inside signIn:', err);
// return res.status(500).json({
// error_code: 500,
// message: 'Internal Server Error'
// });
// }
// };
const signIn = async (req, res) => {
try {
const { email, password } = req.body;
const email = req.body.email;
const password = req.body.password;
if (!email){
if (!email || !password) {
return res.status(400).json({
error_code: 400,
message: 'Email is required'
});
}
if (!password){
return res.status(400).json({
error_code: 400,
message: 'Password is required'
message: 'Email and password are required'
});
}
// Find user by email
const user = await User.findOne({ email });
console.log("🚀 ~ signIn ~ user:", user)
if (!user) {
return res.status(404).json({
@ -100,18 +254,23 @@ const signIn = async (req, res) => {
});
}
// Check if the provided password matches the user's password
const isPasswordValid = bcrypt.compareSync(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({
error_code: 401,
message: 'Password is incorrect'
});
}
if (user.otpVerifly === false) {
return res.status(401).json({
error_code: 401,
message: 'User has not been verified with OTP'
});
}
// Generate JWT token
const token = jwt.sign({ id: user._id, userTypes: user.userTypes }, authConfig.secretKey, { expiresIn: '1h' });
console.log("🚀 ~ signIn ~ token:", token)
// console.log("🚀 ~ signIn ~ token:", token)
return res.status(200).json({
error_code: 200,
@ -128,34 +287,179 @@ const signIn = async (req, res) => {
};
const verifyOtp = async(req,res,next) => {
// const verifyOtp = async(req,res,next) => {
// try{
// const otp = req.body.otp;
// const user = await User.findOne({_id:req.userId});
// // console.log(user.otp,"otp");
// if(user.otp!=otp){
// return res.status(400).send({
// error_code : 400,
// message : 'otp is incorrect'
// })
// }
// user.otpVerifly = true;
// await user.save();
// return res.status(200).send({
// error_code : 200,
// message : 'otp Verified'
// })
// }catch(err){
// console.log('Error inside verifyOtp Controller',err);
// return res.status(500).send({
// message : 'Internal Error',
// error_code : 500,
// })
// }
// }
const verifyOtp = async (req, res) => {
try {
const otp = req.body.otp;
const user = await User.findOne({_id:req.userId});
console.log(user.otp,otp);
if(user.otp!=otp){
return res.status(400).send({
const { email, otp } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({
error_code: 400,
message : 'otp is incorrect'
})
message: 'User not found'
});
}
return res.status(200).send({
if (user.otp !== otp) {
return res.status(400).json({
error_code: 400,
message: 'Incorrect OTP'
});
}
user.otpVerifly = true;
await user.save();
return res.status(200).json({
error_code: 200,
message : 'otp Verified'
})
message: 'OTP verified successfully',
});
}catch(err){
console.log('Error inside verifyOtp Controller',err);
return res.status(500).send({
message : 'Internal Error',
} catch (error) {
console.error('Error in verify OTP:', error);
return res.status(500).json({
error_code: 500,
})
message: 'Failed'
});
}
};
const resendOTP = async (req, res) => {
try {
const { email } = req.body;
const existingUser = await User.findOne({ email: email });
if (!existingUser) {
return res.status(404).json({
error_code: 404,
message: 'User not found'
});
}
// if (!existingUser.otpVerifly) {
// return res.status(400).json({
// error_code: 400,
// message: 'OTP verification is not enabled for this user'
// });
// }
const newOTP = generateOTP();
existingUser.otp = newOTP;
await existingUser.save();
await sendOTPByEmail(email, newOTP);
return res.status(200).json({
error_code: 200,
message: 'OTP resent successfully'
});
} catch (err) {
console.error('Error inside resendOTP:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
const forgotPassword = async (req, res) => {
try {
console.log(req.body, "sahgasdh")
const { email } = req.body;
const user = await User.findOne({ email: email });
console.log("🚀 ~ forgotPassword ~ user:", user)
if (!user) {
return res.status(404).json({
error_code: 404,
message: 'User not found'
});
}
const otp = generateOTP();
user.otp = otp;
await user.save();
await sendOTPByEmail(email, otp);
return res.status(200).json({
error_code: 200,
message: 'OTP sent to user\'s email successfully',
otp
});
} catch (err) {
console.error('Error inside forgotPassword:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
const resetPassword = async (req, res) => {
try {
const { email, newPassword, confirmPassword } = req.body;
if (newPassword !== confirmPassword) {
return res.status(400).json({
error_code: 400,
message: 'New password and confirm password do not match'
});
}
const user = await User.findOne({ email: email });
if (!user) {
return res.status(404).json({
error_code: 404,
message: 'User not found'
});
}
user.password = bcrypt.hashSync(newPassword, 8);
await user.save();
return res.status(200).json({
error_code: 200,
message: 'Password reset successfully'
});
} catch (err) {
console.error('Error inside resetPassword:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
module.exports = {
signIn,
signUp,
verifyOtp
verifyOtp,
resendOTP, forgotPassword, resetPassword
}

View File

@ -4,7 +4,10 @@ const Category = require('../models/categories.model');
const createCategories = async (req, res) => {
try {
if (!req.body.categoriesName) {
console.log(req.body)
const name =req.body;
if (!req.body.name) {
return res.status(400).send({
error_code: 400,
message: "Category name is required"
@ -12,7 +15,7 @@ const createCategories = async (req, res) => {
}
let obj = {
name: req.body.categoriesName,
name: req.body.name ,
};
if (req.file) {

View File

@ -8,17 +8,17 @@ const createLanguage = async function (req, res) {
}
if (!obj.language) {
return res.status(400).json({ error: "Language name is required" });
return res.status(400).json({ error_code: 400,message: "Language name is required" });
}
// Call the model function to create language using obj.language
const language = await Language.create({ name: obj.language });
// If language is created successfully, send a success response
res.status(201).json({ message: "Language created successfully", language });
res.status(200).json({ error_code: 200,message: "Language created successfully", language });
} catch (error) {
console.error('Error creating language:', error);
res.status(500).json({ error: 'Failed to create language' });
res.status(500).json({ error_code: 500,message: 'Failed to create language' });
}
};
@ -30,17 +30,17 @@ const updateLanguage = async function (req, res) {
// Check if languageId is provided
if (!languageId) {
return res.status(400).json({ error: "Language ID is required" });
return res.status(400).json({ error_code: 400,error: "Language ID is required" });
}
// Find the language by ID and update its name
const language = await Language.findByIdAndUpdate(languageId, { name }, { new: true });
if (!language) {
return res.status(404).json({ error: "Language not found" });
return res.status(404).json({ error_code: 404,message: "Language not found" });
}
res.json({ message: "Language updated successfully", language });
res.status(200).json({ error_code: 200,message: "Language updated successfully", language });
} catch (error) {
console.error('Error updating language:', error);
res.status(500).json({ error: 'Failed to update language' });
@ -52,25 +52,25 @@ const deleteLanguage = async function (req, res) {
const languageId = req.params.id;
if (!languageId) {
return res.status(400).json({ error: "Language ID is required" });
return res.status(400).json({ error_code: 400,message: "Language ID is required" });
}
const language = await Language.findByIdAndDelete(languageId);
if (!language) {
return res.status(404).json({ error: "Language not found" });
return res.status(404).json({error_code: 404, message: "Language not found" });
}
res.json({ message: "Language deleted successfully" });
} catch (error) {
console.error('Error deleting language:', error);
res.status(500).json({ error: 'Failed to delete language' });
res.status(500).json({ error_code: 500,message: 'Failed to delete language' });
}
};
const getLanguage = async function (req, res) {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const limit = parseInt(req.query.limit) || 5;
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
@ -96,7 +96,7 @@ const getLanguage = async function (req, res) {
});
} catch (error) {
console.error('Error getting languages:', error);
res.status(500).json({ error: 'Failed to get languages' });
res.status(500).json({ error_code: 500,message: 'Failed to get languages' });
}
};
@ -115,6 +115,7 @@ const changeLanguageStatus = async function (req, res) {
await languageData.save();
res.status(200).send({
error_code: 200,
message: `ads status toggled successfully to ${languageData.status}`,
user: languageData
});
@ -127,10 +128,27 @@ const changeLanguageStatus = async function (req, res) {
}
};
//get alllanguage without pegination
const getAllLanguage = async function (req, res) {
try {
const languages = await Language.find();
res.json({
error_code: 200,
message: 'Languages retrieved successfully',
languages
});
} catch (error) {
console.error('Error getting languages:', error);
res.status(500).json({ error_code: 500,message: 'Failed to get languages' });
}
};
module.exports = {
createLanguage,
updateLanguage,
deleteLanguage,
changeLanguageStatus,
getLanguage
getLanguage,
getAllLanguage
};

View File

@ -5,20 +5,72 @@ const User = require('../models/user.model');
const userConst = require('../util/constant')
// const createNotification = async (req, res) => {
// try {
// const { sendTo, Type, Title, message, user } = req.body;
// // Validate sendTo value
// if (!sendTo || !['toAll', 'host', 'specific'].includes(sendTo)) {
// return res.status(400).json({ error_code: 400, message: 'Invalid sendTo value' });
// }
// let recipients = [];
// // Determine recipients based on sendTo value
// if (sendTo === 'toAll') {
// recipients = await User.find().distinct('_id');
// } else if (sendTo === 'host') {
// const host = await User.findOne({ role: 'host' });
// if (host) recipients = [host._id];
// } else if (sendTo === 'specific') {
// recipients = await User.find({ role: 'specificRole' }).distinct('_id');
// }
// const newNotification = new Notification({
// sendTo,
// Type,
// Title,
// message,
// user,
// recipients
// });
// const savedNotification = await newNotification.save();
// return res.status(201).json({
// error_code: 200,
// message: 'Notification created successfully',
// notification: savedNotification
// });
// } catch (err) {
// console.error('Error inside createNotification controller:', err);
// return res.status(500).json({
// error_code: 500,
// message: 'Internal Server Error'
// });
// }
// };
const createNotification = async (req, res) => {
try {
const { sendTo, Type, Title, message, user } = req.body;
// Validate sendTo value
if (!sendTo || !['toAll', 'host', 'specific'].includes(sendTo)) {
return res.status(400).json({ error_code: 400, message: 'Invalid sendTo value' });
}
let recipients = [];
// Determine recipients based on sendTo value
if (sendTo === 'toAll') {
recipients = await User.find().distinct('_id');
await Promise.all(recipients.map(async (userId) => {
const newNotification = new Notification({
sendTo,
Type,
Title,
message,
user: userId,
});
console.log("🚀 ~ awaitPromise.all ~ newNotification:", newNotification)
await newNotification.save();
}));
} else if (sendTo === 'host') {
const host = await User.findOne({ role: 'host' });
if (host) recipients = [host._id];
@ -33,6 +85,7 @@ const createNotification = async (req, res) => {
user,
recipients
});
const savedNotification = await newNotification.save();
return res.status(201).json({
@ -51,10 +104,11 @@ const createNotification = async (req, res) => {
const getNotifications = async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const limit = parseInt(req.query.limit) || 10;
const skip = (page - 1) * limit;
const searchQuery = req.query.search || '';
@ -125,6 +179,23 @@ const getNotificationId = async(req,res)=>{
}
}
//delete all notifications
const deleteAllNotifications = async (req, res) => {
try {
await Notification.deleteMany({});
res.status(200).json({
error_code: 200,
message: 'All notifications deleted successfully'
});
} catch (err) {
console.error('Error inside deleteAllNotifications controller:', err);
res.status(500).json({
error_code: 500,
message: 'Internal Server Error'
});
}
};
@ -132,7 +203,8 @@ const getNotificationId = async(req,res)=>{
module.exports = {
createNotification,
getNotifications,
deleteNotification,getNotificationId
deleteNotification,getNotificationId,
deleteAllNotifications
};

View File

@ -1,35 +1,83 @@
const PlayList = require('../models/playlist.model');
const User = require('../models/user.model');
const Song = require('../models/song.model');
const { User } = require('../models/user.model');
// const createPlaylist = async (req, res) => {
// try {
// console.log(req.body);
// let obj = {
// name: req.body.name ? req.body.name : undefined,
// songs: req.body.songs ? req.body.songs : undefined,
// userId: req.userId
// }
// const created_playlist = await PlayList.create(obj);
// const user = await User.findById(req.userId);
// await user.playlist.push(created_playlist._id);
// await user.save();
// return res.status(201).send({
// error_code: 200,
// message: 'Playlist got created'
// })
// } catch (err) {
// console.log('Error inside createPlaylist ', err);
// return res.status(500).send({
// error_code: 500,
// message: 'Internal Server Error'
// })
// }
// }
const createPlaylist = async (req, res) => {
try {
console.log(req.body);
// Check if songs are provided in the request body
if (!req.body.songs) {
return res.status(400).send({
error_code: 400,
message: 'Songs must be provided'
});
}
// Convert a single song ID to an array
const songIds = Array.isArray(req.body.songs) ? req.body.songs : [req.body.songs];
// Check if all songs exist
const songs = await Song.find({ _id: { $in: songIds } });
if (songs.length !== songIds.length) {
return res.status(400).send({
error_code: 400,
message: 'One or more songs do not exist'
});
}
let obj = {
name: req.body.name ? req.body.name : undefined,
songs : req.body.songs ? req.body.songs : undefined,
songs: songIds,
userId: req.userId
}
};
const created_playlist = await PlayList.create(obj);
const user = await User.findById(req.userId);
await user.playlist.push(created_playlist._id);
await user.save();
return res.status(201).send({
error_code: 200,
message : 'Playlist got created'
})
message: 'Playlist created successfully'
});
}catch(err)
{
} catch (err) {
console.log('Error inside createPlaylist ', err);
return res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
})
}
});
}
};
const addSong = async (req, res) => {
@ -65,8 +113,7 @@ const removeSong = async(req,res) => {
let playlist = await PlayList.findById(req.params.id);
console.log(playlist);
for (let i = 0; playlist.songs.length; i++) {
if(playlist.songs[i]==req.body.song)
{
if (playlist.songs[i] == req.body.song) {
playlist.songs.splice(i, 1);
await playlist.save();
return res.status(201).send({

View File

@ -5,78 +5,291 @@ const Subcategory = require('../models/subcategories.model');
const Album = require('../models/album.model');
const Artist = require('../models/artist.model')
const Language = require('../models/language.model')
// const createSong = async (req, res) => {
// try {
// const {
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// musicLink,
// trackerID,
// lyrics,
// languageId
// } = req.body;
// const { coverArtImage, musicFile } = req.files;
// const [category, subcategory, album, artist, language] = await Promise.all([
// Category.findById(categoryId),
// Subcategory.findById(subcategoryId),
// Album.findById(albumId),
// Artist.findById(artistId),
// Language.findById(languageId)
// ]);
// if (!category || !subcategory || !album || !artist || !language) {
// const missingEntities = [];
// if (!category) missingEntities.push('Category');
// if (!subcategory) missingEntities.push('Subcategory');
// if (!album) missingEntities.push('Album');
// if (!artist) missingEntities.push('Artist');
// if (!language) missingEntities.push('Language');
// const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
// return res.status(404).json({ error_code: 404, message: errorMessage });
// }
// const coverArtImagePath = coverArtImage[0].path;
// const musicFilePath = musicFile[0].path;
// const baseUrl = `${req.protocol}://${req.get('host')}`;
// const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
// const newSong = await Song.create({
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// musicLink,
// trackerID,
// lyrics,
// languageId,
// coverArtImage: {
// filename: coverArtImage[0].filename,
// fileAddress: coverArtImagePath,
// imageUrl: coverArtImageUrl
// },
// musicFile: {
// filename: musicFile[0].filename,
// fileAddress: musicFilePath
// }
// });
// return res.status(201).json({
// error_code: 200,
// message: 'Song created successfully',
// song: newSong
// });
// } catch (err) {
// console.error('Error inside createSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
// const createSong = async (req, res) => {
// try {
// const {
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// languageId,
// type,
// musicLink,
// trackerID,
// lyrics
// } = req.body;
// if (!type || !['1', '2'].includes(type)) {
// return res.status(400).json({ error_code: 400, message: 'Invalid or missing type parameter' });
// }
// let musicFilePath;
// let musicFileUrl; // Define a variable to store the URL of the music file
// if (type === '1') {
// if (!musicLink || !trackerID) {
// return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
// }
// } else if (type === '2') {
// if (!req.files || !req.files.musicFile) {
// return res.status(400).json({ error_code: 400, message: 'Music file is required' });
// }
// if (!Array.isArray(req.files.musicFile) || req.files.musicFile.length === 0) {
// return res.status(400).json({ error_code: 400, message: 'Invalid music file provided' });
// }
// musicFilePath = req.files.musicFile[0].path;
// musicFileUrl = `${req.protocol}://${req.get('host')}/${musicFilePath}`; // Construct the URL of the music file
// }
// const { coverArtImage } = req.files;
// const coverArtImagePath = coverArtImage[0].path;
// const coverArtImageUrl = `${req.protocol}://${req.get('host')}/${coverArtImagePath}`;
// const [category, subcategory, album, artist, language] = await Promise.all([
// Category.findById(categoryId),
// Subcategory.findById(subcategoryId),
// Album.findById(albumId),
// Artist.findById(artistId),
// Language.findById(languageId)
// ]);
// if (![category, subcategory, album, artist, language].every(entity => entity)) {
// const missingEntities = ['Category', 'Subcategory', 'Album', 'Artist', 'Language']
// .filter((entity, index) => ![category, subcategory, album, artist, language][index]);
// const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
// return res.status(404).json({ error_code: 404, message: errorMessage });
// }
// let newSong;
// if (type === '1') {
// newSong = await Song.create({
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// languageId,
// musicLink,
// trackerID,
// coverArtImage: {
// filename: coverArtImage[0].filename,
// fileAddress: coverArtImagePath,
// imageUrl: coverArtImageUrl
// },
// });
// } else if (type === '2') {
// newSong = await Song.create({
// categoryId,
// subcategoryId,
// albumId,
// artistId,
// title,
// languageId,
// lyrics,
// coverArtImage: {
// filename: coverArtImage[0].filename,
// fileAddress: coverArtImagePath,
// imageUrl: coverArtImageUrl
// },
// musicFile: {
// filename: req.files.musicFile[0].filename,
// fileAddress: musicFilePath,
// url: musicFileUrl // Include the URL of the music file in the database
// }
// });
// }
// return res.status(201).json({
// error_code: 200,
// message: 'Song created successfully',
// song: newSong
// });
// } catch (err) {
// console.error('Error inside createSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
const createSong = async (req, res) => {
try {
console.log(req.body,"ehjyqgfe")
const {
categoryId,
subcategoryId,
albumId,
artistId,
title,
languageId,
type,
musicLink,
trackerID,
lyrics,
languageId
lyrics
} = req.body;
const { coverArtImage, musicFile } = req.files;
if (!type || !['1', '2'].includes(type)) {
return res.status(400).json({ error_code: 400, message: 'Invalid or missing type parameter' });
}
// Check if both cover art image and music file are provided
let musicFilePath;
let musicFileUrl;
if (type === '1') {
if (!musicLink || !trackerID) {
return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
}
} else if (type === '2') {
if (!req.files || !req.files.musicFile) {
return res.status(400).json({ error_code: 400, message: 'Music file is required' });
}
// Find all related documents in parallel
const [category, subcategory, album, artist, language] = await Promise.all([
if (!Array.isArray(req.files.musicFile) || req.files.musicFile.length === 0) {
return res.status(400).json({ error_code: 400, message: 'Invalid music file provided' });
}
musicFilePath = req.files.musicFile[0].path;
musicFileUrl = `${req.protocol}://${req.get('host')}/${musicFilePath}`;
}
console.log("🚀 ~ createSong ~ musicFilePath:", musicFilePath)
const { coverArtImage } = req.files;
const coverArtImagePath = coverArtImage[0].path;
const coverArtImageUrl = `${req.protocol}://${req.get('host')}/${coverArtImagePath}`;
const [category, subcategory, album, language] = await Promise.all([
Category.findById(categoryId),
Subcategory.findById(subcategoryId),
Album.findById(albumId),
Artist.findById(artistId),
Language.findById(languageId)
]);
// Check if all related documents exist
if (!category || !subcategory || !album || !artist || !language) {
const missingEntities = [];
if (!category) missingEntities.push('Category');
if (!subcategory) missingEntities.push('Subcategory');
if (!album) missingEntities.push('Album');
if (!artist) missingEntities.push('Artist');
if (!language) missingEntities.push('Language');
if (![category, subcategory, album, language].every(entity => entity)) {
const missingEntities = ['Category', 'Subcategory', 'Album', 'Language']
.filter((entity, index) => ![category, subcategory, album, language][index]);
const errorMessage = `The following entities were not found: ${missingEntities.join(', ')}.`;
return res.status(404).json({ error_code: 404, message: errorMessage });
return res.status(402 ).json({ error_code: 402, message: errorMessage });
}
// Extract file paths
const coverArtImagePath = coverArtImage[0].path;
const musicFilePath = musicFile[0].path;
const artistIdsArray = artistId.split(',').map(id => id.trim());
console.log("🚀 ~ createSong ~ artistIdsArray:", artistIdsArray)
// Construct the image URL for cover art
const baseUrl = `${req.protocol}://${req.get('host')}`;
const coverArtImageUrl = `${baseUrl}/${coverArtImagePath}`;
let newSong;
// Create the new song
const newSong = await Song.create({
if (type === '1') {
newSong = await Song.create({
categoryId,
subcategoryId,
albumId,
artistId,
artistId: artistIdsArray,
title,
languageId,
musicLink,
trackerID,
lyrics,
languageId,
coverArtImage: {
filename: coverArtImage[0].filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl // Add imageUrl to coverArtImage object
imageUrl: coverArtImageUrl
},
});
} else if (type === '2') {
newSong = await Song.create({
categoryId,
subcategoryId,
albumId,
artistId: artistIdsArray,
title,
languageId,
lyrics,
coverArtImage: {
filename: coverArtImage[0].filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl
},
musicFile: {
filename: musicFile[0].filename,
fileAddress: musicFilePath
filename: req.files.musicFile[0].filename,
fileAddress: musicFilePath,
url: musicFileUrl // Include the URL of the music file in the database
}
});
}
console.log("🚀 ~ createSong ~ newSong:", newSong)
// Return success response with the new song
return res.status(201).json({
return res.status(200).json({
error_code: 200,
message: 'Song created successfully',
song: newSong
@ -85,18 +298,113 @@ const createSong = async (req, res) => {
console.error('Error inside createSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
// const updateSong = async (req, res) => {
// try {
// const { id } = req.params;
// const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true });
// if (!updatedSong) {
// return res.status(404).json({ error_code: 404, message: 'Song not found' });
// }
// return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
// } catch (err) {
// console.error('Error inside updateSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
const updateSong = async (req, res) => {
try {
const { id } = req.params; // Extract the song ID from the request parameters
const updatedSong = await Song.findByIdAndUpdate(id, req.body, { new: true }); // Find song by ID and update with the request body data
console.log(req.params,"dshgudgf")
const {_id} = req.params;
// console.log("🚀 ~ updateSong ~ songId:", songId)
const song = await Song.findById(_id);
console.log("🚀 ~ updateSong ~ song:", song)
if (!song) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
const {
categoryId,
subcategoryId,
albumId,
artistId,
title,
languageId,
type,
musicLink,
trackerID,
lyrics
} = req.body;
const updates = {};
// Input validation
if (categoryId) updates.categoryId = categoryId;
if (subcategoryId) updates.subcategoryId = subcategoryId;
if (albumId) updates.albumId = albumId;
if (artistId) {
updates.artistId = artistId.split(',').map(id => id.trim());
}
if (title) updates.title = title;
if (languageId) updates.languageId = languageId;
if (type) {
if (!['1', '2'].includes(type)) {
return res.status(400).json({ error_code: 400, message: 'Invalid type parameter' });
}
updates.type = type;
if (type === '1') {
if (!musicLink || !trackerID) {
return res.status(400).json({ error_code: 400, message: 'Music link and tracker ID are required for type 1' });
}
updates.musicLink = musicLink;
updates.trackerID = trackerID;
} else if (type === '2') {
// if (!req.files || !req.files.musicFile) {
// return res.status(400).json({ error_code: 400, message: 'Music file is required' });
// }
if (req.files && req.files.musicFile) {
const musicFilePath = req.files.musicFile[0].path;
const musicFileUrl = `${req.protocol}://${req.get('host')}/uploads/${musicFilePath}`;
updates.musicFile = {
filename: req.files.musicFile[0].filename,
fileAddress: musicFilePath,
url: musicFileUrl
};
}
}
}
if (lyrics !== undefined) updates.lyrics = lyrics;
// Update cover art image if provided
if (req.files && req.files.coverArtImage) {
const coverArtImage = req.files.coverArtImage[0];
const coverArtImagePath = coverArtImage.path;
const coverArtImageUrl = `${req.protocol}://${req.get('host')}/uploads/${coverArtImagePath}`;
updates.coverArtImage = {
filename: coverArtImage.filename,
fileAddress: coverArtImagePath,
imageUrl: coverArtImageUrl
};
}
// Perform the update and return the updated song
const updatedSong = await Song.findByIdAndUpdate(_id, updates, { new: true });
if (!updatedSong) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song updated successfully', song: updatedSong });
return res.status(200).json({
error_code: 200,
message: 'Song updated successfully',
song: updatedSong
});
} catch (err) {
console.error('Error inside updateSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
@ -104,6 +412,8 @@ const updateSong = async (req, res) => {
};
const deleteSong = async (req, res) => {
try {
const { id } = req.params;
@ -117,19 +427,81 @@ const deleteSong = async (req, res) => {
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
}
};
// const getSong = async (req, res) => {
// try {
// const { id } = req.params;
// const song = await Song.findById(id)
// .populate('languageId', 'name')
// .populate('artistId', 'ArtistName')
// .select('title musicLink trackerID lyrics coverArtImage');
// if (!song) {
// return res.status(404).json({ error_code: 404, message: 'Song not found' });
// }
// const { languageId, artistId, musicLink, trackerID, lyrics } = song;
// const languageName = languageId ? languageId.name : null;
// const artistName = artistId ? artistId.ArtistName : null;
// const imageUrl = song.coverArtImage ? song.coverArtImage.imageUrl : null;
// const songData = {
// languageName: languageName,
// artistName: artistName,
// musicLink: musicLink || null,
// trackerID: trackerID || null,
// lyrics: lyrics || null,
// imageUrl: imageUrl
// };
// return res.status(200).json({
// error_code: 200,
// message: 'Song retrieved successfully',
// song: songData
// });
// } catch (err) {
// console.error('Error inside getSong:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
const getSong = async (req, res) => {
try {
const { id } = req.params;
const song = await Song.findById(id)
.populate('languageId', 'name')
.populate('artistId', 'ArtistName')
.select('title musicLink trackerID lyrics coverArtImage');
.select('title musicLink trackerID lyrics coverArtImage musicFile');
if (!song) {
return res.status(404).json({ error_code: 404, message: 'Song not found' });
}
return res.status(200).json({ error_code: 200, message: 'Song retrieved successfully', song });
const { languageId, artistId, musicLink, trackerID, lyrics, coverArtImage, musicFile } = song;
const languageName = languageId ? languageId.name : 'Language not available';
const artistNames = artistId.map(artist => artist.ArtistName);
const imageUrl = coverArtImage ? coverArtImage.imageUrl : 'Image not available';
const url = musicFile ? musicFile.url : 'Music file not available';
const songData = {
languageName: languageName,
artistNames: artistNames,
musicLink: musicLink || 'Music link not available',
trackerID: trackerID || 'Tracker ID not available',
lyrics: lyrics || 'Lyrics not available',
imageUrl: imageUrl,
url: url
};
return res.status(200).json({
error_code: 200,
message: 'Song retrieved successfully',
song: songData
});
} catch (err) {
console.error('Error inside getSong:', err);
return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
@ -138,6 +510,8 @@ const getSong = async (req, res) => {
const changeSongStatus = async (req, res) => {
try {
const { id } = req.params;
@ -166,47 +540,82 @@ const changeSongStatus = async (req, res) => {
}
};
const getAllSongs = async (req, res) => {
try {
const { title, artist, category } = req.query;
let query = {};
const { title, artist, category, page, limit } = req.query;
// Build query object based on search fields
const searchFields = ['title', 'artist', 'category'];
searchFields.forEach(field => {
// Build match stage for filtering based on search fields
const matchStage = {};
['title', 'artist', 'category'].forEach(field => {
if (req.query[field]) {
query[field] = { $regex: req.query[field], $options: 'i' };
matchStage[field] = { $regex: req.query[field], $options: 'i' };
}
});
// Pagination parameters
const pageNumber = Math.max(1, parseInt(req.query.pageNumber) || 1);
const pageSize = Math.max(1, parseInt(req.query.pageSize) || 10);
const pageNumber = Math.max(1, parseInt(page) || 1);
const pageSize = Math.max(1, parseInt(limit) || 5);
// Count total songs based on the query
const totalSongs = await Song.countDocuments(query);
const totalPages = Math.ceil(totalSongs / pageSize);
// Find songs based on the query and pagination
const songs = await Song.find(query)
.populate({ path: 'categoryId', select: 'name' })
.populate({ path: 'albumId', select: 'albumName' })
.populate({ path: 'subcategoryId', select: 'SubCategoriesName' })
.populate({ path: 'artistId', select: 'ArtistName' })
.sort({ title: 1 })
.skip((pageNumber - 1) * pageSize)
.limit(pageSize);
// Check if songs are found
if (songs.length === 0) {
return res.status(404).json({ error_code: 404, message: 'Songs not found' });
const pipeline = [
{ $match: matchStage },
{
$lookup: {
from: 'categories',
localField: 'categoryId',
foreignField: '_id',
as: 'category'
}
},
{
$lookup: {
from: 'albums',
localField: 'albumId',
foreignField: '_id',
as: 'album'
}
},
{
$lookup: {
from: 'subcategories',
localField: 'subcategoryId',
foreignField: '_id',
as: 'subcategory'
}
},
{
$lookup: {
from: 'artists',
localField: 'artistId',
foreignField: '_id',
as: 'artist'
}
},
{
$project: {
title: 1,
category: { $arrayElemAt: ['$category.name', 0] },
subcategory: { $arrayElemAt: ['$subcategory.SubCategoriesName', 0] },
artist: { $arrayElemAt: ['$artist.ArtistName', 0] },
album: { $arrayElemAt: ['$album.albumName', 0] },
status: '$status'
}
},
{ $sort: { title: 1 } },
{ $skip: (pageNumber - 1) * pageSize },
{ $limit: pageSize }
];
// Return songs along with pagination details
const totalCount = await Song.countDocuments(matchStage);
const totalPages = Math.ceil(totalCount / pageSize);
const songs = await Song.aggregate(pipeline);
return res.status(200).json({
error_code: 200,
message: 'Songs retrieved successfully',
songs,
// page:pageNumber,
// limit:pageSize,
total_count:totalCount,
total_pages: totalPages,
current_page: pageNumber
});
@ -216,6 +625,46 @@ const getAllSongs = async (req, res) => {
}
};
// const getAllSongs = async (req, res) => {
// try {
// const songs = await Song.find()
// .populate('languageId', 'name')
// .populate('artistId', 'ArtistName')
// .select('title musicLink trackerID lyrics coverArtImage');
// if (!songs || songs.length === 0) {
// return res.status(404).json({ error_code: 404, message: 'Songs not found' });
// }
// const songData = songs.map(song => {
// const { languageId, artistId, musicLink, trackerID, lyrics, coverArtImage } = song;
// const languageName = languageId ? languageId.name : null;
// const artistNames = artistId ? artistId.map(artist => artist.ArtistName) : null;
// const imageUrl = coverArtImage ? coverArtImage.imageUrl : null;
// return {
// languageName: languageName,
// artistNames: artistNames,
// musicLink: musicLink || null,
// trackerID: trackerID || null,
// lyrics: lyrics || null,
// imageUrl: imageUrl
// };
// });
// return res.status(200).json({
// error_code: 200,
// message: 'Songs retrieved successfully',
// songs: songData
// });
// } catch (err) {
// console.error('Error inside getAllSongs:', err);
// return res.status(500).json({ error_code: 500, message: 'Internal Server Error' });
// }
// };
module.exports = {

View File

@ -408,69 +408,30 @@ const changeSubCategoryStatus = async (req, res) => {
}
};
// const getCategories = async (req, res) => {
// try {
// const { CategoriesId } = req.params;
// const categories = await SubCategories.find({ CategoriesId: CategoriesId });
// console.log("🚀 ~ getCategories ~ categories:", categories)
// if (!categories || categories.length === 0) {
// return res.status(400).send({
// error_code: 400,
// message: 'Categories not found for the given category ID'
// });
// }
// // Return the found categories
// res.status(200).json({
// error_code: 200,
// message: 'Categories retrieved successfully',
// categories: categories
// });
// } catch (err) {
// console.error('Error inside getCategories', err);
// res.status(500).send({
// error_code: 500,
// message: 'Internal Server Error'
// });
// }
// };
// ------------------------------------------------
const getSubCategoriesfromCategory = async (req, res) => {
const getCategories = async (req, res) => {
try {
const { CategoriesId } = req.params;
const categories = await SubCategories.find({ CategoriesId: CategoriesId });
const categories = await SubCategories.find({ CategoriesId: CategoriesId });
console.log("🚀 ~ getCategories ~ categories:", categories)
if (!categories || categories.length === 0) {
return res.status(400).json({
return res.status(400).send({
error_code: 400,
message: 'Categories not found for the given category ID'
});
}
const categoriesWithImageUrl = categories.map(category => ({
_id: category._id,
SubCategoriesName: category.SubCategoriesName,
imageUrl: category.image ? category.image.imageUrl : null,
status: category.status,
CategoriesId: category.CategoriesId,
categoryName: category.categoryName
}));
// Return the found categories
res.status(200).json({
error_code: 200,
message: 'Categories retrieved successfully',
categories: categoriesWithImageUrl
categories: categories
});
} catch (err) {
console.error('Error inside getCategories', err);
res.status(500).json({
res.status(500).send({
error_code: 500,
message: 'Internal Server Error'
});
@ -479,6 +440,45 @@ const getSubCategoriesfromCategory = async (req, res) => {
// ------------------------------------------------
// const getSubCategoriesfromCategory = async (req, res) => {
// try {
// const { CategoriesId } = req.params;
// const categories = await SubCategories.find({ CategoriesId: CategoriesId });
// if (!categories || categories.length === 0) {
// return res.status(400).json({
// error_code: 400,
// message: 'Categories not found for the given category ID'
// });
// }
// const categoriesWithImageUrl = categories.map(category => ({
// _id: category._id,
// SubCategoriesName: category.SubCategoriesName,
// imageUrl: category.image ? category.image.imageUrl : null,
// status: category.status,
// CategoriesId: category.CategoriesId,
// categoryName: category.categoryName
// }));
// res.status(200).json({
// error_code: 200,
// message: 'Categories retrieved successfully',
// categories: categoriesWithImageUrl
// });
// } catch (err) {
// console.error('Error inside getCategories', err);
// res.status(500).json({
// error_code: 500,
// message: 'Internal Server Error'
// });
// }
// };
// ------------------------------------------------
module.exports = {
@ -488,6 +488,6 @@ module.exports = {
getSubCategories,
deleteMany,
changeSubCategoryStatus,
getSubCategoriesfromCategory
getCategories
};

View File

@ -1,4 +1,4 @@
const User = require('../models/user.model');
// const User = require('../models/user.model');
const jwt = require('jsonwebtoken');
const authConfig = require('../configs/auth.config');
const bcrypt = require('bcryptjs');
@ -6,48 +6,187 @@ const constant = require('../util/constant');
const Artist = require('../models/artist.model');
const Reward = require('../models/Reward.model');
const Song = require('../models/song.model');
const axios = require('axios');
const { User } = require('../models/user.model');
const { validationResult } = require('express-validator');
const nodemailer = require('nodemailer');
const sendOTPByEmail = async (email, otp) => {
try {
const transporter = nodemailer.createTransport({
service: 'gmail', // e.g., 'Gmail'
auth: {
user: 'ay2087355@gmail.com',
pass: 'mqqqnoutaukxenlh'
}
});
// Send OTP email
await transporter.sendMail({
from: 'checkdemo02@gmail.com',
to: email,
subject: 'Your OTP Code',
text: `Your OTP code is: ${otp}`
});
console.log('OTP email sent successfully');
} catch (error) {
console.error('Error sending OTP email:', error);
throw new Error('Failed to send OTP email');
}
};
const userRegister = async (req, res) => {
try {
// Check if the email already exists
const existingUser = await User.findOne({ email: req.body.email });
console.log("🚀 ~ userRegister ~ existingUser:", existingUser)
if (existingUser) {
return res.status(400).json({
error_code: 400,
message: 'Email already exists'
});
}
// Generate OTP
const otp = Math.floor(10000 + Math.random() * 90000);
// Create user object with hashed password
const user = await User.create({
email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
registerWith: constant.registerWith.Email,
otp: otp,
userName: req.body.userName,
userType: constant.userTypes.customer
});
console.log("🚀 ~ userRegister ~ user:", user)
// Send OTP email
await sendOTPByEmail(user.email, otp);
return res.status(200).json({
error_code: 200,
message: 'Success',
user: user
});
} catch (err) {
console.error('Error in user registration:', err);
return res.status(500).json({
error_code: 500,
message: 'Failed'
});
}
};
//otp verify
const verifyOTP = async (req, res) => {
try {
const { email, otp } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({
error_code: 400,
message: 'User not found'
});
}
if (user.otp !== otp) {
return res.status(400).json({
error_code: 400,
message: 'Incorrect OTP'
});
}
user.otpVerified = true;
await user.save();
return res.status(200).json({
error_code: 200,
message: 'OTP verified successfully',
});
} catch (error) {
console.error('Error in verify OTP:', error);
return res.status(500).json({
error_code: 500,
message: 'Failed'
});
}
};
const createGoogle = async (req, res) => {
try {
// Validate request body
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
let user = await User.findOne({ email: req.body.email });
var flag = 0;
// Fetch user data from Google API using access token
const response = await axios.get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${req.body.accessToken}`);
const userData = response.data;
// Check if the user with this Google ID already exists
let user = await User.findOne({ googleId: userData.id });
// If user with Google ID doesn't exist, check by email
if (!user) {
let obj = {
email: req.body.email,
registerWith: constant.registerWith.google
user = await User.findOne({ email: userData.email });
}
user = await User.create(obj);
flag = 1
}
if (user.registerWith != constant.registerWith.google) {
return res.status(400).send({
error_code : 400,
message: "Can't login Through google"
// If user exists, generate token and return response
if (user) {
const token = jwt.sign({ id: user._id, userType: user.userType }, process.env.JWT_SECRET, { expiresIn: '1h' });
return res.status(200).json({
_id: user._id,
email: user.email,
token: token,
userType: user.userType,
status: user.status,
message: 'User logged in successfully'
});
}
let str = flag ? 'User Got Created' : 'User was already Created';
const token = jwt.sign({ id: user._id }, authConfig.secretKey, {
expiresIn: 600000
// If user doesn't exist, create a new user
const newUser = await User.create({
email: userData.email,
name: userData.name,
profilePic: userData.picture,
authenticationType: "GOOGLE",
googleId: userData.id,
});
return res.status(201).send({
error_code : 200,
message: str,
acessToken: token
})
} catch (err) {
console.log(err);
return res.status(500).send({
// Generate token for the new user
const token = jwt.sign({ id: newUser._id, userType: newUser.userType }, process.env.JWT_SECRET, { expiresIn: '1h' });
// Send response with user data
return res.status(201).json({
_id: newUser._id,
email: newUser.email,
token: token,
userType: newUser.userType,
authenticationType: "GOOGLE",
status: newUser.status,
message: 'New user created and logged in successfully'
});
} catch (error) {
// Handle errors
console.error('Error inside createGoogle:', error);
return res.status(500).json({
error_code: 500,
message: 'Error in creating user'
})
message: 'Internal Server Error'
});
}
}
};
const update = async (req, res) => {
try {
let id = req.params.id;
@ -480,9 +619,162 @@ const changeUserStatus = async (req, res) => {
}
}
const usergetAllSongs =async(req,res)=>{
try {
const song = await Song.find({status: 'Active'});
return res.status(200).send(song);
}catch (err) {
console.log('Error inside changeStatus controller', err);
return res.status(500).send({
error_code: 500,
message: 'Internal server error.'
});
}
}
const newRelease = async (req, res) => {
try {
const fiveDaysAgo = new Date();
fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 3);
const songs = await Song.find({
status: 'activate',
createdAt: { $gte: fiveDaysAgo }
});
return res.status(200).send({error_code:200,message:'new realese songs',song:songs});
} catch (err) {
console.log('Error inside newRelease controller', err);
return res.status(500).send({
error_code: 500,
message: 'Internal server error.'
});
}
}
const homeData = async (req, res) => {
try {
// Pipeline to aggregate songs with category name, artist names, and image URL
const pipeline = [
{
$match: { status: 'activate' }
},
{
$lookup: {
from: 'categories',
localField: 'categoryId',
foreignField: '_id',
as: 'category'
}
},
{
$lookup: {
from: 'artists',
localField: 'artistId',
foreignField: '_id',
as: 'artists'
}
},
{
$group: {
_id: { categoryId: '$categoryId', categoryName: '$category.name' },
songs: {
$push: {
_id: '$_id',
title: '$title',
artistNames: '$artists.ArtistName',
imageUrl: '$coverArtImage.imageUrl'
}
}
}
},
{
$project: {
_id: 0,
categoryName: '$_id.categoryName',
songs: {
$map: {
input: '$songs',
as: 'song',
in: {
_id: '$$song._id',
title: '$$song.title',
artistNames: '$$song.artistNames',
imageUrl: '$$song.imageUrl'
}
}
}
}
}
];
const categoriesWithSongs = await Song.aggregate(pipeline);
return res.status(200).json({
error_code: 200,
message: 'Songs grouped by category retrieved successfully',
categories: categoriesWithSongs
});
} catch (err) {
// Log and handle errors
console.error('Error inside homeData:', err);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
const artistData = async (req, res) => {
try {
const pipeline = [
{
$lookup: {
from: 'songs',
localField: '_id',
foreignField: 'artistId',
as: 'songs'
}
},
{
$project: {
_id: 1,
ArtistName: 1,
songs: {
$map: {
input: '$songs',
as: 'song',
in: {
_id: '$$song._id',
title: '$$song.title',
status: '$$song.status',
imageUrl: '$$song.coverArtImage.imageUrl'
}
}
}
}
}
];
// Execute aggregation pipeline
const artistsWithSongs = await Artist.aggregate(pipeline);
// Return response
return res.status(200).json({
error_code: 200,
message: 'Artist data with songs retrieved successfully',
artists: artistsWithSongs
});
} catch (error) {
// Log and handle errors
console.error('Error inside artistData:', error);
return res.status(500).json({ error_code: 500, message: 'Internal server error' });
}
};
module.exports = {
userRegister,
verifyOTP,
createGoogle,
createFacebook,
update,
@ -496,5 +788,8 @@ module.exports = {
followingArtist,
evaluateAccuracy,
ranking,
changeUserStatus
changeUserStatus,usergetAllSongs,
newRelease,
homeData,
artistData
};

View File

@ -1,4 +1,4 @@
const User = require('../models/user.model');
const {User} = require('../models/user.model');
const constant = require('../util/constant')
const isAdmin = async(req,res,next) => {

View File

@ -1,42 +1,49 @@
const regex = require('../regex');
const User = require('../../models/user.model')
const {User} = require('../../models/user.model')
const multer = require('multer');
const fieldCheck = async (req, res, next) => {
try {
if(!req.body.email){
return res.status(400).send({
if (!req.body.email || req.body.email.trim() === '') {
return res.status(400).json({
error_code: 400,
message : 'Email not provided'
})
message: 'Email not provided or empty'
});
}
if(!req.body.password){
return res.status(400).send({
if (!req.body.password || req.body.password.trim() === '') {
return res.status(400).json({
error_code: 400,
message : 'Password not provided'
})
message: 'Password not provided or empty'
});
}
if (!regex.emailRegex.test(req.body.email)) {
return res.status(400).send({
return res.status(400).json({
error_code: 400,
message : 'Email format is Incorrect'
})
message: 'Email format is incorrect'
});
}
if (!regex.passRegex.test(req.body.password)) {
return res.status(400).send({
return res.status(400).json({
error_code: 400,
message : 'Password format is Incorrect'
})
message: 'Password format is incorrect'
});
}
next();
} catch (err) {
console.log('Error inside auth Middelware fieldCheck',err);
return res.status(500).send({
console.error('Error inside auth Middleware fieldCheck:', err);
return res.status(500).json({
error_code: 500,
message : 'Internal Error'
})
}
message: 'Internal Server Error'
});
}
};
const uniqueEmail = async(req,res,next) => {
@ -61,6 +68,7 @@ const uniqueEmail = async(req,res,next) => {
const userCheckEmail = async (req,res,next) => {
try{
const user = await User.findOne({email : req.body.email});
if(!user){
return res.status(400).send({

View File

@ -1,5 +1,5 @@
const jwt = require('jsonwebtoken');
const User = require('../models/user.model');
const {User} = require('../models/user.model');
const authConfig = require('../configs/auth.config');
const verifyToken = (req,res,next)=>{
@ -23,6 +23,7 @@ const verifyToken = (req,res,next)=>{
console.log(decoded);
req.userId = decoded.id;
const user = await User.findOne({_id:req.userId});
console.log("🚀 ~ jwt.verify ~ user:", user)
if(!user){
return res.status(400).send({
error_code : 400,

View File

@ -2,28 +2,28 @@ const mongoose = require('mongoose')
const idCheck = async (req, res, next) => {
try {
if(!req.params.id)
{
return res.status(401).send({
message : 'id not present'
})
}
let check = mongoose.isValidObjectId(req.params.id);
if(!check){
return res.status(400).send({
message : 'Not a valid Param id'
})
console.log(req.params,"sjkhfjsfad");
if (!req.params._id) {
return res.status(400).json({
message: 'ID not present'
});
}
if (!mongoose.isValidObjectId(req.params._id)) {
return res.status(400).json({
message: 'Not a valid ID'
});
}
next()
next();
} catch (err) {
return res.status(500).send({
console.error('Error inside idCheck middleware:', err);
return res.status(500).json({
message: 'Internal Server Error'
})
}
});
}
};
module.exports = {
idCheck

View File

@ -1,7 +1,7 @@
let nameRegex = /^[.a-zA-Z\s]+$/;
let phoneRegex = /^(\+91[\-\s]?)?[0]?(91)?[6789]\d{9}$/;
let emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
let passRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,15}$/;
let emailRegex = /.+@.+\..+/;
let passRegex = /.{6,}/;
module.exports = {

16
middlewares/uploads.js Normal file
View File

@ -0,0 +1,16 @@
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, cb) {
if (file.fieldname === 'coverArtImage' || file.fieldname === 'musicFile') {
cb(null, './uploads');
}
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const upload = multer({ storage: storage });
module.exports = upload.any(); // Use upload.any() method

View File

@ -5,7 +5,6 @@ const mongoose = require('mongoose');
const artistSchema = new mongoose.Schema({
ArtistName: {
type: String,
required: true
},
image: {
fileName: String,

View File

@ -3,17 +3,14 @@ const mongoose = require('mongoose');
const categorySchema = new mongoose.Schema({
name: {
type: String,
required: true
},
image: {
fileName: {
type: String,
required: true
},
fileAddress: {
type: String,
required: true
}
type: String, }
},
imageUrl: { type: String },
status: {

View File

@ -1,7 +1,10 @@
const mongoose = require('mongoose');
const constant = require('../util/notification.constant')
const Schema = mongoose.Schema;
const notificationSchema = new mongoose.Schema({
userId: { type: Schema.Types.ObjectId, ref: 'User' },
sendTo: {
type: [String],
enum: [constant.sendTo.toAll, constant.sendTo.host, constant.sendTo.specific],
@ -24,10 +27,10 @@ const notificationSchema = new mongoose.Schema({
type: String,
required: true
},
recipients: {
type: [mongoose.SchemaType.objectId],
default: []
}
// recipients: {
// type: [mongoose.SchemaType.objectId],
// default: []
// }
}, { timestamps: true });
module.exports = mongoose.model('Notification', notificationSchema);

View File

@ -6,7 +6,10 @@ const songSchema = new Schema({
categoryId: { type: Schema.Types.ObjectId, ref: 'Category' },
subcategoryId: { type: Schema.Types.ObjectId, ref: 'SubCategories' },
albumId: { type: Schema.Types.ObjectId, ref: 'Album' },
artistId: { type: Schema.Types.ObjectId, ref: 'Artist' },
artistId: [{
type: Schema.Types.ObjectId,
ref: 'Artist',
}],
title: String,
musicLink: String,
trackerID: String,
@ -19,7 +22,8 @@ const songSchema = new Schema({
},
musicFile: {
filename: String,
fileAddress: String
fileAddress: String,
url: String
},
status: {
type: String,

View File

@ -1,4 +1,5 @@
const mongoose = require("mongoose");
const bcrypt = require('bcrypt');
const constant = require('../util/constant');
const userSchema = new mongoose.Schema({
@ -6,129 +7,122 @@ const userSchema = new mongoose.Schema({
type: String,
unique: true,
default: function () {
let username = 'guest' + Math.floor(Math.random() * 10000);
return username;
return 'guest' + Math.floor(Math.random() * 10000);
}
},
image: {
fileName: {
type: String,
fileName: String,
fileAddress: String
},
fileAddress: {
type: String,
}
},
imageUrl:{
type: String
},
firstName:{
type: String,
// required: true
},
lastName:{
type: String,
// required: true
},
address:{
type: String,
},
mobileNo:{
type: Number
},
deviceToken: { type: String, default: "" },
accessToken:{ type: String, default: "" },
deviceType: { type: String, default: "" },
imageUrl: String,
firstName: String,
lastName: String,
address: String,
mobileNo: Number,
email: {
type: String,
required: true,
lowercase: true, // it will covert the email into the lower case and then store in the db,
minLength: 10, // anything less than 10 will fail
// required: true,
lowercase: true,
unique: true
},
password: {
type: String,
// required: true
},
userTypes: {
type: String,
enum: [constant.userTypes.admin, constant.userTypes.customer],
default: constant.userTypes.customer
},
status: {
type: String,
enum: ['Active', 'Deactive'],
default: 'Active'
},
registerWith: {
type: String,
enum: [constant.registerWith.Email, constant.registerWith.google, constant.registerWith.facebook],
default: constant.registerWith.Email
},
playlist: {
type: [mongoose.Schema.Types.ObjectId],
playlist: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'PlayList'
},
favrioteSongs: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Song',
},
}],
favoriteSongs: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Song'
}],
mostPlayedSongs: {
type: Object,
ref: 'Song',
default: {}
},
following: {
type: [mongoose.Schema.Types.ObjectId],
following: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Artist'
},
}],
score: {
type: Number,
default: 0
},
otp: Number,
otpVerifly:{
type: Boolean,
default: false
},
createdAt: {
// I want to default to a new date
type: Date,
immutable: true, // This will ensure the createdAt column is never updated but once in the start
default: () => {
return Date.now();
}
immutable: true,
default: Date.now
},
updatedAt: {
type: Date,
default: () => {
return Date.now();
default: Date.now
}
}
})
});
userSchema.pre('deleteOne', async function (next) {
const userId = this.getFilter()['_id'];
const Artist = require('../models/artist.model');
const artist = await Artist.find({ followers: userId });
const artist = await Artist.find({
followers: userId
})
const artistPromises = artist.map(artist => {
const artistPromises = artist.map(async (artist) => {
artist.followers.pull(userId);
return artist.save();
})
await artist.save();
});
await Promise.all(artistPromises);
});
})
const User = mongoose.model("User", userSchema);
module.exports = mongoose.model("User", userSchema);
const findDefaultAdmin = async () => {
try {
const result = await User.findOne({ userTypes: constant.userTypes.admin });
if (!result) {
const obj = {
userTypes: constant.userTypes.admin,
name: "musicNFT",
mobileNumber: "7038415050",
userName:"admin",
email: "admin@email.com",
password: bcrypt.hashSync("Admin@1", 10),
address: "INDIA",
otpVerifly:true
};
const admin = await User.create(obj);
console.log("Default Admin Created 😇😉😄", admin);
} else {
console.log("Default Admin 😉😄");
}
} catch (error) {
console.error("Error finding or creating default admin:", error);
}
};
findDefaultAdmin();
module.exports = { User };

701
node_modules/.package-lock.json generated vendored
View File

@ -4,6 +4,39 @@
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@mapbox/node-pre-gyp": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
"integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
"dependencies": {
"detect-libc": "^2.0.0",
"https-proxy-agent": "^5.0.0",
"make-dir": "^3.1.0",
"node-fetch": "^2.6.7",
"nopt": "^5.0.0",
"npmlog": "^5.0.1",
"rimraf": "^3.0.2",
"semver": "^7.3.5",
"tar": "^6.1.11"
},
"bin": {
"node-pre-gyp": "bin/node-pre-gyp"
}
},
"node_modules/@mapbox/node-pre-gyp/node_modules/nopt": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
"dependencies": {
"abbrev": "1"
},
"bin": {
"nopt": "bin/nopt.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/@types/node": {
"version": "20.11.24",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.24.tgz",
@ -61,6 +94,46 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"dependencies": {
"debug": "4"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/agent-base/node_modules/debug": {
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"dependencies": {
"ms": "2.1.2"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/agent-base/node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/ansi-regex": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"engines": {
"node": ">=8"
}
},
"node_modules/anymatch": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz",
@ -89,24 +162,47 @@
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw=="
},
"node_modules/aproba": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
"integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ=="
},
"node_modules/are-we-there-yet": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
"integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
"dependencies": {
"delegates": "^1.0.0",
"readable-stream": "^3.6.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/are-we-there-yet/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/array-flatten": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
"integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg=="
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
},
"node_modules/axios": {
"version": "1.6.7",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz",
"integrity": "sha512-/hDJGff6/c7u0hDkvkGxR/oy6CbCs8ziCsC7SqmhjfozqiJGc8Z11wrv9z9lYfY4K8l+H9TpjcMDX0xOZmx+RA==",
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"dependencies": {
"follow-redirects": "^1.15.4",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
"follow-redirects": "^1.14.0"
}
},
"node_modules/balanced-match": {
@ -114,6 +210,35 @@
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="
},
"node_modules/basic-auth": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/basic-auth/-/basic-auth-2.0.1.tgz",
"integrity": "sha512-NF+epuEdnUYVlGuhaxbbq+dvJttwLnGY+YixlXlME5KpQ5W3CnXA5cVTneY3SPbPDRkcjMbifrwmFYcClgOZeg==",
"dependencies": {
"safe-buffer": "5.1.2"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/basic-auth/node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/bcrypt": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz",
"integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==",
"hasInstallScript": true,
"dependencies": {
"@mapbox/node-pre-gyp": "^1.0.11",
"node-addon-api": "^5.0.0"
},
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/bcryptjs": {
"version": "2.4.3",
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-2.4.3.tgz",
@ -248,15 +373,20 @@
"fsevents": "~2.3.2"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"node_modules/chownr": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
"engines": {
"node": ">= 0.8"
"node": ">=10"
}
},
"node_modules/color-support": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
"integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
"bin": {
"color-support": "bin.js"
}
},
"node_modules/concat-map": {
@ -278,6 +408,11 @@
"typedarray": "^0.0.6"
}
},
"node_modules/console-control-strings": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ=="
},
"node_modules/content-disposition": {
"version": "0.5.4",
"resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz",
@ -351,13 +486,10 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/delayed-stream": {
"node_modules/delegates": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"engines": {
"node": ">=0.4.0"
}
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ=="
},
"node_modules/depd": {
"version": "2.0.0",
@ -376,6 +508,55 @@
"npm": "1.2.8000 || >= 1.4.16"
}
},
"node_modules/detect-libc": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.2.tgz",
"integrity": "sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw==",
"engines": {
"node": ">=8"
}
},
"node_modules/dicer": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/dicer/-/dicer-0.2.5.tgz",
"integrity": "sha512-FDvbtnq7dzlPz0wyYlOExifDEZcu8h+rErEXgfxqmLfRfC/kJidEFh4+effJRO3P0xmfqyPbSMG0LveNRfTKVg==",
"dependencies": {
"readable-stream": "1.1.x",
"streamsearch": "0.1.2"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/dicer/node_modules/isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ=="
},
"node_modules/dicer/node_modules/readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
"integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"isarray": "0.0.1",
"string_decoder": "~0.10.x"
}
},
"node_modules/dicer/node_modules/streamsearch": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
"integrity": "sha512-jos8u++JKm0ARcSUTAZXOVC0mSox7Bhn6sBgty73P1f3JGf7yG2clTbBNHUdde/kdvP2FESam+vM6l8jBrNxHA==",
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/dicer/node_modules/string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ=="
},
"node_modules/dotenv": {
"version": "16.3.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.3.1.tgz",
@ -400,6 +581,11 @@
"resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
"integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
},
"node_modules/encodeurl": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz",
@ -481,6 +667,29 @@
"node": ">= 0.10.0"
}
},
"node_modules/express-fileupload": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/express-fileupload/-/express-fileupload-1.5.0.tgz",
"integrity": "sha512-jSW3w9evqM37VWkEPkL2Ck5wUo2a8qa03MH+Ou/0ZSTpNlQFBvSLjU12k2nYcHhaMPv4JVvv6+Ac1OuLgUZb7w==",
"dependencies": {
"busboy": "^1.6.0"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/express-validator": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/express-validator/-/express-validator-7.0.1.tgz",
"integrity": "sha512-oB+z9QOzQIE8FnlINqyIFA8eIckahC6qc8KtqLdLJcU3/phVyuhXH3bA4qzcrhme+1RYaCSwrq+TlZ/kAKIARA==",
"dependencies": {
"lodash": "^4.17.21",
"validator": "^13.9.0"
},
"engines": {
"node": ">= 8.0.0"
}
},
"node_modules/express/node_modules/body-parser": {
"version": "1.20.1",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz",
@ -547,9 +756,9 @@
}
},
"node_modules/follow-redirects": {
"version": "1.15.5",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz",
"integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==",
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.6.tgz",
"integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==",
"funding": [
{
"type": "individual",
@ -565,19 +774,6 @@
}
}
},
"node_modules/form-data": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/forwarded": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
@ -594,6 +790,33 @@
"node": ">= 0.6"
}
},
"node_modules/fs-minipass": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
"dependencies": {
"minipass": "^3.0.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/fs-minipass/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@ -602,6 +825,25 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/gauge": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
"integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
"dependencies": {
"aproba": "^1.0.3 || ^2.0.0",
"color-support": "^1.1.2",
"console-control-strings": "^1.0.0",
"has-unicode": "^2.0.1",
"object-assign": "^4.1.1",
"signal-exit": "^3.0.0",
"string-width": "^4.2.3",
"strip-ansi": "^6.0.1",
"wide-align": "^1.1.2"
},
"engines": {
"node": ">=10"
}
},
"node_modules/get-intrinsic": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.2.4.tgz",
@ -620,6 +862,25 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.1.1",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
},
"engines": {
"node": "*"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/glob-parent": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz",
@ -683,6 +944,11 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-unicode": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
"integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ=="
},
"node_modules/hasown": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz",
@ -709,6 +975,39 @@
"node": ">= 0.8"
}
},
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/https-proxy-agent/node_modules/debug": {
"version": "4.3.4",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz",
"integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==",
"dependencies": {
"ms": "2.1.2"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/https-proxy-agent/node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/iconv-lite": {
"version": "0.4.24",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz",
@ -725,6 +1024,15 @@
"resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz",
"integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA=="
},
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
@ -769,6 +1077,14 @@
"node": ">=0.10.0"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"engines": {
"node": ">=8"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
@ -861,6 +1177,28 @@
"node": ">=10"
}
},
"node_modules/make-dir": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
"integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
"dependencies": {
"semver": "^6.0.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/make-dir/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"bin": {
"semver": "bin/semver.js"
}
},
"node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
@ -937,6 +1275,37 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/minipass": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
"integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
"engines": {
"node": ">=8"
}
},
"node_modules/minizlib": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
"dependencies": {
"minipass": "^3.0.0",
"yallist": "^4.0.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/minizlib/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
@ -1015,6 +1384,32 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/morgan": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/morgan/-/morgan-1.10.0.tgz",
"integrity": "sha512-AbegBVI4sh6El+1gNwvD5YIck7nSA36weD7xvIxG4in80j/UoK8AEGaWnnz8v1GxonMCltmlNs5ZKbGvl9b1XQ==",
"dependencies": {
"basic-auth": "~2.0.1",
"debug": "2.6.9",
"depd": "~2.0.0",
"on-finished": "~2.3.0",
"on-headers": "~1.0.2"
},
"engines": {
"node": ">= 0.8.0"
}
},
"node_modules/morgan/node_modules/on-finished": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.3.0.tgz",
"integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==",
"dependencies": {
"ee-first": "1.1.1"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/mpath": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/mpath/-/mpath-0.9.0.tgz",
@ -1061,22 +1456,57 @@
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/multer": {
"version": "1.4.5-lts.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.1.tgz",
"integrity": "sha512-ywPWvcDMeH+z9gQq5qYHCCy+ethsk4goepZ45GLD63fOu0YcNecQxi64nDs3qluZB+murG3/D4dJ7+dGctcCQQ==",
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.3.tgz",
"integrity": "sha512-np0YLKncuZoTzufbkM6wEKp68EhWJXcU6fq6QqrSwkckd2LlMgd1UqhUJLj6NS/5sZ8dE8LYDWslsltJznnXlg==",
"deprecated": "Multer 1.x is affected by CVE-2022-24434. This is fixed in v1.4.4-lts.1 which drops support for versions of Node.js before 6. Please upgrade to at least Node.js 6 and version 1.4.4-lts.1 of Multer. If you need support for older versions of Node.js, we are open to accepting patches that would fix the CVE on the main 1.x release line, whilst maintaining compatibility with Node.js 0.10.",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.0.0",
"busboy": "^0.2.11",
"concat-stream": "^1.5.2",
"mkdirp": "^0.5.4",
"object-assign": "^4.1.1",
"on-finished": "^2.3.0",
"type-is": "^1.6.4",
"xtend": "^4.0.0"
},
"engines": {
"node": ">= 6.0.0"
"node": ">= 0.10.0"
}
},
"node_modules/multer/node_modules/busboy": {
"version": "0.2.14",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-0.2.14.tgz",
"integrity": "sha512-InWFDomvlkEj+xWLBfU3AvnbVYqeTWmQopiW0tWWEy5yehYm2YkGEc59sUmw/4ty5Zj/b0WHGs1LgecuBSBGrg==",
"dependencies": {
"dicer": "0.2.5",
"readable-stream": "1.1.x"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/multer/node_modules/isarray": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
"integrity": "sha512-D2S+3GLxWH+uhrNEcoh/fnmYeP8E8/zHl644d/jdA0g2uyXvy3sb0qxotE+ne0LtccHknQzWwZEzhak7oJ0COQ=="
},
"node_modules/multer/node_modules/readable-stream": {
"version": "1.1.14",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
"integrity": "sha512-+MeVjFf4L44XUkhM1eYbD8fyEsxcV81pqMSR5gblfcLCHfZvbrqy4/qYHE+/R5HoBUT11WV5O08Cr1n3YXkWVQ==",
"dependencies": {
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"isarray": "0.0.1",
"string_decoder": "~0.10.x"
}
},
"node_modules/multer/node_modules/string_decoder": {
"version": "0.10.31",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
"integrity": "sha512-ev2QzSzWPYmy9GuqfIVildA4OdcGLeFZQrq5ys6RtiuF+RQQiZWr8TZNyAcuVXyQRYfEO+MsoB/1BuQVhOJuoQ=="
},
"node_modules/natural": {
"version": "6.10.0",
"resolved": "https://registry.npmjs.org/natural/-/natural-6.10.0.tgz",
@ -1103,6 +1533,49 @@
"node": ">= 0.6"
}
},
"node_modules/node-addon-api": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz",
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA=="
},
"node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/node-fetch/node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/node-fetch/node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="
},
"node_modules/node-fetch/node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/nodemailer": {
"version": "6.9.3",
"resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-6.9.3.tgz",
@ -1181,6 +1654,17 @@
"node": ">=0.10.0"
}
},
"node_modules/npmlog": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
"integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
"dependencies": {
"are-we-there-yet": "^2.0.0",
"console-control-strings": "^1.1.0",
"gauge": "^3.0.0",
"set-blocking": "^2.0.0"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@ -1208,6 +1692,22 @@
"node": ">= 0.8"
}
},
"node_modules/on-headers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.0.2.tgz",
"integrity": "sha512-pZAE+FJLoyITytdqK0U5s+FIpjN0JP3OzFi/u8Rx+EV5/W+JTWGXG8xFzevE7AjBfDqHv/8vL8qQsIhHnqRkrA==",
"engines": {
"node": ">= 0.8"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/parseurl": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@ -1225,6 +1725,14 @@
"util": "^0.10.3"
}
},
"node_modules/path-is-absolute": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/path-to-regexp": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
@ -1266,11 +1774,6 @@
"node": ">= 0.10"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
},
"node_modules/pstree.remy": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz",
@ -1350,6 +1853,20 @@
"node": ">=8.10.0"
}
},
"node_modules/rimraf": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
"dependencies": {
"glob": "^7.1.3"
},
"bin": {
"rimraf": "bin.js"
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@ -1450,6 +1967,11 @@
"node": ">= 0.8.0"
}
},
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="
},
"node_modules/set-function-length": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.1.tgz",
@ -1493,6 +2015,11 @@
"resolved": "https://registry.npmjs.org/sift/-/sift-16.0.1.tgz",
"integrity": "sha512-Wv6BjQ5zbhW7VFefWusVP33T/EM0vYikCaQ2qR8yULbsilAT8/wQaXvuQ3ptGLpoKx+lihJE3y2UTgKDyyNHZQ=="
},
"node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="
},
"node_modules/simple-update-notifier": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
@ -1577,6 +2104,30 @@
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"dependencies": {
"ansi-regex": "^5.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/supports-color": {
"version": "5.5.0",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz",
@ -1596,6 +2147,33 @@
"node": ">=0.2.6"
}
},
"node_modules/tar": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.0.tgz",
"integrity": "sha512-/Wo7DcT0u5HUV486xg675HtjNd3BXZ6xDbzsCUZPt5iw8bTQ63bP0Raut3mvro9u+CUyq7YQd8Cx55fsZXxqLQ==",
"dependencies": {
"chownr": "^2.0.0",
"fs-minipass": "^2.0.0",
"minipass": "^5.0.0",
"minizlib": "^2.1.1",
"mkdirp": "^1.0.3",
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/tar/node_modules/mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
"bin": {
"mkdirp": "bin/cmd.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@ -1703,6 +2281,14 @@
"node": ">= 0.4.0"
}
},
"node_modules/validator": {
"version": "13.11.0",
"resolved": "https://registry.npmjs.org/validator/-/validator-13.11.0.tgz",
"integrity": "sha512-Ii+sehpSfZy+At5nPdnyMhx78fEoPDkR2XW/zimHEL3MyGJQOCQ7WeP20jPYRz7ZCpcKLB21NxuXHF3bxjStBQ==",
"engines": {
"node": ">= 0.10"
}
},
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@ -1731,6 +2317,14 @@
"node": ">=12"
}
},
"node_modules/wide-align": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
"integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
"dependencies": {
"string-width": "^1.0.2 || 2 || 3 || 4"
}
},
"node_modules/wordnet-db": {
"version": "3.1.14",
"resolved": "https://registry.npmjs.org/wordnet-db/-/wordnet-db-3.1.14.tgz",
@ -1739,6 +2333,11 @@
"node": ">=0.6.0"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",

21
node_modules/asynckit/LICENSE generated vendored
View File

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

233
node_modules/asynckit/README.md generated vendored
View File

@ -1,233 +0,0 @@
# asynckit [![NPM Module](https://img.shields.io/npm/v/asynckit.svg?style=flat)](https://www.npmjs.com/package/asynckit)
Minimal async jobs utility library, with streams support.
[![PhantomJS Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=browser&style=flat)](https://travis-ci.org/alexindigo/asynckit)
[![Linux Build](https://img.shields.io/travis/alexindigo/asynckit/v0.4.0.svg?label=linux:0.12-6.x&style=flat)](https://travis-ci.org/alexindigo/asynckit)
[![Windows Build](https://img.shields.io/appveyor/ci/alexindigo/asynckit/v0.4.0.svg?label=windows:0.12-6.x&style=flat)](https://ci.appveyor.com/project/alexindigo/asynckit)
[![Coverage Status](https://img.shields.io/coveralls/alexindigo/asynckit/v0.4.0.svg?label=code+coverage&style=flat)](https://coveralls.io/github/alexindigo/asynckit?branch=master)
[![Dependency Status](https://img.shields.io/david/alexindigo/asynckit/v0.4.0.svg?style=flat)](https://david-dm.org/alexindigo/asynckit)
[![bitHound Overall Score](https://www.bithound.io/github/alexindigo/asynckit/badges/score.svg)](https://www.bithound.io/github/alexindigo/asynckit)
<!-- [![Readme](https://img.shields.io/badge/readme-tested-brightgreen.svg?style=flat)](https://www.npmjs.com/package/reamde) -->
AsyncKit provides harness for `parallel` and `serial` iterators over list of items represented by arrays or objects.
Optionally it accepts abort function (should be synchronously return by iterator for each item), and terminates left over jobs upon an error event. For specific iteration order built-in (`ascending` and `descending`) and custom sort helpers also supported, via `asynckit.serialOrdered` method.
It ensures async operations to keep behavior more stable and prevent `Maximum call stack size exceeded` errors, from sync iterators.
| compression | size |
| :----------------- | -------: |
| asynckit.js | 12.34 kB |
| asynckit.min.js | 4.11 kB |
| asynckit.min.js.gz | 1.47 kB |
## Install
```sh
$ npm install --save asynckit
```
## Examples
### Parallel Jobs
Runs iterator over provided array in parallel. Stores output in the `result` array,
on the matching positions. In unlikely event of an error from one of the jobs,
will terminate rest of the active jobs (if abort function is provided)
and return error along with salvaged data to the main callback function.
#### Input Array
```javascript
var parallel = require('asynckit').parallel
, assert = require('assert')
;
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
, target = []
;
parallel(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
});
// async job accepts one element from the array
// and a callback function
function asyncJob(item, cb)
{
// different delays (in ms) per item
var delay = item * 25;
// pretend different jobs take different time to finish
// and not in consequential order
var timeoutId = setTimeout(function() {
target.push(item);
cb(null, item * 2);
}, delay);
// allow to cancel "leftover" jobs upon error
// return function, invoking of which will abort this job
return clearTimeout.bind(null, timeoutId);
}
```
More examples could be found in [test/test-parallel-array.js](test/test-parallel-array.js).
#### Input Object
Also it supports named jobs, listed via object.
```javascript
var parallel = require('asynckit/parallel')
, assert = require('assert')
;
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
, expectedTarget = [ 1, 1, 2, 4, 8, 16, 32, 64 ]
, expectedKeys = [ 'first', 'one', 'two', 'four', 'eight', 'sixteen', 'thirtyTwo', 'sixtyFour' ]
, target = []
, keys = []
;
parallel(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
assert.deepEqual(keys, expectedKeys);
});
// supports full value, key, callback (shortcut) interface
function asyncJob(item, key, cb)
{
// different delays (in ms) per item
var delay = item * 25;
// pretend different jobs take different time to finish
// and not in consequential order
var timeoutId = setTimeout(function() {
keys.push(key);
target.push(item);
cb(null, item * 2);
}, delay);
// allow to cancel "leftover" jobs upon error
// return function, invoking of which will abort this job
return clearTimeout.bind(null, timeoutId);
}
```
More examples could be found in [test/test-parallel-object.js](test/test-parallel-object.js).
### Serial Jobs
Runs iterator over provided array sequentially. Stores output in the `result` array,
on the matching positions. In unlikely event of an error from one of the jobs,
will not proceed to the rest of the items in the list
and return error along with salvaged data to the main callback function.
#### Input Array
```javascript
var serial = require('asynckit/serial')
, assert = require('assert')
;
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
, target = []
;
serial(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
});
// extended interface (item, key, callback)
// also supported for arrays
function asyncJob(item, key, cb)
{
target.push(key);
// it will be automatically made async
// even it iterator "returns" in the same event loop
cb(null, item * 2);
}
```
More examples could be found in [test/test-serial-array.js](test/test-serial-array.js).
#### Input Object
Also it supports named jobs, listed via object.
```javascript
var serial = require('asynckit').serial
, assert = require('assert')
;
var source = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, expectedResult = [ 2, 2, 8, 32, 128, 64, 16, 4 ]
, expectedTarget = [ 0, 1, 2, 3, 4, 5, 6, 7 ]
, target = []
;
var source = { first: 1, one: 1, four: 4, sixteen: 16, sixtyFour: 64, thirtyTwo: 32, eight: 8, two: 2 }
, expectedResult = { first: 2, one: 2, four: 8, sixteen: 32, sixtyFour: 128, thirtyTwo: 64, eight: 16, two: 4 }
, expectedTarget = [ 1, 1, 4, 16, 64, 32, 8, 2 ]
, target = []
;
serial(source, asyncJob, function(err, result)
{
assert.deepEqual(result, expectedResult);
assert.deepEqual(target, expectedTarget);
});
// shortcut interface (item, callback)
// works for object as well as for the arrays
function asyncJob(item, cb)
{
target.push(item);
// it will be automatically made async
// even it iterator "returns" in the same event loop
cb(null, item * 2);
}
```
More examples could be found in [test/test-serial-object.js](test/test-serial-object.js).
_Note: Since _object_ is an _unordered_ collection of properties,
it may produce unexpected results with sequential iterations.
Whenever order of the jobs' execution is important please use `serialOrdered` method._
### Ordered Serial Iterations
TBD
For example [compare-property](compare-property) package.
### Streaming interface
TBD
## Want to Know More?
More examples can be found in [test folder](test/).
Or open an [issue](https://github.com/alexindigo/asynckit/issues) with questions and/or suggestions.
## License
AsyncKit is licensed under the MIT license.

76
node_modules/asynckit/bench.js generated vendored
View File

@ -1,76 +0,0 @@
/* eslint no-console: "off" */
var asynckit = require('./')
, async = require('async')
, assert = require('assert')
, expected = 0
;
var Benchmark = require('benchmark');
var suite = new Benchmark.Suite;
var source = [];
for (var z = 1; z < 100; z++)
{
source.push(z);
expected += z;
}
suite
// add tests
.add('async.map', function(deferred)
{
var total = 0;
async.map(source,
function(i, cb)
{
setImmediate(function()
{
total += i;
cb(null, total);
});
},
function(err, result)
{
assert.ifError(err);
assert.equal(result[result.length - 1], expected);
deferred.resolve();
});
}, {'defer': true})
.add('asynckit.parallel', function(deferred)
{
var total = 0;
asynckit.parallel(source,
function(i, cb)
{
setImmediate(function()
{
total += i;
cb(null, total);
});
},
function(err, result)
{
assert.ifError(err);
assert.equal(result[result.length - 1], expected);
deferred.resolve();
});
}, {'defer': true})
// add listeners
.on('cycle', function(ev)
{
console.log(String(ev.target));
})
.on('complete', function()
{
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
// run async
.run({ 'async': true });

6
node_modules/asynckit/index.js generated vendored
View File

@ -1,6 +0,0 @@
module.exports =
{
parallel : require('./parallel.js'),
serial : require('./serial.js'),
serialOrdered : require('./serialOrdered.js')
};

29
node_modules/asynckit/lib/abort.js generated vendored
View File

@ -1,29 +0,0 @@
// API
module.exports = abort;
/**
* Aborts leftover active jobs
*
* @param {object} state - current state object
*/
function abort(state)
{
Object.keys(state.jobs).forEach(clean.bind(state));
// reset leftover jobs
state.jobs = {};
}
/**
* Cleans up leftover job by invoking abort function for the provided job id
*
* @this state
* @param {string|number} key - job id to abort
*/
function clean(key)
{
if (typeof this.jobs[key] == 'function')
{
this.jobs[key]();
}
}

34
node_modules/asynckit/lib/async.js generated vendored
View File

@ -1,34 +0,0 @@
var defer = require('./defer.js');
// API
module.exports = async;
/**
* Runs provided callback asynchronously
* even if callback itself is not
*
* @param {function} callback - callback to invoke
* @returns {function} - augmented callback
*/
function async(callback)
{
var isAsync = false;
// check if async happened
defer(function() { isAsync = true; });
return function async_callback(err, result)
{
if (isAsync)
{
callback(err, result);
}
else
{
defer(function nextTick_callback()
{
callback(err, result);
});
}
};
}

26
node_modules/asynckit/lib/defer.js generated vendored
View File

@ -1,26 +0,0 @@
module.exports = defer;
/**
* Runs provided function on next iteration of the event loop
*
* @param {function} fn - function to run
*/
function defer(fn)
{
var nextTick = typeof setImmediate == 'function'
? setImmediate
: (
typeof process == 'object' && typeof process.nextTick == 'function'
? process.nextTick
: null
);
if (nextTick)
{
nextTick(fn);
}
else
{
setTimeout(fn, 0);
}
}

75
node_modules/asynckit/lib/iterate.js generated vendored
View File

@ -1,75 +0,0 @@
var async = require('./async.js')
, abort = require('./abort.js')
;
// API
module.exports = iterate;
/**
* Iterates over each job object
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {object} state - current job status
* @param {function} callback - invoked when all elements processed
*/
function iterate(list, iterator, state, callback)
{
// store current index
var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;
state.jobs[key] = runJob(iterator, key, list[key], function(error, output)
{
// don't repeat yourself
// skip secondary callbacks
if (!(key in state.jobs))
{
return;
}
// clean up jobs
delete state.jobs[key];
if (error)
{
// don't process rest of the results
// stop still active jobs
// and reset the list
abort(state);
}
else
{
state.results[key] = output;
}
// return salvaged results
callback(error, state.results);
});
}
/**
* Runs iterator over provided job element
*
* @param {function} iterator - iterator to invoke
* @param {string|number} key - key/index of the element in the list of jobs
* @param {mixed} item - job description
* @param {function} callback - invoked after iterator is done with the job
* @returns {function|mixed} - job abort function or something else
*/
function runJob(iterator, key, item, callback)
{
var aborter;
// allow shortcut if iterator expects only two arguments
if (iterator.length == 2)
{
aborter = iterator(item, async(callback));
}
// otherwise go with full three arguments
else
{
aborter = iterator(item, key, async(callback));
}
return aborter;
}

View File

@ -1,91 +0,0 @@
var streamify = require('./streamify.js')
, defer = require('./defer.js')
;
// API
module.exports = ReadableAsyncKit;
/**
* Base constructor for all streams
* used to hold properties/methods
*/
function ReadableAsyncKit()
{
ReadableAsyncKit.super_.apply(this, arguments);
// list of active jobs
this.jobs = {};
// add stream methods
this.destroy = destroy;
this._start = _start;
this._read = _read;
}
/**
* Destroys readable stream,
* by aborting outstanding jobs
*
* @returns {void}
*/
function destroy()
{
if (this.destroyed)
{
return;
}
this.destroyed = true;
if (typeof this.terminator == 'function')
{
this.terminator();
}
}
/**
* Starts provided jobs in async manner
*
* @private
*/
function _start()
{
// first argument runner function
var runner = arguments[0]
// take away first argument
, args = Array.prototype.slice.call(arguments, 1)
// second argument - input data
, input = args[0]
// last argument - result callback
, endCb = streamify.callback.call(this, args[args.length - 1])
;
args[args.length - 1] = endCb;
// third argument - iterator
args[1] = streamify.iterator.call(this, args[1]);
// allow time for proper setup
defer(function()
{
if (!this.destroyed)
{
this.terminator = runner.apply(null, args);
}
else
{
endCb(null, Array.isArray(input) ? [] : {});
}
}.bind(this));
}
/**
* Implement _read to comply with Readable streams
* Doesn't really make sense for flowing object mode
*
* @private
*/
function _read()
{
}

View File

@ -1,25 +0,0 @@
var parallel = require('../parallel.js');
// API
module.exports = ReadableParallel;
/**
* Streaming wrapper to `asynckit.parallel`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableParallel(list, iterator, callback)
{
if (!(this instanceof ReadableParallel))
{
return new ReadableParallel(list, iterator, callback);
}
// turn on object mode
ReadableParallel.super_.call(this, {objectMode: true});
this._start(parallel, list, iterator, callback);
}

View File

@ -1,25 +0,0 @@
var serial = require('../serial.js');
// API
module.exports = ReadableSerial;
/**
* Streaming wrapper to `asynckit.serial`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableSerial(list, iterator, callback)
{
if (!(this instanceof ReadableSerial))
{
return new ReadableSerial(list, iterator, callback);
}
// turn on object mode
ReadableSerial.super_.call(this, {objectMode: true});
this._start(serial, list, iterator, callback);
}

View File

@ -1,29 +0,0 @@
var serialOrdered = require('../serialOrdered.js');
// API
module.exports = ReadableSerialOrdered;
// expose sort helpers
module.exports.ascending = serialOrdered.ascending;
module.exports.descending = serialOrdered.descending;
/**
* Streaming wrapper to `asynckit.serialOrdered`
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {stream.Readable#}
*/
function ReadableSerialOrdered(list, iterator, sortMethod, callback)
{
if (!(this instanceof ReadableSerialOrdered))
{
return new ReadableSerialOrdered(list, iterator, sortMethod, callback);
}
// turn on object mode
ReadableSerialOrdered.super_.call(this, {objectMode: true});
this._start(serialOrdered, list, iterator, sortMethod, callback);
}

37
node_modules/asynckit/lib/state.js generated vendored
View File

@ -1,37 +0,0 @@
// API
module.exports = state;
/**
* Creates initial state object
* for iteration over list
*
* @param {array|object} list - list to iterate over
* @param {function|null} sortMethod - function to use for keys sort,
* or `null` to keep them as is
* @returns {object} - initial state object
*/
function state(list, sortMethod)
{
var isNamedList = !Array.isArray(list)
, initState =
{
index : 0,
keyedList: isNamedList || sortMethod ? Object.keys(list) : null,
jobs : {},
results : isNamedList ? {} : [],
size : isNamedList ? Object.keys(list).length : list.length
}
;
if (sortMethod)
{
// sort array keys based on it's values
// sort object's keys just on own merit
initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)
{
return sortMethod(list[a], list[b]);
});
}
return initState;
}

View File

@ -1,141 +0,0 @@
var async = require('./async.js');
// API
module.exports = {
iterator: wrapIterator,
callback: wrapCallback
};
/**
* Wraps iterators with long signature
*
* @this ReadableAsyncKit#
* @param {function} iterator - function to wrap
* @returns {function} - wrapped function
*/
function wrapIterator(iterator)
{
var stream = this;
return function(item, key, cb)
{
var aborter
, wrappedCb = async(wrapIteratorCallback.call(stream, cb, key))
;
stream.jobs[key] = wrappedCb;
// it's either shortcut (item, cb)
if (iterator.length == 2)
{
aborter = iterator(item, wrappedCb);
}
// or long format (item, key, cb)
else
{
aborter = iterator(item, key, wrappedCb);
}
return aborter;
};
}
/**
* Wraps provided callback function
* allowing to execute snitch function before
* real callback
*
* @this ReadableAsyncKit#
* @param {function} callback - function to wrap
* @returns {function} - wrapped function
*/
function wrapCallback(callback)
{
var stream = this;
var wrapped = function(error, result)
{
return finisher.call(stream, error, result, callback);
};
return wrapped;
}
/**
* Wraps provided iterator callback function
* makes sure snitch only called once,
* but passes secondary calls to the original callback
*
* @this ReadableAsyncKit#
* @param {function} callback - callback to wrap
* @param {number|string} key - iteration key
* @returns {function} wrapped callback
*/
function wrapIteratorCallback(callback, key)
{
var stream = this;
return function(error, output)
{
// don't repeat yourself
if (!(key in stream.jobs))
{
callback(error, output);
return;
}
// clean up jobs
delete stream.jobs[key];
return streamer.call(stream, error, {key: key, value: output}, callback);
};
}
/**
* Stream wrapper for iterator callback
*
* @this ReadableAsyncKit#
* @param {mixed} error - error response
* @param {mixed} output - iterator output
* @param {function} callback - callback that expects iterator results
*/
function streamer(error, output, callback)
{
if (error && !this.error)
{
this.error = error;
this.pause();
this.emit('error', error);
// send back value only, as expected
callback(error, output && output.value);
return;
}
// stream stuff
this.push(output);
// back to original track
// send back value only, as expected
callback(error, output && output.value);
}
/**
* Stream wrapper for finishing callback
*
* @this ReadableAsyncKit#
* @param {mixed} error - error response
* @param {mixed} output - iterator output
* @param {function} callback - callback that expects final results
*/
function finisher(error, output, callback)
{
// signal end of the stream
// only for successfully finished streams
if (!error)
{
this.push(null);
}
// back to original track
callback(error, output);
}

View File

@ -1,29 +0,0 @@
var abort = require('./abort.js')
, async = require('./async.js')
;
// API
module.exports = terminator;
/**
* Terminates jobs in the attached state context
*
* @this AsyncKitState#
* @param {function} callback - final callback to invoke after termination
*/
function terminator(callback)
{
if (!Object.keys(this.jobs).length)
{
return;
}
// fast forward iteration index
this.index = this.size;
// abort jobs
abort(this);
// send back results we have so far
async(callback)(null, this.results);
}

63
node_modules/asynckit/package.json generated vendored
View File

@ -1,63 +0,0 @@
{
"name": "asynckit",
"version": "0.4.0",
"description": "Minimal async jobs utility library, with streams support",
"main": "index.js",
"scripts": {
"clean": "rimraf coverage",
"lint": "eslint *.js lib/*.js test/*.js",
"test": "istanbul cover --reporter=json tape -- 'test/test-*.js' | tap-spec",
"win-test": "tape test/test-*.js",
"browser": "browserify -t browserify-istanbul test/lib/browserify_adjustment.js test/test-*.js | obake --coverage | tap-spec",
"report": "istanbul report",
"size": "browserify index.js | size-table asynckit",
"debug": "tape test/test-*.js"
},
"pre-commit": [
"clean",
"lint",
"test",
"browser",
"report",
"size"
],
"repository": {
"type": "git",
"url": "git+https://github.com/alexindigo/asynckit.git"
},
"keywords": [
"async",
"jobs",
"parallel",
"serial",
"iterator",
"array",
"object",
"stream",
"destroy",
"terminate",
"abort"
],
"author": "Alex Indigo <iam@alexindigo.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/alexindigo/asynckit/issues"
},
"homepage": "https://github.com/alexindigo/asynckit#readme",
"devDependencies": {
"browserify": "^13.0.0",
"browserify-istanbul": "^2.0.0",
"coveralls": "^2.11.9",
"eslint": "^2.9.0",
"istanbul": "^0.4.3",
"obake": "^0.1.2",
"phantomjs-prebuilt": "^2.1.7",
"pre-commit": "^1.1.3",
"reamde": "^1.1.0",
"rimraf": "^2.5.2",
"size-table": "^0.2.0",
"tap-spec": "^4.1.1",
"tape": "^4.5.1"
},
"dependencies": {}
}

43
node_modules/asynckit/parallel.js generated vendored
View File

@ -1,43 +0,0 @@
var iterate = require('./lib/iterate.js')
, initState = require('./lib/state.js')
, terminator = require('./lib/terminator.js')
;
// Public API
module.exports = parallel;
/**
* Runs iterator over provided array elements in parallel
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function parallel(list, iterator, callback)
{
var state = initState(list);
while (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, function(error, result)
{
if (error)
{
callback(error, result);
return;
}
// looks like it's the last one
if (Object.keys(state.jobs).length === 0)
{
callback(null, state.results);
return;
}
});
state.index++;
}
return terminator.bind(state, callback);
}

17
node_modules/asynckit/serial.js generated vendored
View File

@ -1,17 +0,0 @@
var serialOrdered = require('./serialOrdered.js');
// Public API
module.exports = serial;
/**
* Runs iterator over provided array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serial(list, iterator, callback)
{
return serialOrdered(list, iterator, null, callback);
}

View File

@ -1,75 +0,0 @@
var iterate = require('./lib/iterate.js')
, initState = require('./lib/state.js')
, terminator = require('./lib/terminator.js')
;
// Public API
module.exports = serialOrdered;
// sorting helpers
module.exports.ascending = ascending;
module.exports.descending = descending;
/**
* Runs iterator over provided sorted array elements in series
*
* @param {array|object} list - array or object (named list) to iterate over
* @param {function} iterator - iterator to run
* @param {function} sortMethod - custom sort function
* @param {function} callback - invoked when all elements processed
* @returns {function} - jobs terminator
*/
function serialOrdered(list, iterator, sortMethod, callback)
{
var state = initState(list, sortMethod);
iterate(list, iterator, state, function iteratorHandler(error, result)
{
if (error)
{
callback(error, result);
return;
}
state.index++;
// are we there yet?
if (state.index < (state['keyedList'] || list).length)
{
iterate(list, iterator, state, iteratorHandler);
return;
}
// done here
callback(null, state.results);
});
return terminator.bind(state, callback);
}
/*
* -- Sort methods
*/
/**
* sort helper to sort array elements in ascending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function ascending(a, b)
{
return a < b ? -1 : a > b ? 1 : 0;
}
/**
* sort helper to sort array elements in descending order
*
* @param {mixed} a - an item to compare
* @param {mixed} b - an item to compare
* @returns {number} - comparison result
*/
function descending(a, b)
{
return -1 * ascending(a, b);
}

21
node_modules/asynckit/stream.js generated vendored
View File

@ -1,21 +0,0 @@
var inherits = require('util').inherits
, Readable = require('stream').Readable
, ReadableAsyncKit = require('./lib/readable_asynckit.js')
, ReadableParallel = require('./lib/readable_parallel.js')
, ReadableSerial = require('./lib/readable_serial.js')
, ReadableSerialOrdered = require('./lib/readable_serial_ordered.js')
;
// API
module.exports =
{
parallel : ReadableParallel,
serial : ReadableSerial,
serialOrdered : ReadableSerialOrdered,
};
inherits(ReadableAsyncKit, Readable);
inherits(ReadableParallel, ReadableAsyncKit);
inherits(ReadableSerial, ReadableAsyncKit);
inherits(ReadableSerialOrdered, ReadableAsyncKit);

1492
node_modules/axios/CHANGELOG.md generated vendored

File diff suppressed because it is too large Load Diff

20
node_modules/axios/LICENSE generated vendored
View File

@ -1,7 +1,19 @@
# Copyright (c) 2014-present Matt Zabriskie & Collaborators
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:
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 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.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,3 +0,0 @@
# Migration Guide
## 0.x.x -> 1.1.0

969
node_modules/axios/README.md generated vendored Normal file → Executable file

File diff suppressed because it is too large Load Diff

7
node_modules/axios/SECURITY.md generated vendored
View File

@ -1,6 +1,5 @@
# Reporting a Vulnerability
# Security Policy
If you discover a security vulnerability in axios please disclose it via [our huntr page](https://huntr.dev/repos/axios/axios/). Bounty eligibility, CVE assignment, response times and past reports are all there.
## Reporting a Vulnerability
Thank you for improving the security of axios.
Please report security issues to jasonsaayman@gmail.com

5031
node_modules/axios/dist/axios.js generated vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

3281
node_modules/axios/dist/esm/axios.js generated vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

4355
node_modules/axios/dist/node/axios.cjs generated vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

542
node_modules/axios/index.d.cts generated vendored
View File

@ -1,542 +0,0 @@
interface RawAxiosHeaders {
[key: string]: axios.AxiosHeaderValue;
}
type MethodsHeaders = Partial<{
[Key in axios.Method as Lowercase<Key>]: AxiosHeaders;
} & {common: AxiosHeaders}>;
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
type AxiosHeaderParser = (this: AxiosHeaders, value: axios.AxiosHeaderValue, header: string) => any;
type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent'| 'Content-Encoding' | 'Authorization';
type ContentType = axios.AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding';
declare class AxiosHeaders {
constructor(
headers?: RawAxiosHeaders | AxiosHeaders | string
);
[key: string]: any;
set(headerName?: string, value?: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue;
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clear(matcher?: AxiosHeaderMatcher): boolean;
normalize(format: boolean): AxiosHeaders;
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
toJSON(asStrings?: boolean): RawAxiosHeaders;
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
static accessor(header: string | string[]): AxiosHeaders;
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentType(parser?: RegExp): RegExpExecArray | null;
getContentType(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
setContentLength(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentLength(parser?: RegExp): RegExpExecArray | null;
getContentLength(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
setAccept(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAccept(parser?: RegExp): RegExpExecArray | null;
getAccept(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
setUserAgent(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getUserAgent(parser?: RegExp): RegExpExecArray | null;
getUserAgent(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
setContentEncoding(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
getContentEncoding(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
setAuthorization(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAuthorization(parser?: RegExp): RegExpExecArray | null;
getAuthorization(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
[Symbol.iterator](): IterableIterator<[string, axios.AxiosHeaderValue]>;
}
declare class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: axios.InternalAxiosRequestConfig<D>,
request?: any,
response?: axios.AxiosResponse<T, D>
);
config?: axios.InternalAxiosRequestConfig<D>;
code?: string;
request?: any;
response?: axios.AxiosResponse<T, D>;
isAxiosError: boolean;
status?: number;
toJSON: () => object;
cause?: Error;
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
static readonly ERR_NETWORK = "ERR_NETWORK";
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
static readonly ERR_INVALID_URL = "ERR_INVALID_URL";
static readonly ERR_CANCELED = "ERR_CANCELED";
static readonly ECONNABORTED = "ECONNABORTED";
static readonly ETIMEDOUT = "ETIMEDOUT";
}
declare class CanceledError<T> extends AxiosError<T> {
}
declare class Axios {
constructor(config?: axios.AxiosRequestConfig);
defaults: axios.AxiosDefaults;
interceptors: {
request: axios.AxiosInterceptorManager<axios.InternalAxiosRequestConfig>;
response: axios.AxiosInterceptorManager<axios.AxiosResponse>;
};
getUri(config?: axios.AxiosRequestConfig): string;
request<T = any, R = axios.AxiosResponse<T>, D = any>(config: axios.AxiosRequestConfig<D>): Promise<R>;
get<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
delete<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
head<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
options<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, config?: axios.AxiosRequestConfig<D>): Promise<R>;
post<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
put<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
patch<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
postForm<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
putForm<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
patchForm<T = any, R = axios.AxiosResponse<T>, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig<D>): Promise<R>;
}
declare enum HttpStatusCode {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
Ok = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UriTooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
ImATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511,
}
type InternalAxiosError<T = unknown, D = any> = AxiosError<T, D>;
declare namespace axios {
type AxiosError<T = unknown, D = any> = InternalAxiosError<T, D>;
type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
} & {
'Content-Type': ContentType
}>;
type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
type RawCommonResponseHeaders = {
[Key in CommonResponseHeadersList]: AxiosHeaderValue;
} & {
"set-cookie": string[];
};
type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
interface AxiosRequestTransformer {
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
}
interface AxiosResponseTransformer {
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
}
interface AxiosAdapter {
(config: InternalAxiosRequestConfig): AxiosPromise;
}
interface AxiosBasicCredentials {
username: string;
password: string;
}
interface AxiosProxyConfig {
host: string;
port: number;
auth?: AxiosBasicCredentials;
protocol?: string;
}
type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK';
type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream';
type responseEncoding =
| 'ascii' | 'ASCII'
| 'ansi' | 'ANSI'
| 'binary' | 'BINARY'
| 'base64' | 'BASE64'
| 'base64url' | 'BASE64URL'
| 'hex' | 'HEX'
| 'latin1' | 'LATIN1'
| 'ucs-2' | 'UCS-2'
| 'ucs2' | 'UCS2'
| 'utf-8' | 'UTF-8'
| 'utf8' | 'UTF8'
| 'utf16le' | 'UTF16LE';
interface TransitionalOptions {
silentJSONParsing?: boolean;
forcedJSONParsing?: boolean;
clarifyTimeoutError?: boolean;
}
interface GenericAbortSignal {
readonly aborted: boolean;
onabort?: ((...args: any) => any) | null;
addEventListener?: (...args: any) => any;
removeEventListener?: (...args: any) => any;
}
interface FormDataVisitorHelpers {
defaultVisitor: SerializerVisitor;
convertValue: (value: any) => any;
isVisitable: (value: any) => boolean;
}
interface SerializerVisitor {
(
this: GenericFormData,
value: any,
key: string | number,
path: null | Array<string | number>,
helpers: FormDataVisitorHelpers
): boolean;
}
interface SerializerOptions {
visitor?: SerializerVisitor;
dots?: boolean;
metaTokens?: boolean;
indexes?: boolean | null;
}
// tslint:disable-next-line
interface FormSerializerOptions extends SerializerOptions {
}
interface ParamEncoder {
(value: any, defaultEncoder: (value: any) => any): any;
}
interface CustomParamsSerializer {
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
}
interface ParamsSerializerOptions extends SerializerOptions {
encode?: ParamEncoder;
serialize?: CustomParamsSerializer;
}
type MaxUploadRate = number;
type MaxDownloadRate = number;
type BrowserProgressEvent = any;
interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
}
type Milliseconds = number;
type AxiosAdapterName = 'xhr' | 'http' | string;
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
type AddressFamily = 4 | 6 | undefined;
interface LookupAddressEntry {
address: string;
family?: AddressFamily;
}
type LookupAddress = string | LookupAddressEntry;
interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>, statusCode: HttpStatusCode}) => void;
socketPath?: string | null;
transport?: any;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
formSerializer?: FormSerializerOptions;
family?: AddressFamily;
lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
}
// Alias
type RawAxiosRequestConfig<D = any> = AxiosRequestConfig<D>;
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig {
headers: AxiosRequestHeaders;
}
interface HeadersDefaults {
common: RawAxiosRequestHeaders;
delete: RawAxiosRequestHeaders;
get: RawAxiosRequestHeaders;
head: RawAxiosRequestHeaders;
post: RawAxiosRequestHeaders;
put: RawAxiosRequestHeaders;
patch: RawAxiosRequestHeaders;
options?: RawAxiosRequestHeaders;
purge?: RawAxiosRequestHeaders;
link?: RawAxiosRequestHeaders;
unlink?: RawAxiosRequestHeaders;
}
interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers: HeadersDefaults;
}
interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
}
interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
}
type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
interface CancelStatic {
new (message?: string): Cancel;
}
interface Cancel {
message: string | undefined;
}
interface Canceler {
(message?: string, config?: AxiosRequestConfig, request?: any): void;
}
interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
}
interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
}
interface AxiosInterceptorOptions {
synchronous?: boolean;
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
}
interface AxiosInterceptorManager<V> {
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number;
eject(id: number): void;
clear(): void;
}
interface AxiosInstance extends Axios {
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
defaults: Omit<AxiosDefaults, 'headers'> & {
headers: HeadersDefaults & {
[key: string]: AxiosHeaderValue
}
};
}
interface GenericFormData {
append(name: string, value: any, options?: any): any;
}
interface GenericHTMLFormElement {
name: string;
method: string;
submit(): void;
}
interface AxiosStatic extends AxiosInstance {
create(config?: CreateAxiosDefaults): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
Axios: typeof Axios;
AxiosError: typeof AxiosError;
CanceledError: typeof CanceledError;
HttpStatusCode: typeof HttpStatusCode;
readonly VERSION: string;
isCancel(value: any): value is Cancel;
all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
AxiosHeaders: typeof AxiosHeaders;
}
}
declare const axios: axios.AxiosStatic;
export = axios;

495
node_modules/axios/index.d.ts generated vendored
View File

@ -1,116 +1,9 @@
// TypeScript Version: 4.7
export type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
interface RawAxiosHeaders {
[key: string]: AxiosHeaderValue;
}
type MethodsHeaders = Partial<{
[Key in Method as Lowercase<Key>]: AxiosHeaders;
} & {common: AxiosHeaders}>;
type AxiosHeaderMatcher = string | RegExp | ((this: AxiosHeaders, value: string, name: string) => boolean);
type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;
export class AxiosHeaders {
constructor(
headers?: RawAxiosHeaders | AxiosHeaders | string
);
[key: string]: any;
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clear(matcher?: AxiosHeaderMatcher): boolean;
normalize(format: boolean): AxiosHeaders;
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
toJSON(asStrings?: boolean): RawAxiosHeaders;
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
static accessor(header: string | string[]): AxiosHeaders;
static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentType(parser?: RegExp): RegExpExecArray | null;
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentLength(parser?: RegExp): RegExpExecArray | null;
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAccept(parser?: RegExp): RegExpExecArray | null;
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getUserAgent(parser?: RegExp): RegExpExecArray | null;
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAuthorization(parser?: RegExp): RegExpExecArray | null;
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;
}
type CommonRequestHeadersList = 'Accept' | 'Content-Length' | 'User-Agent' | 'Content-Encoding' | 'Authorization';
type ContentType = AxiosHeaderValue | 'text/html' | 'text/plain' | 'multipart/form-data' | 'application/json' | 'application/x-www-form-urlencoded' | 'application/octet-stream';
export type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & {
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
} & {
'Content-Type': ContentType
}>;
export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
type CommonResponseHeadersList = 'Server' | 'Content-Type' | 'Content-Length' | 'Cache-Control'| 'Content-Encoding';
type RawCommonResponseHeaders = {
[Key in CommonResponseHeadersList]: AxiosHeaderValue;
} & {
"set-cookie": string[];
};
export type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
export interface AxiosRequestTransformer {
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
}
export interface AxiosResponseTransformer {
(this: InternalAxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
export interface AxiosTransformer {
(data: any, headers?: any): any;
}
export interface AxiosAdapter {
(config: InternalAxiosRequestConfig): AxiosPromise;
(config: AxiosRequestConfig): AxiosPromise<any>;
}
export interface AxiosBasicCredentials {
@ -121,76 +14,13 @@ export interface AxiosBasicCredentials {
export interface AxiosProxyConfig {
host: string;
port: number;
auth?: AxiosBasicCredentials;
auth?: {
username: string;
password:string;
};
protocol?: string;
}
export enum HttpStatusCode {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
Ok = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UriTooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
ImATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511,
}
export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
@ -201,7 +31,7 @@ export type Method =
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK';
| 'unlink' | 'UNLINK'
export type ResponseType =
| 'arraybuffer'
@ -209,247 +39,78 @@ export type ResponseType =
| 'document'
| 'json'
| 'text'
| 'stream';
export type responseEncoding =
| 'ascii' | 'ASCII'
| 'ansi' | 'ANSI'
| 'binary' | 'BINARY'
| 'base64' | 'BASE64'
| 'base64url' | 'BASE64URL'
| 'hex' | 'HEX'
| 'latin1' | 'LATIN1'
| 'ucs-2' | 'UCS-2'
| 'ucs2' | 'UCS2'
| 'utf-8' | 'UTF-8'
| 'utf8' | 'UTF8'
| 'utf16le' | 'UTF16LE';
| 'stream'
export interface TransitionalOptions{
silentJSONParsing?: boolean;
forcedJSONParsing?: boolean;
clarifyTimeoutError?: boolean;
silentJSONParsing: boolean;
forcedJSONParsing: boolean;
clarifyTimeoutError: boolean;
}
export interface GenericAbortSignal {
readonly aborted: boolean;
onabort?: ((...args: any) => any) | null;
addEventListener?: (...args: any) => any;
removeEventListener?: (...args: any) => any;
}
export interface FormDataVisitorHelpers {
defaultVisitor: SerializerVisitor;
convertValue: (value: any) => any;
isVisitable: (value: any) => boolean;
}
export interface SerializerVisitor {
(
this: GenericFormData,
value: any,
key: string | number,
path: null | Array<string | number>,
helpers: FormDataVisitorHelpers
): boolean;
}
export interface SerializerOptions {
visitor?: SerializerVisitor;
dots?: boolean;
metaTokens?: boolean;
indexes?: boolean | null;
}
// tslint:disable-next-line
export interface FormSerializerOptions extends SerializerOptions {
}
export interface ParamEncoder {
(value: any, defaultEncoder: (value: any) => any): any;
}
export interface CustomParamsSerializer {
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
}
export interface ParamsSerializerOptions extends SerializerOptions {
encode?: ParamEncoder;
serialize?: CustomParamsSerializer;
}
type MaxUploadRate = number;
type MaxDownloadRate = number;
type BrowserProgressEvent = any;
export interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
}
type Milliseconds = number;
type AxiosAdapterName = 'xhr' | 'http' | string;
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
export type AddressFamily = 4 | 6 | undefined;
export interface LookupAddressEntry {
address: string;
family?: AddressFamily;
}
export type LookupAddress = string | LookupAddressEntry;
export interface AxiosRequestConfig<D = any> {
export interface AxiosRequestConfig {
url?: string;
method?: Method | string;
method?: Method;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
transformRequest?: AxiosTransformer | AxiosTransformer[];
transformResponse?: AxiosTransformer | AxiosTransformer[];
headers?: any;
params?: any;
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
data?: D;
timeout?: Milliseconds;
paramsSerializer?: (params: any) => string;
data?: any;
timeout?: number;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
adapter?: AxiosAdapter;
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
onUploadProgress?: (progressEvent: any) => void;
onDownloadProgress?: (progressEvent: any) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>, statusCode: HttpStatusCode}) => void;
socketPath?: string | null;
transport?: any;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
};
formSerializer?: FormSerializerOptions;
family?: AddressFamily;
lookup?: ((hostname: string, options: object, cb: (err: Error | null, address: LookupAddress | LookupAddress[], family?: AddressFamily) => void) => void) |
((hostname: string, options: object) => Promise<[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress>);
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
transitional?: TransitionalOptions
}
// Alias
export type RawAxiosRequestConfig<D = any> = AxiosRequestConfig<D>;
export interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
headers: AxiosRequestHeaders;
}
export interface HeadersDefaults {
common: RawAxiosRequestHeaders;
delete: RawAxiosRequestHeaders;
get: RawAxiosRequestHeaders;
head: RawAxiosRequestHeaders;
post: RawAxiosRequestHeaders;
put: RawAxiosRequestHeaders;
patch: RawAxiosRequestHeaders;
options?: RawAxiosRequestHeaders;
purge?: RawAxiosRequestHeaders;
link?: RawAxiosRequestHeaders;
unlink?: RawAxiosRequestHeaders;
}
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers: HeadersDefaults;
}
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
}
export interface AxiosResponse<T = any, D = any> {
export interface AxiosResponse<T = any> {
data: T;
status: number;
statusText: string;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
headers: any;
config: AxiosRequestConfig;
request?: any;
}
export class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
);
config?: InternalAxiosRequestConfig<D>;
export interface AxiosError<T = any> extends Error {
config: AxiosRequestConfig;
code?: string;
request?: any;
response?: AxiosResponse<T, D>;
response?: AxiosResponse<T>;
isAxiosError: boolean;
status?: number;
toJSON: () => object;
cause?: Error;
static from<T = unknown, D = any>(
error: Error | unknown,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>,
customProps?: object,
): AxiosError<T, D>;
static readonly ERR_FR_TOO_MANY_REDIRECTS = "ERR_FR_TOO_MANY_REDIRECTS";
static readonly ERR_BAD_OPTION_VALUE = "ERR_BAD_OPTION_VALUE";
static readonly ERR_BAD_OPTION = "ERR_BAD_OPTION";
static readonly ERR_NETWORK = "ERR_NETWORK";
static readonly ERR_DEPRECATED = "ERR_DEPRECATED";
static readonly ERR_BAD_RESPONSE = "ERR_BAD_RESPONSE";
static readonly ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
static readonly ERR_NOT_SUPPORT = "ERR_NOT_SUPPORT";
static readonly ERR_INVALID_URL = "ERR_INVALID_URL";
static readonly ERR_CANCELED = "ERR_CANCELED";
static readonly ECONNABORTED = "ECONNABORTED";
static readonly ETIMEDOUT = "ETIMEDOUT";
}
export class CanceledError<T> extends AxiosError<T> {
export interface AxiosPromise<T = any> extends Promise<AxiosResponse<T>> {
}
export type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
export interface CancelStatic {
new (message?: string): Cancel;
}
export interface Cancel {
message: string | undefined;
message: string;
}
export interface Canceler {
(message?: string, config?: AxiosRequestConfig, request?: any): void;
(message?: string): void;
}
export interface CancelTokenStatic {
@ -468,90 +129,38 @@ export interface CancelTokenSource {
cancel: Canceler;
}
export interface AxiosInterceptorOptions {
synchronous?: boolean;
runWhen?: (config: InternalAxiosRequestConfig) => boolean;
}
export interface AxiosInterceptorManager<V> {
use(onFulfilled?: ((value: V) => V | Promise<V>) | null, onRejected?: ((error: any) => any) | null, options?: AxiosInterceptorOptions): number;
use<T = V>(onFulfilled?: (value: V) => T | Promise<T>, onRejected?: (error: any) => any): number;
eject(id: number): void;
clear(): void;
}
export class Axios {
constructor(config?: AxiosRequestConfig);
defaults: AxiosDefaults;
export interface AxiosInstance {
(config: AxiosRequestConfig): AxiosPromise;
(url: string, config?: AxiosRequestConfig): AxiosPromise;
defaults: AxiosRequestConfig;
interceptors: {
request: AxiosInterceptorManager<InternalAxiosRequestConfig>;
request: AxiosInterceptorManager<AxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
getUri(config?: AxiosRequestConfig): string;
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
get<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
delete<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
head<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
options<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
post<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
put<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
patch<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
postForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
putForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
patchForm<T = any, R = AxiosResponse<T>, D = any>(url: string, data?: D, config?: AxiosRequestConfig<D>): Promise<R>;
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 AxiosInstance extends Axios {
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
defaults: Omit<AxiosDefaults, 'headers'> & {
headers: HeadersDefaults & {
[key: string]: AxiosHeaderValue
}
};
}
export interface GenericFormData {
append(name: string, value: any, options?: any): any;
}
export interface GenericHTMLFormElement {
name: string;
method: string;
submit(): void;
}
export function getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
export function toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData;
export function formToJSON(form: GenericFormData|GenericHTMLFormElement): object;
export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
export function isCancel(value: any): value is Cancel;
export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
export interface AxiosStatic extends AxiosInstance {
create(config?: CreateAxiosDefaults): AxiosInstance;
create(config?: AxiosRequestConfig): AxiosInstance;
Cancel: CancelStatic;
CancelToken: CancelTokenStatic;
Axios: typeof Axios;
AxiosError: typeof AxiosError;
HttpStatusCode: typeof HttpStatusCode;
readonly VERSION: string;
isCancel: typeof isCancel;
all: typeof all;
spread: typeof spread;
isAxiosError: typeof isAxiosError;
toFormData: typeof toFormData;
formToJSON: typeof formToJSON;
getAdapter: typeof getAdapter;
CanceledError: typeof CanceledError;
AxiosHeaders: typeof AxiosHeaders;
isCancel(value: any): boolean;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError(payload: any): payload is AxiosError;
}
declare const axios: AxiosStatic;

44
node_modules/axios/index.js generated vendored
View File

@ -1,43 +1 @@
import axios from './lib/axios.js';
// This module is intended to unwrap Axios default export as named.
// Keep top-level export same with static properties
// so that it can keep same with es module or cjs
const {
Axios,
AxiosError,
CanceledError,
isCancel,
CancelToken,
VERSION,
all,
Cancel,
isAxiosError,
spread,
toFormData,
AxiosHeaders,
HttpStatusCode,
formToJSON,
getAdapter,
mergeConfig
} = axios;
export {
axios as default,
Axios,
AxiosError,
CanceledError,
isCancel,
CancelToken,
VERSION,
all,
Cancel,
isAxiosError,
spread,
toFormData,
AxiosHeaders,
HttpStatusCode,
formToJSON,
getAdapter,
mergeConfig
}
module.exports = require('./lib/axios');

View File

@ -1,77 +0,0 @@
import utils from '../utils.js';
import httpAdapter from './http.js';
import xhrAdapter from './xhr.js';
import AxiosError from "../core/AxiosError.js";
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter
}
utils.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
Object.defineProperty(fn, 'name', {value});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {value});
}
});
const renderReason = (reason) => `- ${reason}`;
const isResolvedHandle = (adapter) => utils.isFunction(adapter) || adapter === null || adapter === false;
export default {
getAdapter: (adapters) => {
adapters = utils.isArray(adapters) ? adapters : [adapters];
const {length} = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
}
if (adapter) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons)
.map(([id, state]) => `adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
let s = length ?
(reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) :
'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
'ERR_NOT_SUPPORT'
);
}
return adapter;
},
adapters: knownAdapters
}

View File

@ -1,316 +1,73 @@
'use strict';
import utils from './../utils.js';
import settle from './../core/settle.js';
import buildFullPath from '../core/buildFullPath.js';
import buildURL from './../helpers/buildURL.js';
import {getProxyForUrl} from 'proxy-from-env';
import http from 'http';
import https from 'https';
import util from 'util';
import followRedirects from 'follow-redirects';
import zlib from 'zlib';
import {VERSION} from '../env/data.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import platform from '../platform/index.js';
import fromDataURI from '../helpers/fromDataURI.js';
import stream from 'stream';
import AxiosHeaders from '../core/AxiosHeaders.js';
import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
import EventEmitter from 'events';
import formDataToStream from "../helpers/formDataToStream.js";
import readBlob from "../helpers/readBlob.js";
import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
import callbackify from "../helpers/callbackify.js";
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');
const zlibOptions = {
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
};
const brotliOptions = {
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
}
const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
const {http: httpFollow, https: httpsFollow} = followRedirects;
const isHttps = /https:?/;
const supportedProtocols = platform.protocols.map(protocol => {
return protocol + ':';
});
var isHttps = /https:?/;
/**
* If the proxy or config beforeRedirects functions are defined, call them with the options
* object.
*
* @param {Object<string, any>} options - The options object that was passed to the request.
*
* @returns {Object<string, any>}
*/
function dispatchBeforeRedirect(options, responseDetails) {
if (options.beforeRedirects.proxy) {
options.beforeRedirects.proxy(options);
}
if (options.beforeRedirects.config) {
options.beforeRedirects.config(options, responseDetails);
}
}
/**
* If the proxy or config afterRedirects functions are defined, call them with the options
*
* @param {http.ClientRequestArgs} options
* @param {AxiosProxyConfig} configProxy configuration from Axios options object
* @param {AxiosProxyConfig} proxy
* @param {string} location
*
* @returns {http.ClientRequestArgs}
*/
function setProxy(options, configProxy, location) {
let proxy = configProxy;
if (!proxy && proxy !== false) {
const proxyUrl = getProxyForUrl(location);
if (proxyUrl) {
proxy = new URL(proxyUrl);
}
}
if (proxy) {
// Basic proxy authorization
if (proxy.username) {
proxy.auth = (proxy.username || '') + ':' + (proxy.password || '');
}
function setProxy(options, proxy, location) {
options.hostname = proxy.host;
options.host = proxy.host;
options.port = proxy.port;
options.path = location;
// Basic proxy authorization
if (proxy.auth) {
// Support proxy auth object form
if (proxy.auth.username || proxy.auth.password) {
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
}
const base64 = Buffer
.from(proxy.auth, 'utf8')
.toString('base64');
var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
const proxyHost = proxy.hostname || proxy.host;
options.hostname = proxyHost;
// Replace 'host' since options is not a URL object
options.host = proxyHost;
options.port = proxy.port;
options.path = location;
if (proxy.protocol) {
options.protocol = proxy.protocol.includes(':') ? proxy.protocol : `${proxy.protocol}:`;
}
}
options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
// Configure proxy for redirected request, passing the original config proxy to apply
// the exact same logic as if the redirected request was performed by axios directly.
setProxy(redirectOptions, configProxy, redirectOptions.href);
// If a proxy is used, any redirects must also pass through the proxy
options.beforeRedirect = function beforeRedirect(redirection) {
redirection.headers.host = redirection.host;
setProxy(redirection, proxy, redirection.href);
};
}
const isHttpAdapterSupported = typeof process !== 'undefined' && utils.kindOf(process) === 'process';
// temporary hotfix
const wrapAsync = (asyncExecutor) => {
return new Promise((resolve, reject) => {
let onDone;
let isDone;
const done = (value, isRejected) => {
if (isDone) return;
isDone = true;
onDone && onDone(value, isRejected);
}
const _resolve = (value) => {
done(value);
resolve(value);
};
const _reject = (reason) => {
done(reason, true);
reject(reason);
}
asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
})
};
const resolveFamily = ({address, family}) => {
if (!utils.isString(address)) {
throw TypeError('address must be a string');
}
return ({
address,
family: family || (address.indexOf('.') < 0 ? 6 : 4)
});
}
const buildAddressEntry = (address, family) => resolveFamily(utils.isObject(address) ? address : {address, family});
/*eslint consistent-return:0*/
export default isHttpAdapterSupported && function httpAdapter(config) {
return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
let {data, lookup, family} = config;
const {responseType, responseEncoding} = config;
const method = config.method.toUpperCase();
let isDone;
let rejected = false;
let req;
if (lookup) {
const _lookup = callbackify(lookup, (value) => utils.isArray(value) ? value : [value]);
// hotfix to support opt.all option which is required for node 20.x
lookup = (hostname, opt, cb) => {
_lookup(hostname, opt, (err, arg0, arg1) => {
if (err) {
return cb(err);
}
const addresses = utils.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
});
}
}
// temporary internal emitter until the AxiosRequest class will be implemented
const emitter = new EventEmitter();
const onFinished = () => {
if (config.cancelToken) {
config.cancelToken.unsubscribe(abort);
}
if (config.signal) {
config.signal.removeEventListener('abort', abort);
}
emitter.removeAllListeners();
}
onDone((value, isRejected) => {
isDone = true;
if (isRejected) {
rejected = true;
onFinished();
}
});
function abort(reason) {
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
}
emitter.once('abort', reject);
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
}
}
// Parse url
const fullPath = buildFullPath(config.baseURL, config.url);
const parsed = new URL(fullPath, 'http://localhost');
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
let convertedData;
if (method !== 'GET') {
return settle(resolve, reject, {
status: 405,
statusText: 'method not allowed',
headers: {},
config
});
}
try {
convertedData = fromDataURI(config.url, responseType === 'blob', {
Blob: config.env && config.env.Blob
});
} catch (err) {
throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
}
if (responseType === 'text') {
convertedData = convertedData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
convertedData = utils.stripBOM(convertedData);
}
} else if (responseType === 'stream') {
convertedData = stream.Readable.from(convertedData);
}
return settle(resolve, reject, {
data: convertedData,
status: 200,
statusText: 'OK',
headers: new AxiosHeaders(),
config
});
}
if (supportedProtocols.indexOf(protocol) === -1) {
return reject(new AxiosError(
'Unsupported protocol ' + protocol,
AxiosError.ERR_BAD_REQUEST,
config
));
}
const headers = AxiosHeaders.from(config.headers).normalize();
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)
// See https://github.com/axios/axios/issues/69
if ('User-Agent' in headers || 'user-agent' in headers) {
// User-Agent is specified; handle case where no UA header is desired
if (!headers['User-Agent'] && !headers['user-agent']) {
delete headers['User-Agent'];
delete headers['user-agent'];
}
// Otherwise, use specified value
} else {
// Only set header if it hasn't been set in config
headers.set('User-Agent', 'axios/' + VERSION, false);
const onDownloadProgress = config.onDownloadProgress;
const onUploadProgress = config.onUploadProgress;
const maxRate = config.maxRate;
let maxUploadRate = undefined;
let maxDownloadRate = undefined;
// support for spec compliant FormData objects
if (utils.isSpecCompliantForm(data)) {
const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
data = formDataToStream(data, (formHeaders) => {
headers.set(formHeaders);
}, {
tag: `axios-${VERSION}-boundary`,
boundary: userBoundary && userBoundary[1] || undefined
});
// support for https://www.npmjs.com/package/form-data api
} else if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
headers.set(data.getHeaders());
if (!headers.hasContentLength()) {
try {
const knownLength = await util.promisify(data.getLength).call(data);
Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
/*eslint no-empty:0*/
} catch (e) {
headers['User-Agent'] = 'axios/' + pkg.version;
}
}
} else if (utils.isBlob(data)) {
data.size && headers.setContentType(data.type || 'application/octet-stream');
headers.setContentLength(data.size || 0);
data = stream.Readable.from(readBlob(data));
} else if (data && !utils.isStream(data)) {
if (data && !utils.isStream(data)) {
if (Buffer.isBuffer(data)) {
// Nothing to do...
} else if (utils.isArrayBuffer(data)) {
@ -318,314 +75,218 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
} else if (utils.isString(data)) {
data = Buffer.from(data, 'utf-8');
} else {
return reject(new AxiosError(
return reject(createError(
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
AxiosError.ERR_BAD_REQUEST,
config
));
}
// Add Content-Length header if data exists
headers.setContentLength(data.length, false);
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
return reject(new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config
));
}
}
const contentLength = utils.toFiniteNumber(headers.getContentLength());
if (utils.isArray(maxRate)) {
maxUploadRate = maxRate[0];
maxDownloadRate = maxRate[1];
} else {
maxUploadRate = maxDownloadRate = maxRate;
}
if (data && (onUploadProgress || maxUploadRate)) {
if (!utils.isStream(data)) {
data = stream.Readable.from(data, {objectMode: false});
}
data = stream.pipeline([data, new AxiosTransformStream({
length: contentLength,
maxRate: utils.toFiniteNumber(maxUploadRate)
})], utils.noop);
onUploadProgress && data.on('progress', progress => {
onUploadProgress(Object.assign(progress, {
upload: true
}));
});
headers['Content-Length'] = data.length;
}
// HTTP basic authentication
let auth = undefined;
var auth = undefined;
if (config.auth) {
const username = config.auth.username || '';
const password = config.auth.password || '';
var username = config.auth.username || '';
var password = config.auth.password || '';
auth = username + ':' + password;
}
if (!auth && parsed.username) {
const urlUsername = parsed.username;
const urlPassword = parsed.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;
}
auth && headers.delete('authorization');
let path;
try {
path = buildURL(
parsed.pathname + parsed.search,
config.params,
config.paramsSerializer
).replace(/^\?/, '');
} catch (err) {
const customErr = new Error(err.message);
customErr.config = config;
customErr.url = config.url;
customErr.exists = true;
return reject(customErr);
if (auth) {
delete headers.Authorization;
}
headers.set(
'Accept-Encoding',
'gzip, compress, deflate' + (isBrotliSupported ? ', br' : ''), false
);
var isHttpsRequest = isHttps.test(protocol);
var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
const options = {
path,
method: method,
headers: headers.toJSON(),
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,
protocol,
family,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: {}
auth: auth
};
// cacheable-lookup integration hotfix
!utils.isUndefined(lookup) && (options.lookup = lookup);
if (config.socketPath) {
options.socketPath = config.socketPath;
} else {
options.hostname = parsed.hostname;
options.port = parsed.port;
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
let transport;
const isHttpsRequest = isHttps.test(options.protocol);
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
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,
protocol: parsedProxyUrl.protocol
};
if (parsedProxyUrl.auth) {
var proxyUrlAuth = parsedProxyUrl.auth.split(':');
proxy.auth = {
username: proxyUrlAuth[0],
password: proxyUrlAuth[1]
};
}
}
}
}
if (proxy) {
options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');
setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
var transport;
var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);
if (config.transport) {
transport = config.transport;
} else if (config.maxRedirects === 0) {
transport = isHttpsRequest ? https : http;
transport = isHttpsProxy ? https : http;
} else {
if (config.maxRedirects) {
options.maxRedirects = config.maxRedirects;
}
if (config.beforeRedirect) {
options.beforeRedirects.config = config.beforeRedirect;
}
transport = isHttpsRequest ? httpsFollow : httpFollow;
transport = isHttpsProxy ? httpsFollow : httpFollow;
}
if (config.maxBodyLength > -1) {
options.maxBodyLength = config.maxBodyLength;
} else {
// follow-redirects does not skip comparison, so it should always succeed for axios -1 unlimited
options.maxBodyLength = Infinity;
}
if (config.insecureHTTPParser) {
options.insecureHTTPParser = config.insecureHTTPParser;
}
// Create the request
req = transport.request(options, function handleResponse(res) {
if (req.destroyed) return;
var req = transport.request(options, function handleResponse(res) {
if (req.aborted) return;
const streams = [res];
const responseLength = +res.headers['content-length'];
if (onDownloadProgress) {
const transformStream = new AxiosTransformStream({
length: utils.toFiniteNumber(responseLength),
maxRate: utils.toFiniteNumber(maxDownloadRate)
});
onDownloadProgress && transformStream.on('progress', progress => {
onDownloadProgress(Object.assign(progress, {
download: true
}));
});
streams.push(transformStream);
}
// decompress the response body transparently if required
let responseStream = res;
// uncompress the response body transparently if required
var stream = res;
// return the last request in case of redirects
const lastRequest = res.req || req;
var lastRequest = res.req || req;
// if decompress disabled we should not decompress
if (config.decompress !== false && res.headers['content-encoding']) {
// if no content, but headers still say that it is encoded,
// remove the header not confuse downstream operations
if (method === 'HEAD' || res.statusCode === 204) {
delete res.headers['content-encoding'];
}
switch ((res.headers['content-encoding'] || '').toLowerCase()) {
// if no content, is HEAD request or decompress disabled we should not decompress
if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {
switch (res.headers['content-encoding']) {
/*eslint default-case:0*/
case 'gzip':
case 'x-gzip':
case 'compress':
case 'x-compress':
// add the unzipper to the body stream processing pipeline
streams.push(zlib.createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'deflate':
streams.push(new ZlibHeaderTransformStream());
// add the unzipper to the body stream processing pipeline
streams.push(zlib.createUnzip(zlibOptions));
stream = stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'br':
if (isBrotliSupported) {
streams.push(zlib.createBrotliDecompress(brotliOptions));
delete res.headers['content-encoding'];
}
}
}
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
const offListeners = stream.finished(responseStream, () => {
offListeners();
onFinished();
});
const response = {
var response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: new AxiosHeaders(res.headers),
config,
headers: res.headers,
config: config,
request: lastRequest
};
if (responseType === 'stream') {
response.data = responseStream;
if (config.responseType === 'stream') {
response.data = stream;
settle(resolve, reject, response);
} else {
const responseBuffer = [];
let totalResponseBytes = 0;
responseStream.on('data', function handleStreamData(chunk) {
var responseBuffer = [];
var totalResponseBytes = 0;
stream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
// make sure the content length is not over the maxContentLength if specified
if (config.maxContentLength > -1 && totalResponseBytes > config.maxContentLength) {
// stream.destroy() emit aborted event before calling reject() on Node.js v16
rejected = true;
responseStream.destroy();
reject(new AxiosError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
stream.destroy();
reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',
config, null, lastRequest));
}
});
responseStream.on('aborted', function handlerStreamAborted() {
if (rejected) {
return;
}
const err = new AxiosError(
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
);
responseStream.destroy(err);
reject(err);
stream.on('error', function handleStreamError(err) {
if (req.aborted) return;
reject(enhanceError(err, config, null, lastRequest));
});
responseStream.on('error', function handleStreamError(err) {
if (req.destroyed) return;
reject(AxiosError.from(err, null, config, lastRequest));
});
responseStream.on('end', function handleStreamEnd() {
try {
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (responseType !== 'arraybuffer') {
responseData = responseData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
stream.on('end', function handleStreamEnd() {
var responseData = Buffer.concat(responseBuffer);
if (config.responseType !== 'arraybuffer') {
responseData = responseData.toString(config.responseEncoding);
if (!config.responseEncoding || config.responseEncoding === 'utf8') {
responseData = utils.stripBOM(responseData);
}
}
response.data = responseData;
} catch (err) {
return reject(AxiosError.from(err, null, config, response.request, response));
}
settle(resolve, reject, response);
});
}
emitter.once('abort', err => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
}
});
});
emitter.once('abort', err => {
reject(err);
req.destroy(err);
});
// Handle errors
req.on('error', function handleRequestError(err) {
// @todo remove
// if (req.aborted && err.code !== AxiosError.ERR_FR_TOO_MANY_REDIRECTS) return;
reject(AxiosError.from(err, null, config, req));
});
// set tcp keep alive to prevent drop connection by peer
req.on('socket', function handleRequestSocket(socket) {
// default interval of sending ack packet is 1 minute
socket.setKeepAlive(true, 1000 * 60);
if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;
reject(enhanceError(err, config, null, req));
});
// Handle request timeout
if (config.timeout) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
const timeout = parseInt(config.timeout, 10);
var timeout = parseInt(config.timeout, 10);
if (Number.isNaN(timeout)) {
reject(new AxiosError(
if (isNaN(timeout)) {
reject(createError(
'error trying to parse `config.timeout` to int',
AxiosError.ERR_BAD_OPTION_VALUE,
config,
'ERR_PARSE_TIMEOUT',
req
));
@ -635,51 +296,36 @@ export default isHttpAdapterSupported && function httpAdapter(config) {
// 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 devouring CPU little by little.
// 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(timeout, function handleRequestTimeout() {
if (isDone) return;
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
req.abort();
reject(createError(
'timeout of ' + timeout + 'ms exceeded',
config,
config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
req
));
abort();
});
}
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)) {
let ended = false;
let errored = false;
data.on('end', () => {
ended = true;
});
data.once('error', err => {
errored = true;
req.destroy(err);
});
data.on('close', () => {
if (!ended && !errored) {
abort(new CanceledError('Request stream has been aborted', config, req));
}
});
data.pipe(req);
data.on('error', function handleStreamError(err) {
reject(enhanceError(err, config, null, req));
}).pipe(req);
} else {
req.end(data);
}
});
}
export const __setProxy = setProxy;
};

View File

@ -1,89 +1,34 @@
'use strict';
import utils from './../utils.js';
import settle from './../core/settle.js';
import cookies from './../helpers/cookies.js';
import buildURL from './../helpers/buildURL.js';
import buildFullPath from '../core/buildFullPath.js';
import isURLSameOrigin from './../helpers/isURLSameOrigin.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import parseProtocol from '../helpers/parseProtocol.js';
import platform from '../platform/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import speedometer from '../helpers/speedometer.js';
var utils = require('./../utils');
var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
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');
function progressEventReducer(listener, isDownloadStream) {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined,
event: e
};
data[isDownloadStream ? 'download' : 'upload'] = true;
listener(data);
};
}
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
export default isXHRAdapterSupported && function (config) {
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
let requestData = config.data;
const requestHeaders = AxiosHeaders.from(config.headers).normalize();
let {responseType, withXSRFToken} = config;
let onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
}
let contentType;
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
if (utils.isFormData(requestData)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv) {
requestHeaders.setContentType(false); // Let the browser set it
} else if ((contentType = requestHeaders.getContentType()) !== false) {
// fix semicolon duplication issue for ReactNative FormData implementation
const [type, ...tokens] = contentType ? contentType.split(';').map(token => token.trim()).filter(Boolean) : [];
requestHeaders.setContentType([type || 'multipart/form-data', ...tokens].join('; '));
}
delete requestHeaders['Content-Type']; // Let the browser set it
}
let request = new XMLHttpRequest();
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
const username = config.auth.username || '';
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
const fullPath = buildFullPath(config.baseURL, config.url);
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
@ -94,27 +39,19 @@ export default isXHRAdapterSupported && function (config) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
const response = {
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
settle(resolve, reject, response);
// Clean up request
request = null;
@ -149,7 +86,7 @@ export default isXHRAdapterSupported && function (config) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
@ -159,7 +96,7 @@ export default isXHRAdapterSupported && function (config) {
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request));
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
@ -167,15 +104,14 @@ export default isXHRAdapterSupported && function (config) {
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(new AxiosError(
reject(createError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',
request));
// Clean up request
@ -185,26 +121,27 @@ export default isXHRAdapterSupported && function (config) {
// 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(platform.hasStandardBrowserEnv) {
withXSRFToken && utils.isFunction(withXSRFToken) && (withXSRFToken = withXSRFToken(config));
if (withXSRFToken || (withXSRFToken !== false && isURLSameOrigin(fullPath))) {
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
const xsrfValue = config.xsrfHeaderName && config.xsrfCookieName && cookies.read(config.xsrfCookieName);
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
}
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
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);
}
});
}
@ -220,41 +157,33 @@ export default isXHRAdapterSupported && function (config) {
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken || config.signal) {
if (config.cancelToken) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = cancel => {
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
reject(cancel);
// Clean up request
request = null;
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(fullPath);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
return;
}
// Send the request
request.send(requestData || null);
});
}
if (!requestData) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};

81
node_modules/axios/lib/axios.js generated vendored
View File

@ -1,89 +1,56 @@
'use strict';
import utils from './utils.js';
import bind from './helpers/bind.js';
import Axios from './core/Axios.js';
import mergeConfig from './core/mergeConfig.js';
import defaults from './defaults/index.js';
import formDataToJSON from './helpers/formDataToJSON.js';
import CanceledError from './cancel/CanceledError.js';
import CancelToken from './cancel/CancelToken.js';
import isCancel from './cancel/isCancel.js';
import {VERSION} from './env/data.js';
import toFormData from './helpers/toFormData.js';
import AxiosError from './core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';
import AxiosHeaders from "./core/AxiosHeaders.js";
import adapters from './adapters/adapters.js';
import HttpStatusCode from './helpers/HttpStatusCode.js';
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
*
* @returns {Axios} A new instance of Axios
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios(defaultConfig);
const instance = bind(Axios.prototype.request, context);
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context, null, {allOwnKeys: true});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults);
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.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
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 = spread;
axios.spread = require('./helpers/spread');
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
axios.isAxiosError = require('./helpers/isAxiosError');
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
module.exports = axios;
axios.AxiosHeaders = AxiosHeaders;
axios.formToJSON = thing => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode;
axios.default = axios;
// this module should only have a default export
export default axios
// Allow use of default import syntax in TypeScript
module.exports.default = axios;

View File

@ -1,121 +1,57 @@
'use strict';
import CanceledError from './CanceledError.js';
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.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then(cancel => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = onfulfilled => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise(resolve => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
* Throws a `Cancel` if cancellation has been requested.
*/
throwIfRequested() {
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
token: token,
cancel: cancel
};
};
}
}
export default CancelToken;
module.exports = CancelToken;

View File

@ -1,25 +0,0 @@
'use strict';
import AxiosError from '../core/AxiosError.js';
import utils from '../utils.js';
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
function CanceledError(message, config, request) {
// eslint-disable-next-line no-eq-null,eqeqeq
AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
}
utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
export default CanceledError;

View File

@ -1,5 +1,5 @@
'use strict';
export default function isCancel(value) {
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
}
};

189
node_modules/axios/lib/core/Axios.js generated vendored
View File

@ -1,25 +1,19 @@
'use strict';
import utils from './../utils.js';
import buildURL from '../helpers/buildURL.js';
import InterceptorManager from './InterceptorManager.js';
import dispatchRequest from './dispatchRequest.js';
import mergeConfig from './mergeConfig.js';
import buildFullPath from './buildFullPath.js';
import validator from '../helpers/validator.js';
import AxiosHeaders from './AxiosHeaders.js';
const validators = validator.validators;
var utils = require('./../utils');
var buildURL = require('../helpers/buildURL');
var InterceptorManager = require('./InterceptorManager');
var dispatchRequest = require('./dispatchRequest');
var mergeConfig = require('./mergeConfig');
var validator = require('../helpers/validator');
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
@ -30,91 +24,42 @@ class Axios {
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy;
Error.captureStackTrace ? Error.captureStackTrace(dummy = {}) : (dummy = new Error());
// slice off the Error: ... line
const stack = dummy.stack ? dummy.stack.replace(/^.+\n/, '') : '';
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack && !String(err.stack).endsWith(stack.replace(/^.+\n.+\n/, ''))) {
err.stack += '\n' + stack
}
}
throw err;
}
}
_request(configOrUrl, config) {
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = configOrUrl || {};
config = config || {};
}
config = mergeConfig(this.defaults, config);
const {transitional, paramsSerializer, headers} = 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';
}
var transitional = config.transitional;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean)
silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'),
forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'),
clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0')
}, false);
}
if (paramsSerializer != null) {
if (utils.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
}
} else {
validator.assertOptions(paramsSerializer, {
encode: validators.function,
serialize: validators.function
}, true);
}
}
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils.merge(
headers.common,
headers[config.method]
);
headers && utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
(method) => {
delete headers[method];
}
);
config.headers = AxiosHeaders.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
@ -125,77 +70,65 @@ class Axios {
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
});
const responseInterceptorChain = [];
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
var promise;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift.apply(chain, requestInterceptorChain);
chain.push.apply(chain, responseInterceptorChain);
len = chain.length;
var chain = [dispatchRequest, undefined];
Array.prototype.unshift.apply(chain, requestInterceptorChain);
chain = chain.concat(responseInterceptorChain);
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
i = 0;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
var newConfig = config;
while (requestInterceptorChain.length) {
var onFulfilled = requestInterceptorChain.shift();
var onRejected = requestInterceptorChain.shift();
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
onRejected(error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
promise = dispatchRequest(newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
while (responseInterceptorChain.length) {
promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());
}
return promise;
}
};
getUri(config) {
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
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(mergeConfig(config || {}, {
method,
url,
method: method,
url: url,
data: (config || {}).data
}));
};
@ -203,23 +136,13 @@ utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
Axios.prototype[method] = function(url, data, config) {
return this.request(mergeConfig(config || {}, {
method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url,
data
method: method,
url: url,
data: data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
});
export default Axios;
module.exports = Axios;

View File

@ -1,100 +0,0 @@
'use strict';
import utils from '../utils.js';
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
Error.call(this);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = (new Error()).stack;
}
this.message = message;
this.name = 'AxiosError';
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
response && (this.response = response);
}
utils.inherits(AxiosError, Error, {
toJSON: function toJSON() {
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: utils.toJSONObject(this.config),
code: this.code,
status: this.response && this.response.status ? this.response.status : null
};
}
});
const prototype = AxiosError.prototype;
const descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
'ERR_BAD_OPTION',
'ECONNABORTED',
'ETIMEDOUT',
'ERR_NETWORK',
'ERR_FR_TOO_MANY_REDIRECTS',
'ERR_DEPRECATED',
'ERR_BAD_RESPONSE',
'ERR_BAD_REQUEST',
'ERR_CANCELED',
'ERR_NOT_SUPPORT',
'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(code => {
descriptors[code] = {value: code};
});
Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
}, prop => {
return prop !== 'isAxiosError';
});
AxiosError.call(axiosError, error.message, code, config, request, response);
axiosError.cause = error;
axiosError.name = error.name;
customProps && Object.assign(axiosError, customProps);
return axiosError;
};
export default AxiosError;

View File

@ -1,298 +0,0 @@
'use strict';
import utils from '../utils.js';
import parseHeaders from '../helpers/parseHeaders.js';
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils.isArray(value) ? value.map(normalizeValue) : String(value);
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils.isString(value)) return;
if (utils.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim()
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error('header name must be a non-empty string');
}
const key = utils.findKey(self, lHeader);
if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite)
} else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils.findKey(this, header);
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils.forEach(this, (value, header) => {
const key = utils.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils.forEach(this, (value, header) => {
value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = (this[$internals] = {
accessors: {}
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
// reserved names hotfix
utils.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
}
}
});
utils.freezeMethods(AxiosHeaders);
export default AxiosHeaders;

View File

@ -1,9 +1,8 @@
'use strict';
import utils from './../utils.js';
var utils = require('./../utils');
class InterceptorManager {
constructor() {
function InterceptorManager() {
this.handlers = [];
}
@ -15,39 +14,26 @@ class InterceptorManager {
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
InterceptorManager.prototype.use = function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(id) {
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
};
/**
* Iterate over all the registered interceptors
@ -56,16 +42,13 @@ class InterceptorManager {
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
};
export default InterceptorManager;
module.exports = InterceptorManager;

View File

@ -1,7 +1,7 @@
'use strict';
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
import combineURLs from '../helpers/combineURLs.js';
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');
/**
* Creates a new URL by combining the baseURL with the requestedURL,
@ -10,12 +10,11 @@ import combineURLs from '../helpers/combineURLs.js';
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
export default function buildFullPath(baseURL, requestedURL) {
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
};

View File

@ -1,52 +1,54 @@
'use strict';
import transformData from './transformData.js';
import isCancel from '../cancel/isCancel.js';
import defaults from '../defaults/index.js';
import CanceledError from '../cancel/CanceledError.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import adapters from "../adapters/adapters.js";
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* 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
*/
export default function dispatchRequest(config) {
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders.from(config.headers);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
config.transformRequest
);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
const adapter = adapters.getAdapter(config.adapter || defaults.adapter);
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);
@ -54,12 +56,11 @@ export default function dispatchRequest(config) {
// Transform response data
response.data = transformData.call(
config,
config.transformResponse,
response
response.data,
response.headers,
config.transformResponse
);
response.headers = AxiosHeaders.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
@ -69,13 +70,13 @@ export default function dispatchRequest(config) {
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
reason.response.data,
reason.response.headers,
config.transformResponse
);
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
};

View File

@ -1,9 +1,6 @@
'use strict';
import utils from '../utils.js';
import AxiosHeaders from "./AxiosHeaders.js";
const headersToObject = (thing) => thing instanceof AxiosHeaders ? thing.toJSON() : thing;
var utils = require('../utils');
/**
* Config-specific merge-function which creates a new config-object
@ -11,17 +8,27 @@ const headersToObject = (thing) => thing instanceof AxiosHeaders ? thing.toJSON(
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
export default function mergeConfig(config1, config2) {
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
const config = {};
var config = {};
function getMergedValue(target, source, caseless) {
var valueFromConfig2Keys = ['url', 'method', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];
var defaultToConfig2Keys = [
'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',
'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'
];
var directMergeKeys = ['validateStatus'];
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge.call({caseless}, target, source);
return utils.merge(target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
@ -30,77 +37,51 @@ export default function mergeConfig(config1, config2) {
return source;
}
// eslint-disable-next-line consistent-return
function mergeDeepProperties(a, b, caseless) {
if (!utils.isUndefined(b)) {
return getMergedValue(a, b, caseless);
} else if (!utils.isUndefined(a)) {
return getMergedValue(undefined, a, caseless);
function mergeDeepProperties(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils.isUndefined(b)) {
return getMergedValue(undefined, b);
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (prop in config2) {
return getMergedValue(a, b);
} else if (prop in config1) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b) => mergeDeepProperties(headersToObject(a), headersToObject(b), true)
};
utils.forEach(Object.keys(Object.assign({}, config1, config2)), function computeConfigValue(prop) {
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(config1[prop], config2[prop], prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (!utils.isUndefined(config2[prop])) {
config[prop] = getMergedValue(undefined, config2[prop]);
} else if (!utils.isUndefined(config1[prop])) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
utils.forEach(directMergeKeys, function merge(prop) {
if (prop in config2) {
config[prop] = getMergedValue(config1[prop], config2[prop]);
} else if (prop in config1) {
config[prop] = getMergedValue(undefined, config1[prop]);
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys)
.concat(directMergeKeys);
var otherKeys = Object
.keys(config1)
.concat(Object.keys(config2))
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, mergeDeepProperties);
return config;
};

View File

@ -1,6 +1,6 @@
'use strict';
import AxiosError from './AxiosError.js';
var createError = require('./createError');
/**
* Resolve or reject a Promise based on response status.
@ -8,20 +8,18 @@ import AxiosError from './AxiosError.js';
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
export default function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
reject(createError(
'Request failed with status code ' + response.status,
[AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],
response.config,
null,
response.request,
response
));
}
}
};

View File

@ -1,28 +1,22 @@
'use strict';
import utils from './../utils.js';
import defaults from '../defaults/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
var utils = require('./../utils');
var defaults = require('./../defaults');
/**
* 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
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
export default function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders.from(context.headers);
let data = context.data;
module.exports = function transformData(data, headers, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
data = fn.call(context, data, headers);
});
headers.normalize();
return data;
}
};

View File

@ -1,156 +0,0 @@
'use strict';
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import transitionalDefaults from './transitional.js';
import toFormData from '../helpers/toFormData.js';
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
import platform from '../platform/index.js';
import formDataToJSON from '../helpers/formDataToJSON.js';
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http'],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils.isObject(data);
if (isObjectPayload && utils.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (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)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
const _FormData = this.env && this.env.FormData;
return toFormData(
isFileList ? {'files[]': data} : data,
_FormData && new _FormData(),
this.formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType ) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);
}
throw e;
}
}
}
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,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': undefined
}
}
};
utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch'], (method) => {
defaults.headers[method] = {};
});
export default defaults;

View File

@ -1,7 +0,0 @@
'use strict';
export default {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false
};

View File

@ -1,3 +0,0 @@
# axios // env
The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually.

View File

@ -1,2 +0,0 @@
import _FormData from 'form-data';
export default typeof FormData !== 'undefined' ? FormData : _FormData;

1
node_modules/axios/lib/env/data.js generated vendored
View File

@ -1 +0,0 @@
export const VERSION = "1.6.7";

View File

@ -1,191 +0,0 @@
'use strict';
import stream from 'stream';
import utils from '../utils.js';
import throttle from './throttle.js';
import speedometer from './speedometer.js';
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream.Transform{
constructor(options) {
options = utils.toFlatObject(options, {
maxRate: 0,
chunkSize: 64 * 1024,
minChunkSize: 100,
timeWindow: 500,
ticksRate: 2,
samplesCount: 15
}, null, (prop, source) => {
return !utils.isUndefined(source[prop]);
});
super({
readableHighWaterMark: options.chunkSize
});
const self = this;
const internals = this[kInternals] = {
length: options.length,
timeWindow: options.timeWindow,
ticksRate: options.ticksRate,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
minChunkSize: options.minChunkSize,
bytesSeen: 0,
isCaptured: false,
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null
};
const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
this.on('newListener', event => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
}
}
});
let bytesNotified = 0;
internals.updateProgress = throttle(function throttledHandler() {
const totalBytes = internals.length;
const bytesTransferred = internals.bytesSeen;
const progressBytes = bytesTransferred - bytesNotified;
if (!progressBytes || self.destroyed) return;
const rate = _speedometer(progressBytes);
bytesNotified = bytesTransferred;
process.nextTick(() => {
self.emit('progress', {
'loaded': bytesTransferred,
'total': totalBytes,
'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined,
'bytes': progressBytes,
'rate': rate ? rate : undefined,
'estimated': rate && totalBytes && bytesTransferred <= totalBytes ?
(totalBytes - bytesTransferred) / rate : undefined
});
});
}, internals.ticksRate);
const onFinish = () => {
internals.updateProgress(true);
};
this.once('end', onFinish);
this.once('error', onFinish);
}
_read(size) {
const internals = this[kInternals];
if (internals.onReadCallback) {
internals.onReadCallback();
}
return super._read(size);
}
_transform(chunk, encoding, callback) {
const self = this;
const internals = this[kInternals];
const maxRate = internals.maxRate;
const readableHighWaterMark = this.readableHighWaterMark;
const timeWindow = internals.timeWindow;
const divider = 1000 / timeWindow;
const bytesThreshold = (maxRate / divider);
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
function pushChunk(_chunk, _callback) {
const bytes = Buffer.byteLength(_chunk);
internals.bytesSeen += bytes;
internals.bytes += bytes;
if (internals.isCaptured) {
internals.updateProgress();
}
if (self.push(_chunk)) {
process.nextTick(_callback);
} else {
internals.onReadCallback = () => {
internals.onReadCallback = null;
process.nextTick(_callback);
};
}
}
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
let chunkRemainder = null;
let maxChunkSize = readableHighWaterMark;
let bytesLeft;
let passed = 0;
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
passed = 0;
}
bytesLeft = bytesThreshold - internals.bytes;
}
if (maxRate) {
if (bytesLeft <= 0) {
// next time window
return setTimeout(() => {
_callback(null, _chunk);
}, timeWindow - passed);
}
if (bytesLeft < maxChunkSize) {
maxChunkSize = bytesLeft;
}
}
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
chunkRemainder = _chunk.subarray(maxChunkSize);
_chunk = _chunk.subarray(0, maxChunkSize);
}
pushChunk(_chunk, chunkRemainder ? () => {
process.nextTick(_callback, null, chunkRemainder);
} : _callback);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {
if (err) {
return callback(err);
}
if (_chunk) {
transformChunk(_chunk, transformNextChunk);
} else {
callback(null);
}
});
}
setLength(length) {
this[kInternals].length = +length;
return this;
}
}
export default AxiosTransformStream;

View File

@ -1,58 +0,0 @@
'use strict';
import toFormData from './toFormData.js';
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode);
} : encode;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
};
export default AxiosURLSearchParams;

View File

@ -1,71 +0,0 @@
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
export default HttpStatusCode;

View File

@ -1,28 +0,0 @@
"use strict";
import stream from "stream";
class ZlibHeaderTransformStream extends stream.Transform {
__transform(chunk, encoding, callback) {
this.push(chunk);
callback();
}
_transform(chunk, encoding, callback) {
if (chunk.length !== 0) {
this._transform = this.__transform;
// Add Default Compression headers if no zlib headers are present
if (chunk[0] !== 120) { // Hex: 78
const header = Buffer.alloc(2);
header[0] = 120; // Hex: 78
header[1] = 156; // Hex: 9C
this.push(header, encoding);
}
}
this.__transform(chunk, encoding, callback);
}
}
export default ZlibHeaderTransformStream;

View File

@ -1,7 +1,11 @@
'use strict';
export default function bind(fn, thisArg) {
module.exports = function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};

View File

@ -1,16 +1,7 @@
'use strict';
import utils from '../utils.js';
import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
var utils = require('./../utils');
/**
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
* URI encoded counterparts
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).
replace(/%3A/gi, ':').
@ -26,38 +17,54 @@ function encode(val) {
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?object} options
*
* @returns {string} The formatted url
*/
export default function buildURL(url, params, options) {
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
const _encode = options && options.encode || encode;
const serializeFn = options && options.serialize;
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, options);
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
serializedParams = utils.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, options).toString(_encode);
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) {
const hashmarkIndex = url.indexOf("#");
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
};

View File

@ -1,16 +0,0 @@
import utils from "../utils.js";
const callbackify = (fn, reducer) => {
return utils.isAsyncFn(fn) ? function (...args) {
const cb = args.pop();
fn.apply(this, args).then((value) => {
try {
reducer ? cb(null, ...reducer(value)) : cb(null, value);
} catch (err) {
cb(err);
}
}, cb);
} : fn;
}
export default callbackify;

View File

@ -5,11 +5,10 @@
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
export default function combineURLs(baseURL, relativeURL) {
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
};

View File

@ -1,42 +1,53 @@
import utils from './../utils.js';
import platform from '../platform/index.js';
'use strict';
export default platform.hasStandardBrowserEnv ?
var utils = require('./../utils');
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure) {
const cookie = [name + '=' + encodeURIComponent(value)];
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
utils.isNumber(expires) && cookie.push('expires=' + new Date(expires).toGMTString());
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
utils.isString(path) && cookie.push('path=' + path);
if (utils.isString(path)) {
cookie.push('path=' + path);
}
utils.isString(domain) && cookie.push('domain=' + domain);
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
secure === true && cookie.push('secure');
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove(name) {
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
}
:
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
})() :
// 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() {}
};
})()
);

View File

@ -9,10 +9,8 @@
* @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
*
* @returns {void}
*/
export default function deprecatedMethod(method, instead, docs) {
module.exports = function deprecatedMethod(method, instead, docs) {
try {
console.warn(
'DEPRECATED method `' + method + '`.' +
@ -23,4 +21,4 @@ export default function deprecatedMethod(method, instead, docs) {
console.warn('For more information about usage see ' + docs);
}
} catch (e) { /* Ignore */ }
}
};

View File

@ -1,95 +0,0 @@
'use strict';
import utils from '../utils.js';
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils.isArray(target) ? target.length : name;
if (isLast) {
if (utils.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!target[name] || !utils.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
const obj = {};
utils.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
export default formDataToJSON;

View File

@ -1,111 +0,0 @@
import {TextEncoder} from 'util';
import {Readable} from 'stream';
import utils from "../utils.js";
import readBlob from "./readBlob.js";
const BOUNDARY_ALPHABET = utils.ALPHABET.ALPHA_DIGIT + '-_';
const textEncoder = new TextEncoder();
const CRLF = '\r\n';
const CRLF_BYTES = textEncoder.encode(CRLF);
const CRLF_BYTES_COUNT = 2;
class FormDataPart {
constructor(name, value) {
const {escapeName} = this.constructor;
const isStringValue = utils.isString(value);
let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${
!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''
}${CRLF}`;
if (isStringValue) {
value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
} else {
headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`
}
this.headers = textEncoder.encode(headers + CRLF);
this.contentLength = isStringValue ? value.byteLength : value.size;
this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
this.name = name;
this.value = value;
}
async *encode(){
yield this.headers;
const {value} = this;
if(utils.isTypedArray(value)) {
yield value;
} else {
yield* readBlob(value);
}
yield CRLF_BYTES;
}
static escapeName(name) {
return String(name).replace(/[\r\n"]/g, (match) => ({
'\r' : '%0D',
'\n' : '%0A',
'"' : '%22',
}[match]));
}
}
const formDataToStream = (form, headersHandler, options) => {
const {
tag = 'form-data-boundary',
size = 25,
boundary = tag + '-' + utils.generateString(size, BOUNDARY_ALPHABET)
} = options || {};
if(!utils.isFormData(form)) {
throw TypeError('FormData instance required');
}
if (boundary.length < 1 || boundary.length > 70) {
throw Error('boundary must be 10-70 characters long')
}
const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF + CRLF);
let contentLength = footerBytes.byteLength;
const parts = Array.from(form.entries()).map(([name, value]) => {
const part = new FormDataPart(name, value);
contentLength += part.size;
return part;
});
contentLength += boundaryBytes.byteLength * parts.length;
contentLength = utils.toFiniteNumber(contentLength);
const computedHeaders = {
'Content-Type': `multipart/form-data; boundary=${boundary}`
}
if (Number.isFinite(contentLength)) {
computedHeaders['Content-Length'] = contentLength;
}
headersHandler && headersHandler(computedHeaders);
return Readable.from((async function *() {
for(const part of parts) {
yield boundaryBytes;
yield* part.encode();
}
yield footerBytes;
})());
};
export default formDataToStream;

View File

@ -1,53 +0,0 @@
'use strict';
import AxiosError from '../core/AxiosError.js';
import parseProtocol from './parseProtocol.js';
import platform from '../platform/index.js';
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
/**
* Parse data uri to a Buffer or Blob
*
* @param {String} uri
* @param {?Boolean} asBlob
* @param {?Object} options
* @param {?Function} options.Blob
*
* @returns {Buffer|Blob}
*/
export default function fromDataURI(uri, asBlob, options) {
const _Blob = options && options.Blob || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
asBlob = true;
}
if (protocol === 'data') {
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
const match = DATA_URL_PATTERN.exec(uri);
if (!match) {
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
}
const mime = match[1];
const isBase64 = match[2];
const body = match[3];
const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
if (asBlob) {
if (!_Blob) {
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
}
return new _Blob([buffer], {type: mime});
}
return buffer;
}
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
}

View File

@ -4,12 +4,11 @@
* 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
*/
export default function isAbsoluteURL(url) {
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);
}
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};

View File

@ -1,14 +1,11 @@
'use strict';
import utils from './../utils.js';
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
export default function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
}
module.exports = function isAxiosError(payload) {
return (typeof payload === 'object') && (payload.isAxiosError === true);
};

Some files were not shown because too many files have changed in this diff Show More